7/28/2014
Login
 Thoughts on Web Development
Language Versions Tuesday, November 11, 2008 10:46 AM

Language Versions

Some of the languages I've learned and used in the past have been: FORTRAN, COBOL, 360 Assembler, PL/1, Pascal, C, and C++. Currently, almost all my work has been in C#. Prior to C#, the languages I have been very static. I had assumed the same of C#. While I'm cognizant of the fact that API change (like win16 to win32), I'm not really used to the notion of languages having versions. However, the .NET platform has shaken that basic assumption.

 There are a number of fundamental changes which have occured to C# since it's initial release. What has made this more abscure is that there have also been changes in the version of the .NET Framework leading to the following matrix:

C# Version CLR Version Framework Version
1.0 1.0 1.0
1.1 1.1 1.1
2.0 2.0 2.0
2.0 2.0 3.0
3.0 2.0(updated) 3.5

This is somewhat confusing because there are framework versions, CLR versions, and language versions.

As I'm looking at doing some new work, I've been keeping current on the latest events in the .NET world. I've been pretty good about keeping up with changes in the framework api and changes in the CLR (per my review of Jeffrey Richter's book CLR via C# - it's a great book). However, since I've never expected much evolution of languages, I didn't pay too much attention to changes in the C# language. Well, I've been doing a little bit of updating lately. So what type of things have changed since version 1.1?

  • Lambda expressions
  • Expression trees
  • The var keyword, object and collection intializations and anyonymous types
  • Extension methods
  • Partial methods
  • Query expressions

Over the next/past couple of weeks, I'll be logging postings here which discuss these new features as well as what looks to be the future of ASP.NET and the data story coming out of Microsoft.

MVC
0 Comment(s) Add comment
 
Why MVC? Friday, October 24, 2008 8:08 PM

Casual web developers will probably stay with webforms. you switch to mvc when any of the following are important enough to switch:

  1. You are unit test developer (use test first design) are tried of webforms "fake" and complex event model.
  2. Are writing lots of javascript and tired of id's changing, and want standard html components.
  3. Want better seperation of view and controller code.
  4. Want a ruby on rails coding experience (mvc is easier with a dynamic language like ironpython, ironruby or javascript)
  5. You are commited to the mvc pattern, and want a supported platform
  6. You switched to jQuery (see #3)
  7. Your web site is going to be large and complex.

What are the disadvantages?

  1. No UI designer tools for it at this point.
  2. Requires good understanding of anonymous function and lambda
    expressions to take full use of it.
  3. Coding is harder with a highly typed languages like c# and vb.net,
    but dynamic style features are being added to these languages.
  4. Requires you know the mvc pattern and has a littler longer learning
    curve.
  5. Doesn't attempt to hide the stateless nature of a web site from the
    coder.
MVC
0 Comment(s) Add comment
 
NUnit Testing and Generating User Stories Friday, October 24, 2008 11:18 AM

NUnit Testing and Generating User Stories and ASP.NET MVC Applications

NUnit is a unit-testing framework for .Net languages. There are certain difficulties associated with Test Driven Development of ASP.NET webform applications. In order to do test, you have to pull your code out of the webpage portion of the application and run it into code outside the normal mode of application operation. This is because we're limited in our abilities to emulate what happens inside a web server. This isn't all bad because it forces the developer to structure application logic in a more tiered approach. One of the main goals of the ASP.NET MVC framework is to allow Test Driven Development in an easier manner.

One way to start an application is to begin with User Stories from your customers or clients. User stories should be interesting to the customer and have little to do with any technology driven discussion. For example if you were working on a blog application, you might have the following User Stories:

  • A user should be able to create a new blog entry
  • People should be able to add comments to a blog entry
  • People should be able to view blog entries
  • People should be able to view blog comments

To start the application, choose a story and start building a framework for the application. (As a side note, in Extreme Programming don't spend too much time on documenting requirements because things change.) Typically, Unit Tests are comprised of 3 stages: 1) Setup 2) Execution and 3) Verification.

MVC
0 Comment(s) Add comment
 
Creating Custom HTML Helpers for ASP.NET MVC Applications Thursday, October 23, 2008 3:37 PM

Creating Custom HTML Helpers for ASP.NET MVC Applications

An HtmlHelper is a method you can use in a view to render some special html content. The theory behind the Html helper class is that it makes life easier for you in that you don't have to type out the actual html. Why you would want to create a custom html helper is that there are a limited number of html helper methods built into the box. Custom html helpers allow you to create helpers which are customized to your design/development efforts. For example, there are no built in helpers which allow you to display database results in a table (huh? that can't be right).

There are two ways to create an html helper:

  1. The easy way - create a class which renders a string.
  2. Slightly less easy way - Extension method. If you want your html helper methods to work the same way as the built-in html helper classes, this is the way to go. In other words, if you them to show up in the view page under the Html helper class you would use this method. In VB you create a module with an <Extension> attribute. In C#, you'd have to create a sealed class with static functions.

Custom Html helpers seem like a nice thing if you're doing alot of html editing but they don't seem to go to the heart of application development.

MVC
0 Comment(s) Add comment
 
Unit Testing ASP.NET MVC Applications Tuesday, October 21, 2008 4:33 PM

Unit Testing an ASP.NET MVC Applications

Unit testing is of concern to two audiences: 1) Testers and 2) Test-driven developers. The ASP.NET MVC framework was especially designed to support (encourage) unit testing by testers and test-driven development.

