Posts Tagged ‘ asp.net ’

ASP.NET Hello World.

 

   1: <%@ Page Language="C#" %>

   2: <html xmlns="http://www.w3.org/1999/xhtml">

   3: <head runat="server">

   4: <title></title>

   5: </head>

   6: <body>

   7: <%
   1:  Response.Write("This is a test !"); 

%>

   8: </body>

   9: </html>

On the ASP.NET side, I could include YUI or jQuery and still use ASP.NET controls if I wanted or not use any server side controls and even turn off view-state.

If you don’t have call response.write you can even use the short hand …

<%= "This is a test !" %>

I can still code to the page lifecycle events if I want, or, code for top-to-bottom execution as seen above !

Expressing Intent with the new IHtmlString interface

If you’re paying close attention, you might be asking yourself “Html.TextBox is supposed to return HTML that is already sanitized. Wouldn’t using this syntax with Html.TextBox cause double encoding?

ASP.NET 4 also introduces a new interface, IHtmlString along with a default implementation, HtmlString. Any method that returns a value that implements the IHtmlString interface will not get encoded by this new syntax.

In ASP.NET MVC 2, all helpers which return HTML now take advantage of this new interface which means that when you’re writing a view, you can simply use this new syntax all the time and it will just work. By adopting this habit, you’ve effectively changed the act of HTML encoding from an opt-in model to an opt-out model.

The Goals

There were four primary goals we wanted to satisfy with the new syntax.

  1. Obvious at a glance. When you look at a page or a view, it should be immediately obvious which code blocks are HTML encoded and which are not. You shouldn’t have to refer back to flags in web.config or the page directive (which could turn encoding on or off) to figure out whether the code is actually being encoded. Also, it’s not uncommon to review code changes via check-in emails which only show a DIFF. This is one reason we didn’t reuse existing syntax.

    Not only that, code review becomes a bit easier with this new syntax. For example, it would be easy to do a global search for <%= in a code base and review those lines with more scrutiny (though we hope there won’t be any to review). Also, when you receive a check-in email which shows a DIFF, you have most of the context you need to review that code.

  2. Evokes a similar meaning to <%=. We could have used something entirely new, but we didn’t have the time to drastically change the syntax. We also wanted something that had a similar feel to <%= which evokes the sense that it’s related to output. Yeah, it’s a bit touchy feely and arbitrary, but I think it helps people feel immediately familiar with the syntax.

  3. Replaces the old syntax and allows developers to show their intent. One issue with the current implementation of output code blocks is there’s no way for developers to indicate that a method is returning already sanitized HTML. Having this in place helps enable our goal of completely replacing the old syntax with this new syntax in practice.

    This also means we need to work hard to make sure all new samples, books, blog posts, etc. eventually use the new syntax when targeting ASP.NET 4.

    Hopefully, the next generation of ASP.NET developers will experience this as being the default output code block syntax and <%= will just be a bad memory for us old-timers like punch cards, manual memory allocations, and Do While Not rs.EOF.

  4. Make it easy to migrate from ASP.NET 3.5. We strongly considered just changing the existing <%= syntax to encode by default. We eventually decided against this for several reasons, some of which are listed in the above goals. Doing so would make it tricky and painful to upgrade an existing application from earlier versions of ASP.NET.

    Also, we didn’t want to impose an additional burden for those who already do practice good encoding. For those who don’t already practice good encoding, this additional burden might prevent them from porting their app and thus they wouldn’t get the benefit anyways.

To upgrade an existing ASP.NET MVC 1.0 application to version 2, perform the following steps:

1. Make a backup of the existing project.

2. Open the project file (the file with the .csproj or .vbproj file extension) and locate the ProjectTypeGuid element. In the value of that element, replace the GUID {603c0e0b-db56-11dc-be95-000d561079b0} with {F85E285D-A4E0-4152-9332-AB1D724D3325}.When you are done, the value of that element should be as follows:

<ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>

3. In the Web application root folder, edit the Web.config file. Search for System.Web.Mvc, Version=1.0.0.0 and replace all instances with System.Web.Mvc, Version=2.0.0.0.

4. Repeat the previous step for the Web.config file located in the Views directory.

5. Open the project using Visual Studio and expand the References node in Solution Explorer. Delete the reference to System.Web.Mvc (which points to the version 1.0 assembly). Add a reference to System.Web.Mvc (v2.0.0.0).

6. Add the following bindingRedirect element to the Web.config file in the application root under the configuraton section:

<runtime>

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

<dependentAssembly>

<assemblyIdentity name="System.Web.Mvc"

publicKeyToken="31bf3856ad364e35"/>

<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>

</dependentAssembly>

</assemblyBinding>

</runtime>

7. Create a new ASP.NET MVC 2 application. Copy the files within the Scripts directory into the Scripts directory of the existing application.

