Archive

Archive for the ‘ASP.NET MVC’ Category

Live Blogging – MSDN Mid-Atlantic Roadshow

September 30, 2008 Comments off

Today I am in Roanoke, VA at the MSDN Mid-Atlantic Roadshow. This Microsoft event highlights Web development and .NET 3.5.

Web Development Basics – 9am

Presented by Andrew Duthie, Microsoft Technology Evangelist. Andrew presents a nice history and overview of web development, from HTML/XHTML, Classic ASP, and up to ASP.NET. It definitely confirms my opinion that I am glad I never was a Classic ASP developer!

He discussed Postback and ViewState, (my least favorite features of ASP.NET and hence my appreciation of ASP.NET MVC.) I know this is not a popular ASP.NET view point, but it makes it difficult for traditional web developers like myself to step into an ASP.NET role. One thing he mentioned was that you can disable ViewState for particular controls, for performance reasons. You would only do this if the element was for display only.

He also discussed one of my favorite features, Master Pages. I have long used this same concept in PHP development and I immediately recognized it in ASP.NET.

Note to self: learn about Membership Profiles. I’ve been developing my own because I am connecting to a non-standard data source (IBM iSeries DB2). Andrew said you can write your own custom backend but still use the built in Profile features.

DataBinding Demo: he showed a typical GridView Control bound to a SqlDataSource. “Declarative Data Binding” – there is no executable code that drives the GridView, it is all expressed in the ASPX. It is fast and easy to develop, but you still have the option to develop your own binding for more control.

Web Services: ASMX and WCF Services both supported. ASMX is simpler, and hosted on IIS, but harder to make cross platform capable. WCF is more complex to configure and can be hosted by any .NET process. ADO.NET Data Services uses WCF. WCF can be used to communicate between servers and applications. “ABC”s of WCF: Address, Binding, Contract. I think it’s time I learned about WCF…

What’s New in the .NET 3.5 Framework for Web Developers and Intro to ASP.NET MVC – 10:40am

Zhiming Xue, Architect Evangelist.

New features introduced in .NET 3.5 SP1: ADO.NET Entity Framework, ASP.NET Dynamic Data, ADO.NET Data Services, ASP.NET Routing.

ADO.NET Entity Framework

Microsoft’s 1st ORM offering for .NET. Designed for providing a UI for ORM development.

  • Entity Data Modle (EDM) separates objects from their Data Structures. Objects are mapped to their physical data store via three things: Conceptual Schema Definition (CSDL), Storage Schema Definition (SSDL), and the Mapping Specification (MSL). This approach decouples the DB Schema from the Application Model. This provides flexibility and can be platform independent (requires an Entity Data Provider.)
  • Entity Framework is a set of services that allow you to consume EDM from within your applications. It includes Object Services, Entity Client, EntitySQL, and Linq-to-Entities.
  • Visual Studio Support is supposed to make the development seamless and simple.

DataSets are raw data store connections. Linq To SQL provides an ADO.NET connection to SqlServer. Entity Framework is going to allow ORM connections to most any database.

DEMO: Z wrote live a WPF application that consumes EDM. Create a WPF solution. Add a DLL project and add a new ADO.NET Entity Model item to the project. Select the data connection and store it in the Web.config file. The database is diagrammed in Visual Studio, complete with relationships. It also creates a Mapping Details window, which he did not demonstrate, but it looks like that is where you change the mapping. The EDMX file contains the XML definition of the SSDL and CSDL. Copy the App.Config file from the EDM project to the WPF project – this links the WPF to the correct Data Store. Add an xxxEntities model object to instantiate the connection. Very fast development, very impressive results in less than 5 minutes!

ASP.NET Dynamic Data

Data driven web application scaffolding. If you are unfamiliar, scaffolding, popularized by Ruby on Rails, provides default pages for Insert, Update, Delete, etc. DD is based on an object model with full controls, metadata, validation, etc. This is expressed in two new ASP.NET project types: Entity Data Model and Linq To SQL.

DEMO: Z added a Dynamic Data Web Application to the above demo so that he could tie in to the same EDM code he already produced. Set the connection stream in the Web.config file to connect the site to the EDM data store. Apparently DD is set up assuming Linq, so Z had to make changes to the Page Templates to use the EDM instead. He had to change LinqDataSource to EntityDataSource. Then he had to register the EDM assembly within the individual pages. (Couldn’t you do this once in Web.config?)

