Codeanswer
My blog share the my c# knowledge to others and get response from others.
Thursday, March 19, 2020
Tuesday, October 18, 2016
Action Method in Mvc
In this section, you will learn about the action method of controller class.
All the public methods of a Controller class are called Action methods. They are like any other normal methods with the following restrictions:
Action method must be public. It cannot be private or protected
Action method cannot be overloaded
Action method cannot be a static method.
The following is an example of Index action method of StudentController
Action Method in ASP.NET MVC
Action Method
As you can see in the above figure, Index method is a public method and it returns ActionResult using the View() method. The View() method is defined in the Controller base class, which returns the appropriate ActionResult.
Default Action method:
Every controller can have default action method as per configured route in RouteConfig class. By default, Index is a default action method for any controller, as per configured default root as shown below.
Default Route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{name}",
defaults: new { controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
However, you can change the default action name as per your requirement in RouteConfig class.
ActionResult:
MVC framework includes various result classes, which can be return from an action methods. There result classes represent different types of responses such as html, file, string, json, javascript etc. The following table lists all the result classes available in ASP.NET MVC.
The Index() method of StudentController in the above figure uses View() method to return ViewResult (which is derived from ActionResult). The View() method is defined in base Controller class. It also contains different methods, which automatically returns particular type of result as shown in the below table.
Action method Parameters:
Every action methods can have input parameters as normal methods. It can be primitive data type or complex type parameters as shown in the below example.
Example: Action method parameters
[HttpPost]
public ActionResult Edit(Student std)
{
// update student to the database
return RedirectToAction("Index");
}
[HttpDelete]
public ActionResult Delete(int id)
{
// delete student from the database whose id matches with specified id
return RedirectToAction("Index");
}
Action method parameters can be Nullable type.
By default, the values for action method parameters are retrieved from the request's data collection. The data collection includes name/values pairs for form data or query string values or cookie values. Model binding in ASP.NET MVC automatically maps the URL query string or form data collection to the action method parameters if both names are matching. Visit model binding section for more information on it.
All the public methods of a Controller class are called Action methods. They are like any other normal methods with the following restrictions:
Action method must be public. It cannot be private or protected
Action method cannot be overloaded
Action method cannot be a static method.
The following is an example of Index action method of StudentController
Action Method in ASP.NET MVC
Action Method
As you can see in the above figure, Index method is a public method and it returns ActionResult using the View() method. The View() method is defined in the Controller base class, which returns the appropriate ActionResult.
Default Action method:
Every controller can have default action method as per configured route in RouteConfig class. By default, Index is a default action method for any controller, as per configured default root as shown below.
Default Route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{name}",
defaults: new { controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
However, you can change the default action name as per your requirement in RouteConfig class.
ActionResult:
MVC framework includes various result classes, which can be return from an action methods. There result classes represent different types of responses such as html, file, string, json, javascript etc. The following table lists all the result classes available in ASP.NET MVC.
Result Class | Description |
---|---|
ViewResult | Represents HTML and markup. |
EmptyResult | Represents No response. |
ContentResult | Represents string literal. |
FileContentResult/ FilePathResult/ FileStreamResult | Represents the content of a file |
JavaScriptResult | Represent a JavaScript script. |
JsonResult | Represent JSON that can be used in AJAX |
RedirectResult | Represents a redirection to a new URL |
RedirectToRouteResult | Represent another action of same or other controller |
PartialViewResult | Returns HTML from Partial view |
HttpUnauthorizedResult | Returns HTTP 403 status |
The Index() method of StudentController in the above figure uses View() method to return ViewResult (which is derived from ActionResult). The View() method is defined in base Controller class. It also contains different methods, which automatically returns particular type of result as shown in the below table.
Result Class |
Description |
Base Controller method |
---|---|---|
ViewResult | Represents HTML and markup. | View() |
EmptyResult | Represents No response. | |
ContentResult | Represents string literal. | Content() |
FileContentResult, FilePathResult, FileStreamResult |
Represents the content of a file | File() |
JavaScriptResult | Represent a JavaScript script. | JavaScript() |
JsonResult | Represent JSON that can be used in AJAX | Json() |
RedirectResult | Represents a redirection to a new URL | Redirect() |
RedirectToRouteResult | Represent another action of same or other controller | RedirectToRoute() |
PartialViewResult | Returns HTML | PartialView() |
HttpUnauthorizedResult | Returns HTTP 403 status |
Action method Parameters:
Every action methods can have input parameters as normal methods. It can be primitive data type or complex type parameters as shown in the below example.
Example: Action method parameters
[HttpPost]
public ActionResult Edit(Student std)
{
// update student to the database
return RedirectToAction("Index");
}
[HttpDelete]
public ActionResult Delete(int id)
{
// delete student from the database whose id matches with specified id
return RedirectToAction("Index");
}
Action method parameters can be Nullable type.
By default, the values for action method parameters are retrieved from the request's data collection. The data collection includes name/values pairs for form data or query string values or cookie values. Model binding in ASP.NET MVC automatically maps the URL query string or form data collection to the action method parameters if both names are matching. Visit model binding section for more information on it.
ASP.NET MVC Version History
Microsoft had introduced ASP.NET MVC in .Net 3.5, since then lots of new features have been added.
The following table list brief history of ASP.NET MVC.
MVC Version | Visual Studio | .Net Version | Release date | Features |
---|---|---|---|---|
MVC 1.0 | VS2008 | .Net 3.5 | 13-Mar-2009 |
|
MVC 2.0 | VS 2008, | .Net 3.5/4.0 | 10-Mar-2010 |
|
MVC 3.0 | VS 2010 | .Net 4.0 | 13-Jan-2011 |
|
MVC 4.0 | VS 2010 SP1, VS 2012 | .NET 4.0/4.5 | 15-Aug-2012 |
|
MVC 5.0 | VS 2013 | .NET 4.5 | 17-oct-2013 |
|
MVC 5.2 - Current | VS 2013 | .NET 4.5 | 28-Aug-2014 |
|
Thursday, October 13, 2016
Angular Tutorial - Part 1: Introduction to Angular.js
In this article we will look at the basics of Angular.Js. This is the first part of an article series. The main objective of this series is to learn about Angular and see how Angular helps us in developing more flexible, maintainable and testable client side web applications and that too without compromising with the productivity.
Link to complete series
Angular Tutorial - Part 1: Introduction to Angular.js
Angular Tutorial - Part 2: Understanding Modules and Controllers
Angular Tutorial - Part 3: Understanding and using Directives
Angular Tutorial - Part 4: Understanding and implementing Filters
Angular Tutorial - Part 5: Understanding and implementing Services
Angular Tutorial - Part 6: Building and Validating Data Entry Forms
Angular Tutorial - Part 7: Understanding Single page applications and Angular routing
Background
If we take a look back in time and see how our software applications have evolved then we can clearly see how the application development and development model has evolved. Almost two decade ago most software applications were getting built as standalone applications. These applications were targeted at a single user and ran on their operating systems.
Then came the need to share data across multiple users and a need to store data at a central location. This need gave birth to distributed applications. Distributed applications ran as standalone applications on the user’s machine giving him a rich user interface (les call it desktop like experience) to work with, and behind the scenes, these applications sent data to a server.
Read More
Introduction to Angular
Introduction to Angular
So what is Angular, and why would you want to use it? The simplest answer to that question is that Angular is a JavaScript library, but it's so much more than that. It's probably more accurate to categorize it as an MV* framework. Angular isn't just an MV* framework, it's an opinionated MV* framework. What is opinionated software? Well, opinionated software guides you into certain ways of doing things. Opinionated software has a vision. It may limit itself to solving fewer problems, but generally, software with opinions solves those problems with less fuss. That doesn't mean that there isn't more than one way to solve a problem with Angular. For example, take DOM manipulation. Angular wants you to only manipulate your DOM inside of directives, but with Angular, inside of a directive you can use jQuery, Zepto, any other library, or even just raw JavaScript to manipulate your DOM. That doesn't mean that you can't manipulate the DOM from within any other piece of an Angular application, but Angular definitely has an opinion about whether or not you should, and it gently guides you into doing things a certain way.
Let’s make sure that we understand exactly what an MV* framework is.
Read More
So what is Angular, and why would you want to use it? The simplest answer to that question is that Angular is a JavaScript library, but it's so much more than that. It's probably more accurate to categorize it as an MV* framework. Angular isn't just an MV* framework, it's an opinionated MV* framework. What is opinionated software? Well, opinionated software guides you into certain ways of doing things. Opinionated software has a vision. It may limit itself to solving fewer problems, but generally, software with opinions solves those problems with less fuss. That doesn't mean that there isn't more than one way to solve a problem with Angular. For example, take DOM manipulation. Angular wants you to only manipulate your DOM inside of directives, but with Angular, inside of a directive you can use jQuery, Zepto, any other library, or even just raw JavaScript to manipulate your DOM. That doesn't mean that you can't manipulate the DOM from within any other piece of an Angular application, but Angular definitely has an opinion about whether or not you should, and it gently guides you into doing things a certain way.
Let’s make sure that we understand exactly what an MV* framework is.
Read More
TaskTimer, Reducing Your Exposure To The Internet
Introduction
Internet is a great tool, but it often distracts us. This can be said of computer clutter in general--all the icons and files in close proximity make it too easy for us to dart off into an unexpected adventure. TaskTimer is a tool to limit our exposure to the distractions by tempering our access to the internet and by periodically reminding us to focus on a chosen task. It appears as a tray icon and is completely configured in one step by setting a desired nag message, the approximate frequency with which you'd like to see the nag message, and, finally, the target internet adapter (e.g. Wi-Fi) you'd like for the program to turn on and off, based on your needs.
Turning on TaskTimer will block all access to your immediate network, including your internet connection. Then, until you close the application, you will only be able to access the internet for the limited amount of time that you request for your internet goal. Likewise, there is additional functionality to encourage staying focused on non-internet goals as well. Exiting TaskTimer will re-enable your internet access.
Background
It is well known that webpages and advertisements are designed to maximize our exposure to marketing material. Users may not even notice how much time they engage with content they never planned to consume. The result is hours upon hours of wasted time every day--hours that could have been spent productively enhancing one's skill set or one's social connections. The first step in making changes for the better is to understand and accept this potential challenge.
Currently, there is no stand-alone solution to the problem of internet overindulgence. There are multiple websites that offer to keep track of your time online--even services that store a log of tasks you worked on--but these are still services, interested in keeping you online and not offline. TaskTimer takes the alternative approach that only freeware could take in that it asks for no contribution at all from the user. It respects the users decision about being offline, and enforces the user's intended goal of being online for only a limited amount of time, after which the internet gets shut off, prompting a re-examination of whether it's worth it for the user to continue browsing.
Using the code
Written in C# .NET Framework 4.0, the code for TaskTimer is attached as a Visual Studio project. Although currently fully-functional, it's highly likely that one may desire some additional feature(s), in which case they should feel free to change / enhance TaskTimer.
The core functionality uses System.Timers.Timer to monitor for changes every 15 seconds. Upon launching the application, ApplicationContext.cs stores the user's current internet configuration (IP address, etc.) into container class InternetDetails.cs. The user interface, Form.cs, displays the list of internet adapters in your computer that could be controlled by the program. The user is encouraged to store their settings before closing the initial popup window, although it is possible to close the UI and the program by selecting "Close Program" from the icon created in the task-bar. Pressing the "Save and Turn Off Internet" button will, indeed, turn off internet access.
By Reference
Internet is a great tool, but it often distracts us. This can be said of computer clutter in general--all the icons and files in close proximity make it too easy for us to dart off into an unexpected adventure. TaskTimer is a tool to limit our exposure to the distractions by tempering our access to the internet and by periodically reminding us to focus on a chosen task. It appears as a tray icon and is completely configured in one step by setting a desired nag message, the approximate frequency with which you'd like to see the nag message, and, finally, the target internet adapter (e.g. Wi-Fi) you'd like for the program to turn on and off, based on your needs.
Turning on TaskTimer will block all access to your immediate network, including your internet connection. Then, until you close the application, you will only be able to access the internet for the limited amount of time that you request for your internet goal. Likewise, there is additional functionality to encourage staying focused on non-internet goals as well. Exiting TaskTimer will re-enable your internet access.
Background
It is well known that webpages and advertisements are designed to maximize our exposure to marketing material. Users may not even notice how much time they engage with content they never planned to consume. The result is hours upon hours of wasted time every day--hours that could have been spent productively enhancing one's skill set or one's social connections. The first step in making changes for the better is to understand and accept this potential challenge.
Currently, there is no stand-alone solution to the problem of internet overindulgence. There are multiple websites that offer to keep track of your time online--even services that store a log of tasks you worked on--but these are still services, interested in keeping you online and not offline. TaskTimer takes the alternative approach that only freeware could take in that it asks for no contribution at all from the user. It respects the users decision about being offline, and enforces the user's intended goal of being online for only a limited amount of time, after which the internet gets shut off, prompting a re-examination of whether it's worth it for the user to continue browsing.
Using the code
Written in C# .NET Framework 4.0, the code for TaskTimer is attached as a Visual Studio project. Although currently fully-functional, it's highly likely that one may desire some additional feature(s), in which case they should feel free to change / enhance TaskTimer.
The core functionality uses System.Timers.Timer to monitor for changes every 15 seconds. Upon launching the application, ApplicationContext.cs stores the user's current internet configuration (IP address, etc.) into container class InternetDetails.cs. The user interface, Form.cs, displays the list of internet adapters in your computer that could be controlled by the program. The user is encouraged to store their settings before closing the initial popup window, although it is possible to close the UI and the program by selecting "Close Program" from the icon created in the task-bar. Pressing the "Save and Turn Off Internet" button will, indeed, turn off internet access.
By Reference
Using .NET libraries from JAVA
Recent popularization of net offerings seems to resolve virtually any interoperability issue between JAVA and .Web programs because of platform independence and universal transport channel. And that is actual, the pliability and universality of internet offerings founded options in mixture with good-defined requisites makes this technology a winner in virtually eighty% might be even ninety% of cases. However fairly there are no cons?
Of direction there are and circumstances unresolvable with internet carrier come out on occasion in many crucial initiatives. The major purpose why internet offerings does no longer slot in each case is regularly performance, protection and development costs. The determination the right way to clear up these disorders mostly relies on system architects and it might be probably the most essential choice in challenge entailing quite a lot of specific consequences.
How you can identify in case your case will have to be solved with net offerings?
If you are the one to make a decision you must recollect as a minimum following aspects. Let’s say we now have .Web library with some legacy business common sense or relevant encryption/buying and selling algorithm or .Net simplest API to corporate CRM, here is how we could analyse this:
examine in case your requirement is worth constructing dedicated customer-server infrastructure. Will you ought to run go desktop executions? Don't forget that net provider is consumer server. In our case we might must construct web provider on .Internet side and wrap selected approaches in our WCF SVC or ASMX interface. If it’s just one approach and dll located on the identical laptop as our JAVA software is it worth to host internet server and consume it on neighborhood host? Obviously not.
Examine if you could have enough money it. Each web provider name has rather colossal overhead on each request message if we use xml protocol every easy approach is wrapped in xml envelope and handed in http request ingesting internet server resources, and together with all different delays of transport channel, serialization/deserialization and internet request processing correctly if it is trading algorithm that locations transactions on currency trading or inventory market we must restrict it… identical in all other circumstances have been we make various requests in short time or we just rely on speed we must now not add that so much of buzz into our communication.
Investigate if it’s no longer too simple. If the library that we use comprises single system for encrypting or calculating anything, must we make: web provider, consumer, host web server, permit http conversation, build .Web net mission simply to load one approach from one dll and get in touch with it as soon as in lifetime of our JAVA challenge? No.
Investigate if it’s now not too elaborate. Regularly the amount of code that we need to reuse in JAVA could be oppositely too massive. Wrapping countless numbers of methods in web carrier and passing hundreds of execution places by way of web provider customer would rate us rather a lot in progress and additional maintenance. Simple illustration would be the case were we want to construct JAVA software with WPF interface, i will be able to’t assume exposing all WPF framework classes by way of internet offerings enforcing call-backs and constructing out of it responsive UI.
We could anticipate that up to now we have now determined if our solution must and would be implemented with net offerings interoperability technique, but what must we do if it does now not fit in there? Most of builders most often don't meet such problems but as a result if they do it’s rough to find a excellent solution. It is not that effortless to get JAVA and .Web work collectively by way of our possess, with out spending for it extra time than entire our undertaking is deliberate for. And of course we must remember that it isn't a excellent apply to reinvent the wheel.
What are the possible choices to make use of .Internet libraries from JAVA application?
Most of us does no longer comprehend that there are some native JAVA to .Web bridges to be had in the marketplace whereas these solutions does exactly this what web carrier does not so they fill our gap of 20% circumstances perfectly.
Native JAVA to .Net Bridge leverages JAVA native methods invocation capabilities with native platform exact verbal exchange channels and direct invocations on .Web objects. In this approach we get .Net procedure being hosted natively for our JAVA utility giving us entry to any .Internet library directly from JAVA code like they were native JAVA objects. When you consider that of direct invocation passing between tactics we get instant execution with out delays, overhead and further infrastructure.
Moreover we get a few additional advantages, these are: efficient call-backs mechanism if you want to with no trouble subscribe cross platform movements, entry to any .Net library without any wrappers and implementation on .Web side, lifecycle of objects and methods bound into one runtime and no client server solutions accordingly no additional side merchandise to keep and display.
JAVA to .Internet interop market is not large. There are simplest few carriers who managed to supply efficient and flexible adequate solutions that could be nontoxic for initiatives of any measurement.
Picking out proper bridge will have to be pushed by using simplicity of usage, performance and flexibility. This year there used to be new answer launched called Javonet. It appears to be very appealing because of a number of causes. The mission was once firstly born as tutorial study for object database techniques at Polish-jap Institute of information science. From very beginnig it was aimed on high efficiency.
For the duration of commercialization it was improved with very programmer-pleasant API and many valuable aspects. Javonet offers access to any .Net library nonetheless it's customized, part of .Net framework or delivered by using 1/3 celebration firms. There aren't any changes in .Net code required and libraries can be loaded from neighborhood directories or GAC. And it supports both x86 and x64.
Having entry to any library instantly we are able to just reference them from our JAVA code and work on objects and courses from such library like they have been native JAVA objects. Javonet API exposes specified NObject variable for JAVA which works as manage to .Net object. For the reason that all invocations and references are performed in runtime we will initialize and make use of any object, process, property or discipline making use of reflection-type syntax by way of supplying names in steady strings.
JAVA to .Web bridge like Javonet handles internally rubbish collector moves and exceptions with a purpose to seize .Internet exceptions on JAVA side and if our NObject control is collected on JAVA aspect corresponding object will get disposed on .Net aspect as good. All these points makes such bridging resolution a huge leading edge technological know-how that gives you us all-in-one framework for making use of .Net code from JAVA.
The possibilities of these options are worth exploring as high efficiency and easy utilization results in new strategies of how we would apply this in our tasks. In tutorial and samples we will read step by step publications make full JAVA software with WinForms or WPFinterface or how you can lengthen .Internet category in JAVA, typically even for tremendously experienced builders these sort of solutions looks like magic.
I totally encourage all JAVA builders to become aware of and test these solutions to preserve in intellect new choices how CLR and JVM interoperability issues would be resolved in state-of-the-art world.
Subscribe to:
Posts (Atom)
-
The following article discusses the WPF command binding feature with relation to Mouse clicks. One of WPF powerful features is the bindin...
-
SQL Server has never been short of ways to read from and write to files and it is always better to use the standard techniques provided b...
-
In this article we will look at the basics of Angular.Js. This is the first part of an article series. The main objective of this series i...