8. Compile the application and run it. If any errors occur, refer to the Breaking Changes section of this document for possible solutions.

MVC is a design pattern that stands for Model-View-Controller. What is strives to do is separate the concerns of an application’s presentation layer by assigning specific roles to the three different components.

The Controller is responsible for handling all user input. Once input has been received, the Controller will perform any operations/actions it needs to, which might include interacting with the Model.

The Model represents the core concern/logic of the application. Once the Controller retrieves some model data and performs any work with the model/etc it needs to it constructs a presentation model that describes the model in terms the View can understand.

The View is the visual representation of the model. It presents the model data to the actual user in a way that is meaningful. In a web application, this would typically be HTML.

With these three pieces in place, your presentation layer becomes cleanly separated in such a way that each component can be developed/tested independently.

 

So what does MVC look like when implemented over the web?

When an HTTP request comes into the application it is mapped to a controller. Remember as we mentioned in the previous slide, in the MVC design pattern, the controller is the piece of the trifecta that handles all user input. In the case of a web application, user input is represented as HTTP requests [Advance Animation].

Once the controller has received input, it performs whatever operations it needs to and then assembles a presentation model [Advance Animation].

The controller then takes the model and passes it off to the view. Remember that the view is simply a visual representation of the model [Advance Animation].

The view then “transforms” the model into whatever format it uses to represent it. In a web application, this would typically be HTML [Advance Animation].

The view then serves the request by responding with its visual representation.

For security reasons related to exploits or whatever that is, I need to store the files uploaded by users in a different partition. That’s OK.

But then, and here’s the problem, I need to get them on order to display them to users (this includes pictures). I tried this (it worked perfectly the time I used php), but apparently does not work with ASP.NET or maybe I am doing something wrong.

I write this code in the aspx file:

<img src="/Image/Index/filename.extension" alt="…" />

The src of this image is another action that gets the image from our secret directory in our different partition and it goes like this:

        public Image Index(string fileName)
        {
            string source = Constants.ImagesPath + fileName;
            Image img = System.Drawing.Image.FromFile(source);
            return img;
        }

I get the image, debugging confirms it! But the only thing presented is the alternative text. As I said before, I used to do something similar with php and it worked, but, of course, php also has its problems and that’s way we changed to ASP.NET.

the solution is:

1. public void Index1(String FilePath)  

2. {  

3.     byte[] FileStreamBytes = null;  

4.     FilePath = @"c:\sampleImage.png";  

5.     FileStream objFileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);  

6.     FileStreamBytes = new byte[objFileStream.Length];  

7.     objFileStream.Read(FileStreamBytes, 0, FileStreamBytes.Length);  

8.     objFileStream.Close();  

9.     objFileStream = null;  

0.     Response.BinaryWrite(FileStreamBytes);  

1.     Response.End();  

2. }  

This article is based on a prerelease version of the ASP.NET MVC Framework. Details are subject to change.

Contents
All Routes Lead to a Factory
Factory Extensibility
Execution Is Just the Beginning
Selector Attributes
Filter Attributes
Custom Action Filters
Getting Results
The Action Is Over

Controllers are the lynchpins of the Model View Controller (MVC) design pattern. They are on the front line, first receiving a client’s requests, and then translating the requests into instructions for the model where your application’s domain logic and data reside. Controllers are also responsible for selecting a view for presenting information to the user.
In this article, I will dissect the ASP.NET MVC framework and look at how controllers work. I’ll explain how the framework interacts with your controllers and how you can influence those interactions. I’ll look at controller factories, controller actions, action filters, and action results as well.
I’ll dig in fairly deeply, so if you are looking for a more general introduction to the ASP.NET MVC framework, see Chris Tavares’ article “Building Web Apps without Web Forms.”
All Routes Lead to a Factory
It’s difficult to talk about the life of a controller without talking about routes. The routing table in an ASP.NET application contains the information necessary for the ASP.NET routing module to extract information from an incoming URL and direct the request to the proper software component. In January’s column, I looked at using the ASP.NET routing module with Web Forms (“Routing with ASP.NET Web Forms”.) In that column, I built my own routing handler in order to execute a Web form, but the ASP.NET MVC framework provides a routing handler that will eventually direct a request to one of our controllers.
For this MVC routing handler to process requests, you need to configure the routing table during application startup. The default routing configuration provided by the MVC project template lives in the global.asax file and is shown in Figure 1.

Figure 1 The Default Routing Configuration