The default scaffolding is very nice and has all the features you would expect. I saw a Routing mechanism, but he did not really discuss how it is used. He demonstrated custom validation. It uses System.ComponentModel.DataAnnotations and implements events for validation.

Overall it looks interesting, but I’m not sure yet how it would be used in a real world setting.

ADO.NET Data Services

Formerly “Astoria”, this technology exposes data in a secure fashion over the web or network. It is a combination of patterns and libraries that enable the creation and consumption of data services for the web as “feeds”. This does not have to be a database: it can be any data source.

  • Implemented as ATOM – tables = feeds, rows = entities. Includes CRUD, is RESTful, and a URI points to a resource.
  • Uses common URL syntax
  • Capable of exposing any object model that contains IQueryable<T>, such as Linq to SQL and EDM.
  • Locked down by default and supports Operation Batching
  • Supports optimistic concurrency

DEMO: Z added a ADO.NET Data Service item to the above Web project. You have to update the service code to indicate what the model is and set some rules. It was a lot of copy and paste and went by too quickly to document. At this point he basically lost me. He hard coded the port the service executed on. He generated a file using DataServiceUTIL.exe (but never executed the app that I saw) and then copied the file into the WPF solution. He added a reference in the XAML to the service and a pointer to the service in App.config. He did finally get it working, and it is interesting, but again I’m not sure how I would use it.

ASP.NET Routing

Routing maps an application URL to specific handlers. I have been using this in ASP.NET MVC for a while, and they have always said that this was not limited to MVC. His example used DynamicDataRoute() instances. At this point his time was running short, so he didn’t really go into a lot of details.

ASP.NET MVC

As we know, MVC has been in my sights for a while now, and I have been very pleased with the implementation. To be fair to Z, he was really rushing to get through this because of time. Unfortunately, I think he skipped a lot of important basics, but he did at least demo the default and the Task List projects. He really skimmed over the project types, and in the long run I think he just confused anyone who was not already familiar with MVC. Last but not least, he only mentioned that you could use Unit Testing, but did not demo it at all.

AJAX Development and Troubleshooting – 1pm

Andrew Duthie presenting. AJAX is a system of lightweight calls to the server without having to repost the entire web page. I have used AJAX extensively in ASP.NET MVC using jQuery.

ASP.NET AJAX

  • Simple Development Framework
  • Represented as additional libraries to ASP.NET
  • Two Models:
  • UpdatePanel Control (zero code implementation)
  • ScriptManager Control (provides a rich framework of JavaScript libraries)

Included with .NET 3.5. AJAX Control Toolkit is a separate project available from CodePlex. The AJAX libraries work on Windows, Mac OS, and Linux in IE, Firefox, Opera, Safari, and others.

DEMO: Andrew created an AutoComplete textbox sample. Create a Web Form and add an AJAX Form to it, which automatically set up the ScriptManager. Add a reference to the AjaxControlToolkit. Now all the Extenders are available in the toolbox. Drag an AutoCompleteExtender to the page and set up a few attributes to hook into a data source. Viola! Good demo.

AJAX updates in .NET 3.5 SP1:

  • Browser History – allows an Ajax page to be bookmarked for future return (including page data)
  • Script Combining – batches a set of Scripts to be treated as a single download

ANNOUNCEMENT: jQuery will be included in all future versions of Visual Studio! It is to be treated as a first class citizen, complete with jQuery support. Microsoft will even have full PSS support. ASP.NET MVC will be the first ship of this feature.

AJAX Troublesooting

While it is a great tool, Visual Studio is not enough. You also need tools for CSS, DOM, and Scripting analysis.

  • The IE Developer Toolbar allows you to drill down into your code and is especially good for IE 6 and IE7. IE8 has built in developer tools including JavaScript debugging, dynamic CSS changes, and more.
  • Firebug is a similar tool for Firefox.
  • Firebug Lite is a tool that can be run without being installed (runs as a JavaScript app.)
  • httpwatch (IE and Firefox Only) – basic is free, pro costs money
  • fiddler – interaction record log

Other Frameworks

Andrew then spent the rest of the session showing some cool AJAX and JavaScript components.