There are different ways to test an ASP.NET MVC application:

  1. Test a view
  2. Test ViewData
  3. Test other results

To create the unit tests for the MVC application, open a new project in Visual Studio and select OK in the Create Unit Test Project dialog. You can select the Visual Studio default Unit Test framework or if you have another framework you like, you can create the unit tests based upon that. I'll have to look into this a bit more before writing any more detailed blog entries.

MVC
0 Comment(s) Add comment
 
Preventing Javascript Injection Attacks in ASP.NET MVC Applications (Part 1) Tuesday, October 21, 2008 2:03 PM

Preventing JavaScript Injection Attacks and Cross-Site Scripting Attacks in MVC Apps (part 1)

Whenever you ask your users for input, you run the rusk of someone doing something unreasonable. Unreasonable in the sense of mistaken input which causes some damage or that someone has maliciously does something bad. In the case of feedback forms, it could be easy for someone who has bad intentions to enter in some javascript code which might cause some problems. For example, a hacker could enter something like this into a textbox:

<script>alert(“Boo!”)</script>

If you feed this into a database and redisplay it without validating the input, everytime it is shown, it is going to show a javascript alert box. That can pretty annoying for your users. And while this is not awful for your users, it could be possible without data input validation to be opened to cross site scripting attacks (XSS). Cross site scripting attacks could allow hackers to collect your users personal information on a form and post it to their website or allow them to steal sensitive information stored in browser cookies.

Okay, so let's say your controller code looks like the following:

     
public class HomeController : Controller
 {
  private FeedbackDataContext db = new FeedbackDataContext();

  public ActionResult Index()
  {
       return View(db.Feedbacks);
  }

  public ActionResult Create(string message)
  {
       // Add feedback
       var newFeedback = new Feedback();
       newFeedback.Message = message;
       newFeedback.EntryDate = DateTime.Now;
       db.Feedbacks.InsertOnSubmit(newFeedback);
       db.SubmitChanges();

       // Redirect
       return RedirectToAction("Index");
  }
 }
MVC
0 Comment(s) Add comment
 
Preventing Javascript Injection Attacks in ASP.NET MVC Applications (Part 2) Tuesday, October 21, 2008 2:01 PM

Preventing Javascript Injection Attacks in ASP.NET MVC Applications (part 2)

