Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

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.


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 architecture with webform engine
  • Routing
  • HTML Helpers
  • Ajax Helpers
  • Auto binding
MVC 2.0 VS 2008, .Net 3.5/4.0 10-Mar-2010
  • Area
  • Asynchronous controller
  • Html helper methods with lambda expression
  • DataAnnotations attributes
  • Client side validation
  • Custom template
  • Scaffolding
MVC 3.0 VS 2010 .Net 4.0 13-Jan-2011
  • Unobtrusive javascript validation
  • Razor view engine
  • Global filters
  • Remote validation
  • Dependency resolver for IoC
  • ViewBag
MVC 4.0 VS 2010 SP1,

VS 2012
.NET 4.0/4.5 15-Aug-2012
  • Mobile project template
  • Bundling and minification
  • Support for Windows Azure SDK
MVC 5.0 VS 2013 .NET 4.5 17-oct-2013
  • Authentication filters
  • Bootstrap support
  • New scaffolding items
  • ASP.Net Identity
MVC 5.2 - Current VS 2013 .NET 4.5 28-Aug-2014
  • Attribute based routing
  • bug fixes and minor features upate

Wednesday, April 6, 2011

Presenting Data with the DataGridView Control in .NET 2.0

Defining Custom Column and Cell Types

With the DataGridView, you are already leaps and bounds ahead of the DataGrid for presenting rich data because of the built-in column types that it supports out of the box. But there are always custom scenarios that you will want to support to display custom columns. Luckily, another thing the DataGridView makes significantly easier is plugging in custom column and cell types.
If you want to customize just the painting process of a cell, but you don’t need to add any properties or control things at the column level, you have an event-based option rather than creating new column and cell types. You can handle the CellPainting event and draw directly into the cell itself, and you can achieve pretty much whatever you want with the built-in cell types and some (possibly complex) drawing code. But if you want to be able to just plug your column or cell type in a reusable way with the same ease as using the built-in types, then you can derive your own column and cell types instead.
The model you should follow for plugging in custom column types matches what you have already seen for the built-in types: You need to create a column type and a corresponding cell type that the column will contain. You do this by simply inheriting from the base DataGridViewColumn and DataGridViewCell classes, either directly or indirectly, through one of the built-in types.
The best way to explain this in detail is with an example. Say I wanted to implement a custom column type that lets me display the status of the items represented by the grid’s rows. I want to be able to set a status using a custom-enumerated value, and cells in the column will display a graphic indicating that status based on the enumerated value set on the cell. To do this, I define a StatusColumn class and a StatusCell class (I disposed of the built-in type naming convention here of prefixing DataGridView on all the types because the type names get sooooooooooo long). I want these types to let me simply set the value of a cell, either programmatically or through data binding, to one of the values of a custom-enumerated type that I call StatusImage. StatusImage can take the values Green, Yellow, or Red, and I want the cell to display a custom graphic for each of those based on the value of the cell. Figure 6.7 shows the running sample application with this behavior.
06fig07.jpg Figure 6.7 Custom Column and Cell Type Example

Defining a Custom Cell Type

To achieve this, the first step is to define the custom cell type. If you are going to do your own drawing, you can override the protected virtual Paint method from the DataGridViewCell base class. However, if the cell content you want to present is just a variation on one of the built-in cell types, you should consider inheriting from one of them instead. That is what I did in this case. Because my custom cells are still going to be presenting images, the DataGridViewImageCell type makes a natural base class. My StatusCell class isn’t going to expose the ability to set the image at random, though; it is designed to work with enumerated values. I also want the cell value to be able to handle integers as long as they are within the corresponding numeric values of the enumeration, so that I can support the common situation where enumerated types are stored in a database as their corresponding integer values. The code in Listing 6.4 shows the StatusCell class implementation.

Example 6.4. Custom Cell Class

namespace CustomColumnAndCell
{
   public enum StatusImage
   {
      Green,
      Yellow,
      Red
   }

   public class StatusCell : DataGridViewImageCell
   {
      public StatusCell()
      {
         this.ImageLayout = DataGridViewImageCellLayout.Zoom;
      }