Microsoft Silverlight 2.0

Ashish Jaiman, ISV Architect Evangelist

Silverlight is a cross browser, cross platform .NET plugin for delivering Rich Experiences in a browser.  Silverlight runs in the browser sandbox and executes .NET code.  Can be hosted in any container element in HTML.  HTML can be overlaid on top of Silverlight elements, and you can have many Silverlight components on a single page.

Silverlight 1.0 was only HTML and JavaScript.  Silverlight 2.0, on the other hand, includes a mini CLR, WPF controls, LINQ, collections, media, layout controls, and more.  Silverlight 2.0 has local storage, FileOpen capabilities, sockets, and cross domain HTTP requests.

Silverlight Pros:

  • Video/Audio
  • Enhanced UX to increase stickiness
  • Decrease the learning curve
  • High resolution imagery
  • Data Visualization
  • Leverage .NET Skills for cross browser/cross platform solutions

Silverlight Cons:

  • Requires a browser plugin
  • There is still a learning curve
  • Need for designers to take full advantage

Designer and Developer Collaboration

This brings up one of the main problems with WPF and Silverlight.  Microsoft’s belief is that developers should focus on developing data, communications, business rules, etc.  Designers should be the ones designing our user experiences.  As a one man shop, I can tell you that this isn’t going to happen, but I understand Microsoft’s point.

In order to really maximize the XAML abstraction concept, it will truly take a designer’s touch wrapped around a developer’s logic.  XAML is simply a description of a user interface in XML and contains no code.  A designer can then use tools like Expression Blend (2.5 for Silverlight 2.0) to design the interface, which will then export the design as XAML.  Visual Studio then can read the XAML and allow the developer to add any necessary application logic.  In fact, Blend and Visual Studio can be opened and used simultaneously against the same code, which is more realistic for someone in my shoes.

ASP.NET includes Silverlight support via the <asp:xaml> and <asp:media> tags, Silverlight has web-service support, and it can utilize the Membership, Profile, and Application Service integration.  IIS 7.0 also includes specific support for Silverlight.

Here is a pretty cool Silverlight demo.  (Go to the “Patient Journey Demonstrator”)

Styling and skinning are completely customizable, which is one of the main points of WPF technologies: however you can imagine visualizing your data or application, then you should be able to make it a reality in WPF/Silverlight.

Local Storage

“Cookies on steroids”, local storage provides 1MB of application specific local information.  Can be expanded if the user allows it.  Exposed through Microsoft Isolated Storage.

DOM Integration

Silverlight is still a browser application, so it can interact with and create HTML elements and scripts through .NET code.

Open File Dialog

You can use this to open a local file on the client.

LINQ

Silverlight 2.0 has LINQ support as part of its CLR.  Currently only on IEnumerable<T>, but XLINQ and DLINQ are in development.

Data Acquisition

Silverlight supports the following Methods:

  • GET, POST,
  • Headers
  • Background threads
  • Streaming
  • Cross domain access (ClientAccess.xml, a subset of CrossDomain.xml)
  • WebClient and HttpWebRequest/Response

The session ended when the instructor’s computer went belly up.

ASP.NET MVC 5 Update

September 24, 2008 Comments off

Yesterday I wrote about updating to ASP.NET MVC Preview 5. Today I tested the changes I made and they failed, so I obviously had a little more work to do.

First, I had to update the Web.config file in several places (just like I did going from Preview 2 to Preview 3.) The only way I could get this to work was to create a brand new Preview 5 web page project and copy the afflicted lines from the new Web.config to the old one. I also went ahead and updated the namespaces, httpModules, and httpHandlers sections.

Then, with the site actually running again, I tried a full blown walk through and discovered a problem. Since System.Web.Mvc.BindingHelperExtensions was replaced with a call to UpdateModel(model, Request.Form.AllKeys), an error occurred. Specifically, a NullReferenceException was thrown because “AllKeys” contained form elements that are not properties in the model object. My gut reaction was to simply add them to my class, but that just didn’t seem right: the model should be unaffected the presentation.

So, at least as a temporary solution, I created a custom List<string> of Keys. I used Reflection to get a list of Property names, and if those names are in Requst.Form.AllKeys then I add it to my list:

