Twitter Feed Popout byInfofru

OverrideThis.com

Adventures in .NET Software Craftsmanship!

CapArea.NET–jQuery Mobile Introduction

 

imageAs promised, the following is the link to the bitbucket repository with all the sample code for my presentation on jQuery Mobile on the ASP.NET MVC platform.

https://bitbucket.org/rhp_74/overridethis.rsvpmobilesample

I would like to thank everybody who attended the user group and once again thank the Capital Area.NET User Group leadership for allowing me to share my ideas and thoughts in such a great venue.  Now, go build something and lets conquer the mobile space!

WebPiCmdLine–Easily provision your Web Servers!

The Web Platform Installer is Microsoft’s solution for distributing framework, products and applications that revolve around their web platform solutions.  If you are a web developer like me, it is probably the first thing you need to install on your development box or on the servers you manage.  Needless to say, I am a big fan but I don’t think I realized its true potential until I stumbled into the command line version of the Web Platform Installer, also known as the WebPiCmdLine.  Now, I get to do a lot of the infrastructure work in the projects that I take part of that means provisioning servers, installing the Continuous Integration software (Build Server), automating deployments to staging and production environments. In other words, I implement and design Deployment Pipelines for Continuous Delivery processes.  Anyway, too much conversation, lets look at a couple of working examples of when the WebPiCmdLine is useful and convenient.

 

Example 1 – Ramping up a Basic Developer Box

Lets say you want to install basic development tools on a Windows 7 Professional fresh install, perhaps you are performing a demo of a basic web application or maybe you are installing the latest and greatest technology and don’t want to ruin your current development environment.  Well one way you could setup all the required software on a fresh install  is to download the Web Platform Installer and browse through their list of frameworks, products and applications and click which products you want to install and your done.  The drawback though, is that you would have to be clicking around to find all the products and accepting all the EULA (End User License Agreement), it just takes too much attention and time.  The quick and easy way is to use the WebPiCmdLine to do the work.  Now my assumptions for the following snippet of code is that you have downloaded the WebPiCmdLine and extracted its content to a local folder on your drive, in my case “C:\Installer\WebPiCmd\”, the following script is located in the “C:\Installer\” folder.

 

@rem installer.cmd
SET WebPiCmd=.\webpicmd\WebPiCmd.exe
%WebPiCmd% /Install /Products:NETFramework4 /AcceptEula
%WebPiCmd% /Install /Products:SQLExpress /SQLPassword:P@ssw0rd /AcceptEula
%WebPiCmd% /Install /Products:SQLManagementStudio /AcceptEula
%WebPiCmd% /Install /Products:VWD /AcceptEula
%WebPiCmd% /Install /Products:MVC3 /AcceptEula
%WebPiCmd% /Install /Products:MVC4VS2010 /AcceptEula

 

Example 2 – Web Server for ASP.NET MVC Applications

The setup would be the same as above but in this scenario we are installing on top a Windows Server 2008 R2 fresh install.  This would be our web server to showcase a basic ASP.NET MVC application.

 

@rem installer.cmd
SET WebPiCmd=.\webpicmd\WebPiCmd.exe
%WebPiCmd% /Install /Products:NETFramework4 /AcceptEula
%WebPiCmd% /Install /Products:IIS7 /AcceptEula
%WebPiCmd% /Install /Products:MVC3 /AcceptEula
%WebPiCmd% /Install /Products:MVC4VS2010 /AcceptEula

 

Conclusion

I wrote a blog, not so long ago, about installing Rails on Ubuntu and how I had scripted out a basic install to ease the process of rolling a new Ubuntu image and rebuilding my developer environment.  The script that I wrote was fairly complex and tedious, but if a Linux noob like me could write it anybody can.  At the time, I felt there was no equivalent easy way to perform quick and clean scripted installations on the Windows platform but recent research has shown me that times are changing.  The WebPiCmdLine is just one of the relatively new tools (see NuGet, Chocolatey, or PowerShell)  that are providing developers the power to write deployment and automation scripts for the windows platform.  One comment, I do feel that the Web Platform Installer is powerful and useful enough that it really shouldn’t be only associated with the web, why not re-brand it as the Windows Platform Installer, and let it be used for installing anything on the operating system.