      protected override object GetFormattedValue(object value,
         int rowIndex, ref DataGridViewCellStyle cellStyle,
         TypeConverter valueTypeConverter,
         TypeConverter formattedValueTypeConverter,
         DataGridViewDataErrorContexts context)
      {

         string resource = "CustomColumnAndCell.Red.bmp";
         StatusImage status = StatusImage.Red;
         // Try to get the default value from the containing column
         StatusColumn owningCol = OwningColumn as StatusColumn;
         if (owningCol != null)
         {
            status = owningCol.DefaultStatus;
         }
         if (value is StatusImage || value is int)
         {
            status = (StatusImage)value;
         }
         switch (status)
         {
            case StatusImage.Green:
               resource = "CustomColumnAndCell.Green.bmp";
               break;            case StatusImage.Yellow:
               resource = "CustomColumnAndCell.Yellow.bmp";
               break;
            case StatusImage.Red:
               resource = "CustomColumnAndCell.Red.bmp";
               break;
            default:
               break;
         }
         Assembly loadedAssembly = Assembly.GetExecutingAssembly();
         Stream stream =
            loadedAssembly.GetManifestResourceStream(resource);
         Image img = Image.FromStream(stream);
         cellStyle.Alignment =
            DataGridViewContentAlignment.TopCenter;
         return img;
      }
   }
}
The first declaration in this code is the enumeration StatusImage. That is the value type expected by this cell type as its Value property. You can then see that the StatusCell type derives from the DataGridViewImageCell, so I can reuse its ability to render images within the grid. There is a default status field and corresponding property that lets the default value surface directly. The constructor also sets the ImageLayout property of the base class to Zoom, so the images are resized to fit the cell with no distortion.
The key thing a custom cell type needs to do is either override the Paint method, as mentioned earlier, or override the GetFormattedValue method as the StatusCell class does. This method will be called whenever the cell is rendered and lets you handle transformations from other types to the expected type of the cell. The way I have chosen to code GetFormattedValue for this example is to first set the value to a default value that will be used if all else fails. The code then tries to obtain the real default value from the containing column’s DefaultValue property if that column type is StatusColumn (discussed next). The code then checks to see if the current Value property is a StatusImage enumerated type or an integer, and if it is an integer, it casts the value to the enumerated type.
Once the status value to be rendered is determined, the GetFormattedValue method uses a switch-case statement to select the appropriate resource name corresponding to the image for that status value. You embed bitmap resources in the assembly by adding them to the Visual Studio project and setting the Build Action property on the file to Embedded Resource. The code then uses the GetManifestResourceStream m

http://osteele.com/archives/2004/08/web-mvc

ASP.NET MVC Pro’s and Con’s