typeof(TransactionRequestInfo).GetProperties().ToList().ForEach(p =>
    {
        if (Request.Form.AllKeys.Contains(p.Name))
        {
            keys.Add(p.Name);
        }
    });

UpdateModel(pmtInfo, keys.ToArray());

{NOTE: TransactionRequestInfo and pmtInfo are from the Authorize.Net project, which I still need to update on the site.}

After I got it working, I realized that this is actually a query, so I could use Linq instead:

var keys = from p in typeof(TransactionRequestInfo).GetProperties()
           where Request.Form.AllKeys.Contains(p.Name)
           select p.Name;
UpdateModel(pmtInfo, keys.ToArray());

This shortened the code, got rid of a Lambda Expression, and prevented the need to cast the Properties[] to a List<PropertyInfo> object.

I should probably add logic to make sure only Public properties are selected. Since I may end up using this in more than one place, I will probably want to make it an Extension method of Request.Form.

One more problem

After updating my assembly references in Web.config and reloading the site, I received an error because it could no longer find the referenced assembly.  I checked in my bin folder and sure enough the assemblies were not there.  Compiling the solution did not replace them as it had before, so I copied them into bin from the C:\Program Files\Microsoft ASP.NET\ASP.NET MVC CodePlex Preview 5 directory and reloaded the site.  Once again, all is working properly.

Categories: ASP.NET MVC

Updating to ASP.NET MVC Preview 5

September 23, 2008 1 comment

Well, I once again fell off the wagon when it comes to updating this site. I’ve been so busy working on my new ASP.NET MVC project that I even missed the Preview 4 update. That would be bad enough, until I recently found out that Preview 5 is now out. What a slacker I am!

So I spent the last little bit updating my Preview 3 projects to Preview 5. I don’t know how much of this was Preview 4 specific since I skipped it entirely. Here is what I did:

  1. Uninstall Preview 3 from my PC.
  2. Close all Visual Studio instances.
  3. Install Preview 5.
  4. Open my MVC projects.
  5. Remove previous references to System.Web.Abstractions, System.Web.Mvc, and System.Web.Routing.
  6. Add these references back, pointing now to the new install path.
  7. Add a reference to Microsoft.Web.Mvc, found in the same location.

Breaking Changes

I had used System.Web.Mvc.BindingHelperExtensions in several locations, but this functionality has been moved to the Controller class. To correct it, simply replace the calls to BindingHelperExtensions.UpdateFrom(model, Request.Form) with UpdateModel(model, Request.Form.AllKeys).

That was all I had to do to get it up and running. Now I need to uninstall Preview 3 from the server, install Preview 5, and reload my sites.

Categories: ASP.NET MVC

Updating from ASP.NET MVC Preview 2 to Preview 3

June 11, 2008 6 comments

I have been using Preview 3 since it was recently released, but only in a couple of test projects and in conjunction with learning more about my new found love: jQuery. This morning, I thought I would undergo the task of updating one of my “real” projects from Preview 2 to Preview 3. Unfortunately, it wasn’t as straight-forward as I had hoped, so I wanted to share the process with you.

Updating References

First things first: my project is set to automatically copy the DLL references to the Bin directory, so even though Preview 3 is installed on my machine, pre-existing projects have no knowledge of it. This was confirmed by trying to use the new View method to call a view page. This is actually pretty obvious and was expected.

To correct it, I first had to remove the References to System.Web.Abstractions, System.Web.Mvc, and System.Web.Routing. Maybe it is available but I just don’t know about it, but I was sort of surprised that there is not an “Update Reference” feature in VS.

Then I had to add references to their new versions, found in the “C:\Program Files\Microsoft ASP.NET\ASP.NET MVC Preview 3\Assemblies” directory (default install location: YMMV).

Finally, to ensure there was still no confusion, outside of Visual Studio I navigated to the Bin directory and deleted the previously copied DLLs. This may not be necessary, as I expect the IDE to properly detect that a different version is now in play and copy the new version over the old. Since I am not so optimistic, however, I went ahead and deleted them manually. The next Build properly copied in the updated DLLs.

Correcting Compiler Errors