One of the routing configuration entries in Figure 1 is a route named Default with an URL template of “{controller}/{action}/{id}”. This URL template is a pattern the routing engine will use to first see if an incoming URL is a match for this route. A URL that would match such a route would be http://localhost/home/index/. When the routing engine finds a match, it will again use the URL template as a pattern to lift parameters from the incoming URL. In this example, the string “home” becomes the controller parameter because it is in the {controller} position, and the string “index” becomes the action parameter.
The anonymously typed object constructed as the third parameter to MapRoute represents the default values for the routing engine to use if it cannot find a given parameter in the URL. In the case of http://localhost/home/index/, the routing engine doesn’t find “id” information in the URL, but it will still pass along an id parameter with the default value of an empty string. The routing engine passes all these parameters to a routing handler via a RouteData object.
It’s important to note that the routing engine knows nothing about ASP.NET MVC. The engine’s only job is to analyze URLs and pass control to a route handler. The MapRoute method being invoked inside of the RegisterRoutes method of Figure 1 is an extension method provided by the MVC framework. Every route registered with MapRoute is configured to use an MvcRouteHandler object—this is the route handler provided by the MVC framework. As you saw in the January column, it is the route handler’s job to find an HTTP handler for a request—that is an object implementing the IHttpHandler interface. In MVC applications, this object will be an object of type MvcHandler, and inside MvcHandler is where processing becomes interesting.
Figure 2 shows the processing flow for a typical MVC request. When control reaches the MvcHandler, the MvcHandler is able to extract the controller parameter from the RouteData produced by the routing module earlier in the processing. The handler will ultimately send this controller parameter, which is a string value, to a controller factory. It is then the factory’s responsibility to construct and return a controller. All controllers in an MVC application implement the IController interface.

One of the things that many people have asked for over the years with ASP.NET is built-in support for developing web applications using a model-view-controller (MVC) based architecture.

Last weekend at the Alt.NET conference in Austin I gave the first public demonstration of a new ASP.NET MVC framework that my team has been working on.  You can watch a video of my presentation about it on Scott Hanselman’s blog here.

We’ll be releasing a public preview of this ASP.NET MVC Framework a little later this year.  We’ll then ship it as a fully supported ASP.NET feature in the first half of next year.

What is a Model View Controller (MVC) Framework?

MVC is a framework methodology that divides an application’s implementation into three component roles: models, views, and controllers.

  • "Models" in a MVC based application are the components of the application that are responsible for maintaining state.  Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).
  • "Views" in a MVC based application are the components responsible for displaying the application’s user interface.  Typically this UI is created off of the model data (for example: we might create an Product "Edit" view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).
  • "Controllers" in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI.  In a MVC application the view is only about displaying information – it is the controller that handles and responds to user input and interaction.

One of the benefits of using a MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application.  Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated.

The MVC pattern can also help enable red/green test driven development (TDD) – where you implement automated unit tests, which define and verify the requirements of new code, first before you actually write the code itself.

A few quick details about the ASP.NET MVC Framework

I’ll be doing some in-depth tutorial posts about the new ASP.NET MVC framework in a few weeks once the bits are available for download (in the meantime the best way to learn more is to watch the video of my Alt.net presentation).

A few quick details to share in the meantime about the ASP.NET MVC framework:

  • It enables clean separation of concerns, testability, and TDD by default.  All core contracts within the MVC framework are interface based and easily mockable (it includes interface based IHttpRequest/IHttpResponse intrinsics).  You can unit test the application without having to run the Controllers within an ASP.NET process (making unit testing fast).  You can use any unit testing framework you want to-do this testing (including NUnit, MBUnit, MS Test, etc).
  • It is highly extensible and pluggable.  Everything in the MVC framework is designed so that it can be easily replaced/customized (for example: you can optionally plug-in your own view engine, routing policy, parameter serialization, etc).  It also supports using existing dependency injection and IOC container models (Windsor, Spring.Net, NHibernate, etc).
  • It includes a very powerful URL mapping component that enables you to build applications with clean URLs.  URLs do not need to have extensions within them, and are designed to easily support SEO and REST-friendly naming patterns.  For example, I could easily map the /products/edit/4 URL to the "Edit" action of the ProductsController class in my project above, or map the /Blogs/scottgu/10-10-2007/SomeTopic/ URL to a "DisplayPost" action of a BlogEngineController class.
  • The MVC framework supports using the existing ASP.NET .ASPX, .ASCX, and .Master markup files as "view templates" (meaning you can easily use existing ASP.NET features like nested master pages, <%= %> snippets, declarative server controls, templates, data-binding, localization, etc).  It does not, however, use the existing post-back model for interactions back to the server.  Instead, you’ll route all end-user interactions to a Controller class instead – which helps ensure clean separation of concerns and testability (it also means no viewstate or page lifecycle with MVC based views).
  • The ASP.NET MVC framework fully supports existing ASP.NET features like forms/windows authentication, URL authorization, membership/roles, output and data caching, session/profile state management, health monitoring, configuration system, the provider architecture, etc.
Summary

If you are looking to build your web applications using a MVC approach, I think you’ll find this new ASP.NET MVC Framework option very clean and easy to use.  It will enable you to easily maintain separation of concerns in your applications, as well as facilitate clean testing and TDD.