The Index method displays the default view and passes to it the feedbacks stored in the database. The Create method takes the new Feedback item and adds it to the database. The Index view would look something like this:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="CustomerFeedback.Views.Home.Index"%> <%@ Import Namespace="CustomerFeedback.Models" %> <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">      <h1>Customer Feedback</h1>      <p>           Please use the following form to enter feedback about our product.      </p>      <form method="post" action="/Home/Create">           <label for="message">Message:</label>           <br />           <textarea name="message" cols="50" rows="2"></textarea>           <br /><br />           <input type="submit" value="Submit Feedback" />      </form>      <% foreach (Feedback feedback in ViewData.Model)      {%>           <p>           <%=feedback.EntryDate.ToShortTimeString()%>           --           <%=feedback.Message%>           </p>      <% }%></asp:Content>      

The Index view baskically contains two sections: the section to post the new feedback information to the /Home/Create action and the part which displays the feedback passed into the view from the controller. So, what can we do to prevent the input or injection of javascript into the database? We can take two approaches:

MVC
0 Comment(s) Add comment
 
Preventing Javascript Injection Attacks in ASP.NET MVC Applications (Part 3) Tuesday, October 21, 2008 1:50 PM

Preventing JavaScript Injection Attacks and Cross-Site Scripting Attacks in MVC Apps (part 3)

  1. We can call Html.Encode on what we're displaying from the database in the view before sending it off to the browser (converts the braces to the appropriate literal):
         <% foreach (Feedback feedback in ViewData.Model)
    {%>
      <p>
      <%=feedback.EntryDate.ToShortTimeString()%>
      --
      <%=Html.Encode(feedback.Message)%>
      </p>
    <% }%>
    
  2. Another approach you could take is to encode input before it is submitted to the database. You can do this in the Create method of the controller:
              public ActionResult Create(string message)
      {
           // Add feedback
           var newFeedback = new Feedback();
           newFeedback.Message = Server.HtmlEncode(message);
           newFeedback.EntryDate = DateTime.Now;
           db.Feedbacks.InsertOnSubmit(newFeedback);
           db.SubmitChanges();
    
           // Redirect
           return RedirectToAction("Index");
      }
    

In the first approach, we stored the actual javascript in the database. This might seem less safe to some but the advantage of it is that if you need to return it later as is, it is easier to deal with. If you take the second approach you may alter what the user has altered and it may be difficult to unalter it later.

MVC
0 Comment(s) Add comment
 
ASP.NET MVC URL Routing Monday, October 20, 2008 5:45 PM

ASP.NET MVC URL Routing

While URL routing is an optional aspect of ASP.NET webforms application, it is essential to ASP.NET MVC applications. It's how browser requests get over to MVC action controllers. When you create an ASP.NET MVC web application in Visual Studio 2008, the web.config file contains (among other things) the following lines:

		<modules runAllManagedModulesForAllRequests="true">
			<remove name="UrlRoutingModule"/>
			<add name="UrlRoutingModule"
type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, 
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
		</modules>
		...

The routing table is setup in the global.asax file:

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
        ...
        

The default route is setup to handle 85% of the routing requirements for your application. In the example above, the MapRoute method is naming the route as "Default", setting up the basic pattern for the route url and giving the parts names, and then initializes those parts with default values. Specifically in the code above, it sets the default controller as Home, the default action as Index, and the default id as nothing.

You run into limitations of the default URL routing pretty quickly. For example, if you were creating a blogging application you would want a URL similar to /Archive/11-06-2007. This obviously doesn't fit into the default routing scheme which would read the default as an action. You really want to use the date as a parameter. So, you have to put a new route into the URL routing table by editing the global.asax file. You want to add your new route before the one already in the routing table so that it gets routed first. The modified file looks like the following:

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Blog",  // Route name - this our new blog route
                "Archive/{entryDate}", // This gives us the archive action with the entrydate parameter
                new { controller = "Archive", action = "Entry"}  // and of course the results.
            );

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );
        }

Next we have to create a controller for the Archive action and we end up with a new controller class. It is important that we name the parameter for the action appropriately and that it matches what we named the parameter in the global.asax file (in this case, entryDate). Of course, there is no parameter checking going on in this example:

    public class ArchiveController : Controller
    {
        public ActionResult Index()
        {
            // Add action logic here
            throw new NotImplementedException();
        }
        public ActionResult Entry(DateTime entryDate)
        {
            return Content("You requested the blog entry for" + entryDate.ToString());

        }
    }