Bundling and Minimizing JavaScript and CSS with ASP.NET 4.5

I am in the process of getting back from the Build 2011 conference in Anaheim, California where  I got to see a ton of stuff related to Windows 8 development and designing Metro style application, and I shall blog a bit on the topic after I have had a good chance to digest all the information.  But right now, I just want to showcase one of the coolest new features of ASP.NET 4.5 “Bundling and Minimization of JavaScript and CSS”.

 

Now for those of you not familiar with the benefits of bundling and minimizing your JavaScript and CSS files, lets just say that reducing the number and raw size of web requests a browser needs to make to interact with your server is going to make your application faster.  A faster web application in most internet business scenarios equals more clients equals more money ( faster = more clients = more money).

 

So you might be asking yourself how complicated is it to setup Bundling and Minimizing of JavaScript and CSS in an ASP.NET 4.5 web application, and the short answer is, not hard at all.  You can setup bundling and minimizing in your Global.asax Application_Start to define what to bundle (See following snippet).

 

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    RegisterBundlers();
}

private static void RegisterBundlers() {

    BundleTable.Bundles.AddDefaultFileExtensionReplacements();
    BundleTable.Bundles.AddDefaultIgnorePatterns();
    BundleTable.Bundles.AddDefaultFileOrderings();

    var cssBundle = new Bundle("~/Content/css", typeof(CssMinify));
    cssBundle.AddDirectory("~/Content", "*.css", false);
    BundleTable.Bundles.Add(cssBundle);
}

 

Finally, you can modify the reference to your scripts and styles in your layout or master page to target the proper resources.

 

<link href="Styles/css" rel="stylesheet" type="text/css" />
<script src="Scripts/js" type="text/javascript"></script>

 

For more information make sure to read the ASP.NET 4.5 Preview bits release notes (here).

Learning Razor-Shared Content & Layout