At this point, the Solution would not compile for two reasons. First, RenderView no longer exists since it was replaced with the simpler View method. I’m sure that if this had been a Beta or RC that they would have provided a new RenderView that simply wrapped the new View method and returned null. This would have preserved backwards compatibility, but hey, as good as this stuff is it is still just a Preview level technology, so I can’t complain. Besides, I ultimately agree with their decision because it would be silly to retain a method you don’t want available in the final Release.

Now, if you have a lot of RenderView calls and are Find-And-Replace averse, you can add a simple local method to your Controller class to do just what I was suggesting:

private void RenderView(string viewName)
{
    View(viewName);
}

I did not do this, but I don’t see why it wouldn’t work. And of course, if you are using any more complicated signatures you’ll have to replicate them as well.

Second, all of the ViewPages that use a custom ViewData type, you have to change all the property calls to now reference ViewData.Model.xxx. I just let the compiler direct me to where I had done so and updated them manually.

After making these changes, the solution compiled successfully.

Updating Web.Config

And now for the part that wasn’t as straight-forward. Web.Config contains “Add Assembly” tags that hard code references the assembly names and PublicKeyTokens for several assemblies, including System.Web.Abstractions and System.Web.Routing assemblies mentioned above. At run-time, the assemblies could not be loaded. I’m not sure why the refence replacement did not update these, but I believe the PublicKeyTokens had been changed. To correct them, I opened the Web.Config of a working Preview 3 project and copied those two lines.

Running the site again produced a separate instance of the same error, this time in the HttpModules section trying to add “UrlRoutingModel”, so I copied the appropriate line from the new Web.Config to the old one. I went ahead and went through the entire Web.Config looking for references to any of the three DLLs in question and found a couple more which I also replaced.

The Dreaded Blank Page Issue

At this point, the Solution compiled, but trying to run the site produced a blank page. Unsure as to the cause, I copied the entire Web.config file contents over (retaining my custom mods, of course), but to no avail. If I typed in the full URL of the default {controller}/{action} the page threw an error, but at least that was progress! It turns out in the Index.aspx I was using the ViewData.ContainsDataElement(“key”) method, which no longer exists. I changed this to ViewData.Keys.Contains(“key”) and the page would now load. When I tried it again from the root, however, I still received a blank page.

I remembered having a frustration right after switching to Preview 3 that no matter what Routing I added, the Default would always go to the Home controller. I found the answer at the ASP.NET MVC Forums: in Preview 3, the Default.aspx Code Behind includes a hard-coded Response.Redirect(“~/Home”) in the Page_Load method. I changed it to my default Controller name and everything began to function as expected. Remembering this experience led me to wonder if the problem was somehow related to Default.aspx, which would produce a blank page if successfully called. I have a Routing that is supposed to address this that worked fine in Preview 2, but apparently it no longer functions in Preview 3. Anyway, to make a long story shorter, I was going to add this to the Default.aspx Code Behind only to find that there was no Code Behind file in Preview 2.

Not being an ASP.NET developer, I’m not sure what to think of this, and I did not know any other way to handle the problem. I deleted the original Default.aspx file and added a new Web Form to my Project. I replaced the default Designer Code and the relevant Code Behind code to match my successful Preview 3 Default.aspx file, and I also updated the Response.Redirect line to point to my desired Controller. Finally, all seems to have been returned to normal.

Conclusions

While it was frustrating to work through, in hindsight it wasn’t all that bad. The changes are pretty easy to implement, once you know where the traps lie. And the moral of the story is simple: this is Preview technology, expect breaking changes.

Categories: ASP.NET MVC

[REPOST] – Deploying ASP.NET MVC on IIS6.0

June 6, 2008 2 comments

Last week, I finally got the ball rolling on our IIS server. With a little help from a friend, I managed to get the SSL Certificate installed. A quick tutorial, and the site was moved to the server but it would not respond. Monday, I managed to get the site to respond by installing the .NET 3.5 framework on the server and I mistakenly thought it was up and running, so I released it to the beta testers. Of course, immediately the testers informed me that only the home page was showing, while all other links returned a 404 message.

I went through several efforts and can now happily say that it does work, so I am officially saying it is deployed. It is far from finished, but it is live on the web (sorry, I can’t share the address at this time). Here are the steps I followed that got it running:

  1. Install .Net Framework 3.5 on IIS Server
  2. Change Route URLs in Global.aspx.cs to include the .mvc extension (this is in the comments for that file)
  3. Install ASP.NET MVC Preview 2 on the IIS Server.
  4. Add an ISAPI extension to the application for .mvc that points to “c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll”.
  5. Uncheck the “Verify that file exists” box on the Extensions configuration dialog.