MVC
0 Comment(s) Add comment
 
MVC Views Monday, October 20, 2008 4:03 PM

MVC Views and HTML Helpers

Views are not the same thing as .NET aspx pages in that there is no direct correspondence between what URL you type in the address bar and what page is shown as a view. There is a level of indirection which occurs and it is up to the controller action to decide view is sent back to the browser. By default the name of the view returned from a controller action is the name of the controller action. For example, if the controller Product has a method named Index and it returns a default view, it is the Index view:

    public class ProductController : Controller
    {
        public ActionResult Index()
        {
            // Add action logic here
            return View();
        }
     }

Again, it is important to have the view in the correct directory structure. So, the view must be created in the Views\Product directory. You can specifically name the view which is returned besides defaulting to the same name as the Controller Action. It seems you have to use embedded script with views (which seems like a drag - but maybe I just don't know enough yet).

For ViewPages, there are two imporant properties:

  • ViewData - you use this to access all the data sent over from the controller action. The ViewData object can be thought of as a dictionary type of object containing key/data pairs. You can certainly stick database records into the ViewData object.
  • Html - this property exposes the HtmlHelper class.
    • The Html helper class contains methods like Html.TextBox() and Html.SubmitButton to render html elements. So that the following code would render a textbox on the form with the ID of firstName:
      <%= Html.TextBox("firstName") %>
MVC
0 Comment(s) Add comment
 
MVC Controllers Thursday, October 16, 2008 2:54 PM

MVC refers to Model View Controller

MVC architecture depends alot on having things in the right folders and having the right names. So, when your ProductController.Index() function returns the default View(), it has to be in the \Views\Product directory.

Controllers

  • Controllers return ActionResults
    • ViewResults - contains HTML markup and content you want to send back to the brownser.
  • JsonResult
  • RedirectToRouteResult - allows you to re-route the controller action to another controller action.
  • ContentResult - allows you to send some text back.
  • Custom Action Result - create your own custom action result. For example, an Excel spreadsheet file.
MVC
0 Comment(s) Add comment
 
MVC Overview Wednesday, October 15, 2008 4:34 PM

I've been watching the videos from www.asp.net\mvc. Here are some of my notes:

MVC Overview

Model == Contains business and data access logic.

View == contails HTML markup and content that is returned to the browser.

Controller ==> fires off some logic in response to a browser request.

In Visual Studio, you want to select the ASP.NET MVC Web Application under New Project. I originally thought you would want to select Open Website but that is not the case. Visual Studio also lets you select to have Unit Tests created at the same time. The default MVC Web Application contains three folders: Models, Controllers, and Views. The default MVC web application is very simple and consists of the home page and an about page. The important thing to notice about the application is the url - there is no extension listed for the Home or Home/About pages. No .aspx, no .html. This highlights the difference between an ASP.NET application and an MVC application.

 For an ASP.NET application, a url == an .aspx page.

This is not true for an MVC application. For an MVC application, a url == a Controller Action.

To summarize, an ASP.NET application is more content centric. Whereas, an MVC application is more logic-centric. This leads to the observation that url routing is a key aspect of MVC application architecture. Look in the global.asax file to see where the route table is setup. During the Application_Start the routing table is initialized.

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

        }
        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }

The default routing table is set up to handle a controller, an action, and an id. The default route is controller = "Home" action = "Index" and id = " ".  So, if you typed in the url /MyController/DoSomething/34, the MyController controller would be invoked with the DoSomething action and an id of 34.

So, the HomeController.cs file int he Controllers directory invokes Index view contained in the Views\Home directory by default. The directory structure and file names are by convention and have to be followed for everything to work. This seems particularly fragile to me but I don't know very much at this point.

Models are supposed to contain all the logic for the application. The controller actions are supposed to be skinny and the model is supposed to do all the work in a series of classes.

MVC
0 Comment(s) Add comment
 
© LimberTech 2014