As web developer’s in the .NET world we have been spoiled by the advantages of using centralized master pages for managing shared content and layout since the 2.0 version of the .NET Framework.  The ASP.NET MVC 1.0 Framework was no exception we were able to take advantage of our knowledge of ASP.NET master page’s to layout the content of our views.  Now, Razor is no exception either, we still will have the ability to centralize the way content is laid out in our application but some of the mechanics of how the process works have changed.  In fact, one could argue that the way layout is defined in Razor is more inline with the way the Spark view engine (http://www.sparkviewengine.com) does rendering than traditional master pages.

 

Layout Pages

In Razor the concept of a master page is equivalent to a layout page, and one could argue that a similar comparison could be made between the concept of ASP.NET placeholders and sections in Razor.  The following snippet shows what a very basic Razor layout page looks like.  As you can see this is mostly a plain vanilla HTML file the only exception is the directive @RenderBody() which is just a method call that tells Razor where to render the Contents of the child view.

 

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>My WebSite</title>
    </head>
    <body>
        @RenderBody()
    </body>
</html>

 

A basic child view would just specify its layout page and provide the content that is going to be rendered by the @RenderBody() method. As you can see in the following snippet the code for the template is very minimalistic and elegant.

 

@{
    Layout = "~/_SiteLayout.cshtml";
}

<h1>Hello World!</h1>
<h2>Hello World!</h2>
<h3>Hello World!</h3>

 

So far the two samples (snippets) have been very basic, so lets complicate things a bit what if we wanted to have a three column layout.  Well we would still want the main section of the page to drive of the @RenderContent() functionality but for the additional sections you can use Razor’s @RenderSection() method to define additional section’s that can be filled with content from our child views.  The following is the snippet for a three column layout page using CSS.

 

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>My WebSite</title>
        <style>
            #container { width: 700px; }
            #left { float: left; width: 150px; }
            #content { padding: 0 210px 0 160px; }
            #right { float: right; width: 200px; }
            .clear { clear: both; }
        </style>
    </head>
    <body>
        <div id="container">
            <div id="left">
                @RenderSection("left", required:false)
            </div>
            <div id="content">
                @RenderBody()
            </div>
            <div id="right">
                @RenderSection("right", required:false)
            </div>
            <div class="clear"></div>
        </div>
    </body>
</html>

 

The “required:false” parameter specifies if the child view is required to provide content for this section in our case the left and right sections will be optional.   The following is a sample snippet of a page that provides content for all sections, as you can see it is still very minimalistic and elegant.

 

@{
    Layout = "~/_3ColLayout.cshtml";
}

<h1>Main Content</h1>

@section left {
    <h1>Left Content</h1>
}

@section right {
    <h1>Right Content</h1>
}

 

Well, this sums up all the basic information you should need to get started with using layout pages in Razor.  Thanks for reading!

Security Trimming an ASP.NET SiteMapCollection

Yes, I know what everybody is thinking right now, Don't SiteMaps already provide functionality for Security Trimming?   Well they do and they don't.  This functionality is available only if you are using an implementation of the ASP.NET MembershipProvider and RoleProvider.  In the applications that I have to work with in a day to day basis that is rarely the case, I always have to develop a custom security provider using forms or windows authentication that support some far fetched business requirements.   I still however love to use SiteMaps and have rarely seen the need to customize the base SiteMap provider for any other reason.    So, in order to have security trimming and still use and bind the information from my SiteMap I wrote the following block of code that just begged to be re-factored.

Exhibit A - Code that needs (begs) for refactoring.

// do security trimming.
List<SiteMapNode> nodes = new List<SiteMapNode>();
foreach (SiteMapNode node in SiteMap.RootNode.ChildNodes) {
    if (node.Roles.Count == 0) {
        // just add.
        nodes.Add(node);
        continue;
    } else {
        // validate security.
        foreach (var role in node.Roles) {
             if (this.Page.User.IsInRole(role.ToString())) {
                 nodes.Add(node);
                 break;
             }
        }
   }
}

// return list.
this.ListViewTopMenu.DataSource = SiteMap.RootNode.ChildNodes;
this.ListViewTopMenu.DataBind();


I decided that, because I was going to need to reuse this functionality in several places and I wanted to avoid creating a class that would perform this task specifically,  that I should add a new method to the SiteMapCollection class using a C# 3.0 Extension Method. 

Step 1 - Extension Method

public static class SiteMapNodeCollectionExtension {
	
	public static IList FilterByRoles(
		this SiteMapNodeCollection nodeColl, 
		IPrincipal user) {
		
		// collection used to store array values to return to browser
		List nodes = new List();

		// iterate through the node collection to return the valid nodes.
		foreach (SiteMapNode node in nodeColl) {
			if (node.Roles.Count == 0) {
				// just add.
				nodes.Add(node);
				continue;

			} else {
				// validate security.
				foreach (var role in node.Roles) {
					if (user.IsInRole(role.ToString())) {
						// add to collection.
						nodes.Add(node);
						break;
					}
				}
			}
		}
		return nodes;
	}
	
}

 

This blog is not intended to be a tutorial, but I would like to point out the facts that C# Extension methods have to be defined in a static class as a static method and the first parameter must be the class to be extended (Notice the use of the 'this' keyword on the fist parameter).

Step 2 - Refactoring of the client code.

// bind list.
this.ListViewTopMenu.DataSource = SiteMap.RootNode.ChildNodes.FilterByRoles(this.Page.User);
this.ListViewTopMenu.DataBind();

Thank you for reading,

Roberto Hernandez