In our current iteration of improving our software development strategy, ASP.NET WebForms simply doesn’t fit in with the new demands of being unit testable and flexible. It comes as no surprise that ASP.NET MVC has been getting all the headlines lately. Like many others, I’ve gotten the itch to try it out. In this post I’ll talk about what I believe are the main pro’s and con’s of the new style for building web applications.
Scale
PRO – No ViewState or "surprise crap"
In traditional ASP.NET WebForms, the luxury of pretending to behave like a Windows Form comes at a price. The ViewState is a reliable way of storing all of the state information for the form. Unfortunately, due to the limitations of the web, this data needs to be a giant string inside of a hidden form field. This ends up adding a substantial number of bytes to the page, making it slower and requiring extra bandwidth. Of course the ViewState is controllable, much like the dinosaurs in Jurassic Park.
Not only is the ViewState gone, but "mystery" generated HTML is also gone. You have strict control over the HTML. This gives you great power, but with great power comes great responsibility. Use it wisely, and you will have elegant XHTML output with no surprises. You need to really know your HTML, which in today’s web world is a prerequisite anyway.
PRO – Faster server-side
It’s hard to get any real performance data about MVC, but it’s been suggested that it’s potentially 8000 times faster. Supposedly it’s due to less processing since it simply processes a "template" instead of having to build a complicated control tree. Even if it’s twice as fast, or even marginally faster, that would be significant for popular sites, or give at least a slight boost to smaller sites.
PRO – Simplified model for multiple related views
One thing that I found much easier to do with MVC was to have multiple versions of a page that displayed the same data, but in a slightly different format. For example, on my RSS package tracking website, you can look at your tracking information in a full-featured desktop browser, a mobile browser, or an RSS reader. The data being displayed is always the same, but the actual rendered output was different. If I later want to make an iPhone specific version for example, I would simply make a new view, and use an existing controller action.
PRO – Unit testable
One of the biggest challenges with WebForms was that testing was difficult. Not only was the actual output not easy to test, but the code-behind would tend to be a place that would contain important code that would never get unit tested. With both MVC and WebForms, it’s best to keep your logic away from the page, but it’s not always easy or ideal. MVC makes it simple to unit test the logic that is specific to a page. To do so, you simply test the actions in your controllers, which are regular, easy to test classes.
CON – Difficult to convert an existing site
MVC is not only a framework in this case, but a style. It is possible to convert specific pages as needed, but the cost is high. The problem is that MVC is radically different, so the benefit of converting probably isn’t worth it for most of your existing pages.
If you decide to convert your site to MVC, you may also run into issues trying to maintain existing page addresses. The specific issue I’ve ran into is that routes cannot have a trailing slash. If you want to maintain existing URL’s that have trailing slashes, there is no way to have the built-in routing generate URL’s with a trailing slash. You may end up losing one of the big advantages that MVC has to offer.
CON – Not best for SEO out of the box
I’ve mentioned some of the SEO issues before, and all but the trailing slash issue have a reasonable workaround. The routing engine likes to allow multiple addresses to render the same page, instead of enforcing a single address for each page. Luckily, as Scott Hanselman mentions, you can use a URL rewrite engine to bend it to your will. I highly recommend spending some time writing intelligent rules that perform the necessary 301 redirects, because you don’t want to take chances with SEO (Search Engine Optimization).
CON – Challenges if you’re not running IIS7
It’s clear that the last couple of versions of IIS have been major improvements over their predecessors. IIS7 takes .NET integration to an entirely new level. There is already a good page that covers the challenges you’ll face if you’re not running IIS6. I’ll just list them here for brevity:
  • .NET needs to handle all page requests to ensure that the MVC pages will be processed. This leads to bad performance of static files.
  • HTTP Compression through IIS6 doesn’t work, because the MVC pages are dynamic.
  • The homepage gives a 404 when hosted on the root of a domai

http://www.ytechie.com/2008/10/aspnet-mvc-pros-and-cons.html

Tuesday, March 29, 2011

Cloud Spend Analytics using CloudRows


AWS Spending Analytics

Review and analyze your IT expenses

CloudRows delivers an extensive set of AWS activity and spending reports, in a unified, easy-to-use analytical dashboard.
Key reports:
* Spending overview and drilldown
* Activity overview and drilldown
* Budget tracking status

http://www.cloudrows.com/

MVC Advantages and disadvantages

Languages of the real and artificial.

Web MVC

The Model-View-Controller (MVC) architecture is a standard architecture for interactive applications. In client-server programming, the MVC components are distributed across at least two nodes of a network. This leads to a set of choices about where to deploy each component of the architecture. One solution is the traditional server-based MVC model. Another is the Rich Internet Application (RIA) model. In a real-world application with client-side validation, these are more similar than they might seem.

Desktop MVC

In an interactive application, there is typically a domain model, code to present the model to the user, and code to act upon the model in response to the user manipulation of input devices such as the keyboard and mouse. For example, in a word processor the domain model is the document, which contains entities such as paragraphs, spans, and styles. The system presents the document to the user as (for a sighted user) glyphs rendered as pixel patterns, and interprets keystrokes and mouse actions as edit, formatting, and control commands.
Smalltalk-80 introduced the Model-View-Controller (MVC) architecture for structuring this type of application. MVC separates the maintainance of the domain model (the Model), the presentation of the model (the View), and the interpretation of user input (the Controller).
Model-View-Controller Control Flow2