The last one is what finally made all the pieces fall into place. I don’t know if it is a “DUH” sort of a thing, but you have to remember that I am not an IIS or ASP.NET guy.

I found information on all but the last entry scattered across the web. Hopefully by putting them all in one place it will help some poor wayward soul in the future. According to those resources, these steps should also work for IIS7 in classic mode (integration mode? are those the same?) but should be unnecessary in the default IIS7 configuration.

At any rate, it lives!

Categories: ASP.NET MVC

ASP.NET MVC Source Code Released

March 21, 2008 Comments off

ScottGu has just announced the release of the ASP.NET MVC Source Code. You can download the code from CodePlex. It is important to note that this does not mean MVC will be open source (or that it won’t be), just that they are sharing the code during development so that we do not need to wait for their releases to correct bugs locally. So while you can create a custom implementation, you cannot distribute it, and I wouldn’t want to rely on it.

Categories: ASP.NET MVC

ASP.NET MVC Wish List

March 10, 2008 4 comments

Last Updated 03/12/2008

This morning I watched a video from Mix08 of Scott Hanselman’s session on ASP.NET MVC. I enjoyed the presentation, although I’m sure I will have to watch it several more times. The Routing capabilities are phenomenal but they will take a little while to get my head around. For now, the default Routing mechanism should suit my purposes just fine. I can also see that I am going to have to learn about Unit Testing, so that (in Scott’s own words), I don’t “suck”.

I have been developing a site using the new MVC approach, and overall I ahve to say I finally feel right at home in ASP.NET. I still get all the C# and Framework goodness I am used to, but I can now do it in the close-to-the-HTML way that I am familiar with. Let’s face it, until ASP.NET, WordPad was my web IDE of choice.

In the video, Scott asks us to blog and post about what we would like to see done differently in MVC, so that is the purpose of this post. I will use it as a running tally of my MVC Wish List. My first item was addressed in Scott’s presentation: I wanted the ability to route all non-conforming traffic to a default page rather than relying on the web server configuration and 404 files, and all that ugliness. Well, apparently you can already do this by declaring a *catchall Route. When I figure out the mechanics of this I will try to post a sample.

The Wish List:

1. Make UrlHelper.Action() Static

Make appropriate UrlHelper methods (and probably also HtmlHelper) available in a static context. I wanted to add standard navigation to my page in my custom MasterPage, but I could not use the Url.Action( action, controller) method because at that point there is no ViewPage instantiated. I think this would provide a uniform approach to Url writing.

2. Supply a pre-action Controller Event – added 3/11/2008

I think it would be great to have a generic event (or maybe a partial method?) that would execute before the controller begins the action method. This behavior could be simulated now, but each action would need to explicitly call the method. Implementing it this way would ensure that it was executed every time the controller was called. I think this could be great for things like caching, session management, security, logging, etc.

Update: Scott commented below about a possible solution to this already in place. I don’t think it is exactly what I had in mind, but I will experiment with it when I can and report back.

3. Add a TableRow method to HtmlHelper added 3/12/2008

I’ve been playing with Html.Form<T> and BindingHelperExtensions.UpdateFrom for building and processing form elements. I think both of these are very cool, and I will be posting about them shortly. Since Form elements are frequently presented in a Table, it would be good to have something like Html.TableRow<T>(inputType, label, T.Property) [obviously this is psuedo-code] that would create a simple table row based on the property with two elements:

<tr>
  <td>label</td>
  <td><input type="text" name="Property.Name"
    value="Property.Value"></td>
</tr>

The main benefit of this would be automatically generating the correct property name, so that it lined up perfectly with the UpdateFrom functionality. Another benefit would be to have it automatically populate the Value attribute with the current value of the Property. InputType above would ideally be able to accept the results of Form.Select, Form.Textbox, etc., or could be overloaded with an enum and some additional parameters.

OK, so that is the short (and boring) list for now. As I get further into the project, I’m sure I will find more, but as of now I have a lot more to rave about than to complain about. Keep up the great work fellas!

Categories: ASP.NET MVC