Use ViewModels to manage data & organize code in ASP.NET MVC applications

The concept of the ViewModel isn’t just for ASP.NET MVC, as you’ll see references to ViewModels throughout the web in articles and blog posts about the MVC, MVP, and MVVM patterns. Those posts and articles can center around any number of technologies such as ASP.NET, Silverlight, WPF, or MVC… This post will investigate ViewModels as they apply to the world of ASP.NET MVC.

What is an ASP.NET MVC ViewModel?

In ASP.NET MVC, ViewModels allow you to shape multiple entities from one or more data models or sources into a single object, optimized for consumption and rendering by the view. The below image illustrates the concept of a ViewModel:

 

image_16

The purpose of a ViewModel is for the view to have a single object to render, alleviating the need for UI logic code in the view that would otherwise be necessary. This means the only responsibility, or concern, of the view is to render that single ViewModel object, aiding in a cleaner separation of concerns (SoC). Concerns are distinct aspects of the application that have a particular purpose (i.e., concern), and keeping these aspects apart means your application is more organized, and the code more focused. Putting data manipulation code in its own location away from the view and controller, enforces SoC.

Using ViewModels in MVC for finer granularity and better SoC leads to more easily maintainable and testable code. Remember, unit testing is about testing small units.

Along with better coding practices, there are many business reasons demonstrating why you might consider using ViewModels:

  • Incorporating dropdown lists of lookup data into a related entity
  • Master-detail records view
  • Pagination: combining actual data and paging information
  • Components like a shopping cart or user profile widget
  • Dashboards, with multiple sources of disparate data
  • Reports, often with aggregate data

The above scenarios are common to a wide variety of applications, and deal with more complex data than basic CRUD forms-over-data page (e.g., a simple 1:1 mapping to the db table). For example, providing a list of states, and ensuring that the state that matches the state of current customer, means that you need to either provide two sets of data or a single set of customer/state data combined, as shown in the image below.

 

image_6

Some scenarios such as a lookup table representing states in the USA, could easily work with either ViewModels or a ViewBag/ViewData object, so there is some potential overlap at times. It’s up to the application architects and developers to decide what works best with their exact use case.

Creating a ViewModel

Although a ViewModel consists of multiple entities, at its core a ViewModel is still just a class – and one that doesn’t even inherit from anything special, as many MVC classes do.

Physically, ViewModels can exist in different locations, listed below:

  • In a folder called ViewModels that resides in the root of the project. (small apps)
  • As a .dll referenced from the MVC project (any size app)
  • In a separate project(s) as a service layer, for large applications that generate view/content specific data. (enterprise apps)

Since a ViewModel is just a class, the easiest way to get started using one is to create a new folder named ViewModels and add a new code file to it.

To create the CustomerViewModel ViewModel, add the Customer and StatesDictionary types as properties to form one CustomerViewModel class. In the example below, the CustomerViewModel class contains the newly defined properties.

public class CustomerViewModel 

{

    public Customer Customer { get; set; }

    public StatesDictionary States { get; set; }

    public CustomerViewModel(Customer customer)

    {

        Customer = customer;

        States = new StatesDictionary();

    }

}

Generally, ViewModels contain the word “ViewModel” as part of its name; however, the conventions at work here are for consistency in code readability, since other classes in MVC state their intents in their names as well (e.g., names of controllers, action methods, etc…use conventions in their names).

The StatesDictionary class is a simple Dictionary object containing two type parameters of type string. The class also contains the definitions for all the members in the Dictionary (i.e., the state data). The only property in the StatesDictionary class is the StateSelectList, which is an object that Html Helpers use with to render an HTML <select> element that displays a listing of states. The type Dictionary<string, string> in the StateSelectList property maps to the state abbreviation then state name, respectively.

public class StatesDictionary

{

    public static SelectList StateSelectList

    {

        get { return new SelectList(StateDictionary, "Value", "Key"); }

    } 

    public static readonly IDictionary<string, string> 

        StateDictionary = new Dictionary<string, string> { 

      {"Choose...",""}

    , { "Alabama", "AL" }

    , { "Alaska", "AK" }

    , { "Arizona", "AZ" }

    , { "Arkansas", "AR" }

    , { "California", "CA" }

    // code continues to add states...

    }; 

}

Data that lives in small lists and infrequently changes, like the StatesDictionary class, exists in all types of applications. In real world applications, you’ll find a variety of methods for dealing with lookup data such as a list of states – often XML files and SQL tables. You can replace the code in the StateDictionary method to use entities from Entity Framework, read data from files, or any data access code that you require.

After creating the ViewModel, the next steps are to instantiate it in a controller and return it to the view.

Getting the ViewModel to the view

Starts with the controller…

Sending a ViewModel to the view for rendering will work the same as when dealing with a model. Since it’s just a class, the view doesn’t know, and doesn’t care, where the model or ViewModel came from. You can create the instance of the ViewModel class in the controller, or resolve it if using an IoC container. Remember that just as you would do with views, you should keep controllers clean of unnecessary code, meaning that only code that fetches the model or ViewModel belongs here, and little more.

public ActionResult Edit(int id)

{

    Customer customer = context.Customers.Single(x => x.Id == id);

    var customerViewModel = new CustomerViewModel(customer);

    return View(customerViewModel);

}

Then the view renders the ViewModel…

In order for the view to know what object to use, set the @model keyword to point to the ViewModel, just like you already would with a regular model.

@model FourthCoffee.Web.ViewModels.CustomerViewModel

Because the Customer object is a property of the ViewModel, you’ll see the model.Class.Property syntax to access the ViewModel data, similar to the following line of code.

<div class="editor-label">

    @Html.LabelFor(model => model.Customer.FirstName)

</div>

<div class="editor-field">

    @Html.EditorFor(model => model.Customer.FirstName)

    @Html.ValidationMessageFor(model => model.Customer.FirstName)

</div>

@* ...View code continues rendering properties... *@

Additionally, you can edit the Edit/Create views so that the DropDownList containing a list of the states will display, and display the correct state matching that of the customer.

<div class="editor-field">    

    @Html.DropDownList("state", new SelectList(StatesDictionary.StateSelectList, 

                       "Value", "Text", Model.Customer == null ? "" : Model.Customer.State))

    @Html.ValidationMessageFor(model => model.Customer.State)

</div>

As you might have noticed, using a ViewModel is just as easy as using the ViewBag or ViewData objects. ViewModels, however, provide those extra benefits like being easier to test and optimize.

Checking the results

After a user navigates to the /Customers/Edit/1 URL in the browser, the Razor view engine renders the CustomerViewModel similarly to the following screen shot.

image_4

The State DropDownList displays the states and the current state for that customer, as expected.

Digging Further into ViewModels

Because ViewModels render pre-manipulated data that no longer have those 1:1 mappings between model classes and database tables, you’ll need to do create mappings yourself. You can manually map small ViewModels, but this will quickly become burdensome when mapping larger classes, especially when working with parent-child-grandchild, multi-level, or complex data. This is where a tool such as AutoMapper comes into play. AutoMapper will let you fluently setup mappings between ViewModels and models more easily than doing so manually, or writing your own mapper.

Here are some tips for using ViewModels:

  • Put only data that you’ll render in the ViewModel.
  • The view should direct the properties of the ViewModel, this way it fits better for rendering and maintenance.
  • Use a mapper when ViewModels become complex.

Some tools that can help assist you in generating POCOs (Plain Old CLR Objects) for models and ViewModels are:

POCO Generator

EF POCO Templates

In addition to these tools, you can use MvcScaffolding to create actions and views based on ViewModels. MvcScaffolding, invention of ASP.NET team member Steve Sanderson, gives you more power in creating CRUD, repository, unit test and other templates quickly and painlessly. Check out Steve’s Multi-part series on MvcScaffolding here. MvcScaffolding works with ViewModels as well as models.

You should always prefer using a ViewModel rather than instantiating multiple models and putting that manipulation code in the controller.

Summary

ViewModels help you organize and manage data in MVC applications when you need to work with more complex data than the other objects allow. Using ViewModels gives you the flexibility to use data as you see fit. ViewModels area generally a more flexible way to access multiple data sources than models + ViewBag/ViewData objects.

Further reading: Comparing the MVC and MVVM patterns along with their respective ViewModels

Download the code!

A 30 year sorting algorithm saga: from 250k to 14GB in one minute

Microsoft Research busted through the world record for sorting an unprecedented amount of data in under one minute, with a new sorting technique called MinuteSort (with flat datacenter storage). The Microsoft Research team sorted the equivalent of two 100-byte data records for every human being on the planet.

That’s a rough equivalent of a short email message, for example, this series of 1’s represents 200 bytes:

1111111111111111111111111111111111111111111111111111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111111111111111111111111111111

This is 200 bytes of a plain text message you might send in an email.

How much wood could a woodchuck chuck if a woodchuck could chuck wood?
Good woodchucks chuck much.

Multiply that by the population of planet Earth, currently at around 7 BILLION, and the result is 1,400,000,000,000 bytes, or over 14GB in one minute.

That’s a lot of data to wade through, and sorting hasn’t always been so fast and sexy. Take a look at this scan of an ancient TI-99 programming magazine article from 1983 on five popular sorting algorithms, some still used today.

  • Bubble Sort
  • Shell Sort
  • Selection Sort
  • Heap Sort
  • Quick Sort

Here’s a sampling of the article, page 1 & 2 (Download the complete 5 pages)

 

Ti-1_2ti-1a_2

 

Turn to the last page or the article and you can see that in 1983 the Quick Sort, wins the honor of sorting roughly 250k in about 1 minute and the Bubble sort can run equivalent of the 200 byte sample sample above in about 6 minutes (ouch).

image_12

How times have changed.

Sorting basics from Carnegie Mellon http://www.cs.cmu.edu/~adityaa/211/Lecture12AG.pdf [pdf]

Download the complete article

Big congrats to the awesome team at Microsoft Research! 100 points and a Geritol if you are old enough to have used a TI-99 or have read this magazine.

Partial views in ASP.NET MVC

What is a partial view and when should I use it?

As developers become familiar with the ASP.NET MVC model, they’ll naturally want to create reusable components filled with content & code. In Web Forms, we could do this by creating a web user control or a web server control, but in MVC, we will use partial views. You’ll notice that conceptually, all of the scenarios below would work for either technology.

  • A stock ticker that’s displayed on each page in an application.
  • A calendar widget that’s displayed on multiple pages in application.
  • A login box.
  • A social networking component used on multiple pages, such as a Facebook Like button.

While ASP.NET MVC partial views may behave similarly in theory to web user controls, syntactically and functionally, the two behave differently. Web user controls found in web forms uses ViewState, PostBacks, and Events while MVC partial views do not use any of the preceding techniques for managing state. Just as ASP.NET web user controls do, partial views can tap into the models contained in your application as well as share data between other application components.

Rendering partial views

Partial views in ASP.NET MVC 3 allow the developer to create reusable content with the very precise and clean Razor syntax (or ASPX). The syntax that renders the partial view is implemented as an Html helper. The Html.Partial helper renders the partial view named “_FeaturedProduct” inline. The first argument of all overloaded methods in the call the @Html.Partial expect the view/partial’s file name, without the file extension. Adhering to convention, the @Html.Partial helper assumes the view resides in the \Views\Shared\ folder. Additional overloads in the @Html.Partial method allow you to pass ViewData/ViewBag objects between views/partials (see below under Sharing data…).

The code below demonstrates the call to render the featured product partial view.

<div>
  @Html.Partial("_FeaturedProduct")
</div
>

Partial views can be rendered inside a Layout Page (or if using MVC 2/3 w/ASPX, the Master Page) as well as regular views.

There are some cases where you might like to step aside and write directly to the HTTP Response stream rather than having a partial view render the results (partials/views use MvcHtmlString/StringWriter). To do so, use the Html.RenderPartial helper.

<div>
  @Html.RenderPartial(“_FeaturedProduct”)
</div
>

Use Html.RenderPartial for streaming images or other elements that are media-centric or where faster download times are highly important.

Creating a partial view

Both partial views and regular views are .cshtml files, with the difference being the folder where the partial views reside: \Views\Shared\. Use the Add New View dialog by accessing the context menu from the \Views\Shared node in Solution Explorer. The Add New View template dialog offers choices for creating your partial views, including the option for strongly typing views. Don’t forget to check off  “Create as a partial view” or you’ll end up with a lot of code to delete.

SNAGHTML44dfac8

Once you’ve created the view you can get started customizing it by simply editing the file. There’s no problem in deleting or modifying the view’s code, as there’s no designer tied to it. The code shown below (_FeaturedProduct.cshtml) is the same code the default view template creates, but modified to display the featured product differently:

<style type=“text/css”>
    .featuredProduct {border: solid 1px #000}
</style
>
<
div>
    <div>
        <h2>
            Our Featured product:<br />
            @ViewBag.FeaturedProduct.Name
        </h2>
    </div>    <div>
        <h3>
            Now discounted to $@String.Format(“{0:F}”, ((decimal)ViewBag.FeaturedProduct.Price)-100)
        </h3>
    </div>  
    <div>
        @Html.ActionLink(“Featured Product Details”, “Details”, new { id = ViewBag.FeaturedProduct.ProductId })
    </div> 
    <div>
        <img class=“featuredProduct” src=@Href(“~/Content/Images”)/@ViewBag.FeaturedProduct.ImageName” alt=Featured Product”/>
    </div
>
</
div
>

As with strongly typed views, strongly typed partial views also support dot notation syntax and access to the model, ViewBag, ViewData and other classes specifically designed for sharing data.

It should be clear when reading through the above code that the syntax of partial view looks the same as a regular view. The important take-away is not about the syntax but how the partial view is used. However, a syntactic benefit to developers is the consistency between both partial and full views, particularly when we need to share data between them.

Sharing Data between views and partial views

It’s a common occurrence to pass data between components of an application, and in this case those components are MVC partials, views & controllers. As previously noted, you should use the ViewBag or ViewData classes to share data across views and controllers. First, a few notes on ViewBag and ViewData:

  • ViewData was available in previous versions; ViewBag was released with MVC 3.
  • ViewData can contain any type of data in a name-value pair format. I.e., ViewData[“Message”] = “Welcome”;
  • ViewBag objects are just wrappers around ViewData objects, and allow developers to code to them using strongly typed syntax.
  • ViewBag objects can be extended by simply setting properties in a more fluent syntax. I.e.,  ViewBag.Customer = new Customer(1,”Smith”);

If code in a controller uses either the ViewBag or ViewData classes, those classes will be available throughout the view’s lifecycle, and that includes its partial views.

The preferable object is the ViewBag. Because of its more fluent and dynamic syntax, there’s more complex objects that can be shared quite easily between components. The sample below demonstrates setting up the ViewBag object in the controller so it will be available to all necessary components:

ProductModel productModel = new ProductModel();        
public ActionResult Index()
{
    ViewBag.FeaturedProduct = new FeaturedProduct(105, "The Most Awesome Bike Ever!", 1000.00M, "bike4.png");          
    return View(productModel.Products);           
}

The ViewBag is accessed inside the view or partial using the follows syntax:

@ViewBag.FeaturedProduct.Name

Summary

Partial views are a great way to reuse fragments of HTML and Razor syntax together, with the ability to easily share data.

Resources:

Introducing Razor

Introducing MVC Development w/the Razor View Engine

Razor View Syntax

How to Connect to SQL Azure through SQL Server Management Studio 2008 (SSMS 2008)

Most developers on the Microsoft stack that use SQL Server, and who are migrating their databases to SQL Azure, likely work in SQL Server Management Studio 2008 (SSMS 2008), Visual Studio, or a mixture of both, for DBA and data management tasks. Fortunately, SQL Azure has two options for those who need to administer, create, maintain, and develop using SQL Azure: The SQL Azure Management Portal and SSMS 2008.

Before you start — If you want to try out the online tools or see take SQL Azure for a spin with SSMS 2008, sign up for a 90 day free trial.

Connect to SQL Azure from SSMS 2008

You can use SQL Server Management Studio (including, and especially, SQL Express) to connect to SQL Azure, but you first need to have some information handy that you can find in the SQL Azure Online Management Portal. Once there, you can view your subscription information including the information you need to connect to a SQL Azure server or database.

image3

Here is the information you need:

  1. The fully qualified server name. See the blocked out, red, parts of above image, as to where you can locate your server info.
  2. Valid credentials that you have already setup via the online SQL Azure Management Portal (of course, the password is not available for viewing, as it should be memorized anyway)

Enter this information into the SQL Server 2008 Connect to Server dialog, and click the Connect button to authenticate. Don’t forget you must choose SQL Server Authentication before you may enter credentials.

image16

Upon successful authentication, SQL Server Management Studio opens. This is the exact same SSMS you are familiar with, with the only difference being that you have connected to SQL Azure instead of a SQL Server on your LAN.

SNAGHTMLa64d4e1

From here you can run queries, manage tables, and do all the SQL administrative tasks you need to. Note there is a SQL Azure Database node in the Template Explorer that you can access from the View menu. Of course if you are using SQL Azure you’ll want the SQL Azure SDK for Visual Studio 2010.

Connect to SQL Azure from Visual Studio

The same credentials and authentication happen in both tools, SSMS and Visual Studio. This means all that you need to do is open the SQL Server Object explorer and connect exactly as you would any SQL Server in your LAN. Once connected, you can enjoy administering and working with SQL Azure inside of Visual Studio.

SNAGHTMLcf0cc28_1

Troubleshooting SQL Azure Connectivity

The Firewall check failed error is very common, as you need to enter an IP Address range to connect to SQL Azure from various client programs (i.e., SSMS). Here’s the error text:

Firewall check failed. Cannot open server ‘SERVERNAME’ requested by the login. Client with IP address XXX.XXX.XXX.XXX is not allowed to access the server. To enable access, use the SQL Azure Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range. It may take up to five minutes for this change to take effect.

If you get this error you can reset it from the Windows Azure Mgmt Portal. Just navigate to the server you need access to, then add in the IP Range, as shown in the image below:

image_4

Alternatively, you can use SQLCMD in the Windows command prompt which will look something like this:

C:\>SQLCMD –U<user>@<server> -P<password> -S<server>.database.windows.net

exec sp_set_firewall_rule N’Allow Windows Azure’,’0.0.0.0′,’0.0.0.0′

SQLCMD Azure commands: http://msdn.microsoft.com/en-us/library/windowsazure/ee621783.aspx

NOTE: Only the server-level principal login (this is the primary/master login that you use to connect to the Windows Azure Portal online, a Windows Live Id), while connected to the master database, can configure firewall settings for your SQL Azure server. Also, check out the SQL Azure troubleshooting for other common errors, troubleshooting, and help.

Common JavaScript mistakes and pitfalls you can avoid

Having solid JavaScript skills is more important than ever in today’s web applications, and will continue to grow in importance as more browsers, IDEs, etc…, boast of HTML5 feature support. New HTML5 elements such as <canvas> , and features like Web Storage, Web Sockets, or Geolocation depend heavily on JavaScript. Despite tons of freely available, open source, or 3rd party libraries such as jQuery, Prototype, or Script.aculo.us, we still need to keep in mind that they’re just JavaScript layered on top of JavaScript – a level of abstraction. Knowing the under the hood workings and “gotchas” of JavaScript will certainly give you a boost with writing better code.

Developers that use strongly typed languages tend to treat JavaScript as a restricted rather than an expressive language, as they’re used to working with many compiler restrictions. On top of that, JavaScript’s reputation as a “toy, browser-only, language” precedes itself; many developers don’t bother to look deeply at some of its powerful features, as well as some language quirks that can really cause trouble.

The truth is out there: Dealing with truthy/falsy values

Dealing with comparisons and equality is usually straightforward, but JavaScript has a few caveats. Because of the way JavaScript deals with expressions, it has two sets of equality operators and some complicated rules around one of them (==/!==). The first set…

The “Equals” operator  ( = = )  and The “Does-not-equal” Operator ( ! = )

And the second set…

The “Strict Equals” operator ( = = = ) and The “Strict Does-not-equal” Operator ( ! = = )

If you’re wondering why JavaScript has two sets of equality(ish) operators, it’s because JavaScript works on the premise of truthy and falsy values.  The == / != operators will work as you might expect if the operands are of the same type (boolean), but if they are not, the == and != operators try to coerce the values, using a rather large and drawn out ritual to determine the result. Truthy/falsy values are a means for JavaScript to deal with non-Boolean expressions, by pretending as if they are Boolean anyway.

As a rule of thumb, JavaScript evaluates the values in the list below as false, and everything else as true:

  • false
  • null
  • empty string (“”)
  • 0
  • NaN

Since values like null, “”, and NaN, aren’t boolean values but are still treated as such, that makes them falsy. In short, when you compare expressions that aren’t actual boolean values, JavaScript can produce results that are inconsistent with what you might expect. For example, if you compare the value 0 to false, this is what you get:

(0 == false)  // true 
(0 === false) // false (correct)

When expressions accept anything, including NaN, undefined, etc…, there’s a lot of room for mistakes, even by experienced developers. Amplify that with the many rules involved to mentally juggle, and it too easy to see how == and != disrupt your thought processes while coding.

The take-away: the strict === and !== operators are the best way to go, but don’t shrug off the equals operator just yet, as you’ll likely run across them daily in the JavaScript world, making this valuable information for the maintenance coder.

What exactly is an isNaN(NaN); anyway?

NaN, or Not-A-Number, is a construct of JavaScript that’s useful only in very specific edge cases. Why then, is this important to know? Being a mischievous little code gremlin, NaN pops up everywhere. It’s a property of the Number object, (Number.NaN), and default value of NaN is NaN, yet it’s a falsy value. When trying use NaN in an expression, NaN returns a false every time. Since NaN is no help in determining what is actually non-numeric, you’ll need an alternative. Fortunately there is a very reliable isNaN() function you can use. Notice when the isNaN() function evaluates an alphanumeric string, the result is true, and a false for numeric values. To further investigate how isNaN() behaves, enter a few of the following statements in the Console tab of any browser’s dev tools and browse the results. (IE F12 dev tools featured below).

SNAGHTML6fc7755

isNaN() works as expected with numbers and alphanumerical data.

The conculsion: use isNaN().

Is eval() evil or just misunderstood?

eval()is the little function that wants to do everything for you, including dynamically creating and executing JavaScript.  Want to parse JSON? eval(). Want to clump a bunch of stuff together? eval(). Want to make up code to run on the fly? eval(). eval() finds ways to do something, anything, with what you give it, making it easy for developers to do both awesome and horrible things with it.

In an attempt to keep eval() innocent, many suggest limiting eval() usage to the following scenarios:

1) You need to allow script to run dynamically.

This opens up your page to potential security issues, so only use this when it’s necessary, as there are a few different ways to execute code dynamically in JavaScript (a quick Bing search shows many different techniques). That leaves…

2) Parsing JSON

You can use eval() for JSON parsing; however, you are still going to run into the same security issues. On top of that, the JSON.parse() method works much better as it’s meant just for JSON handling.

In general, stay away from eval() where you can, it has the potential to get evil quickly, and there’s usually a decent alternative.

Avoid function faux pas.

Functions live a first class life In JavaScript, so they’re not just functions, they’re objects too. It all depends very much on how you them. Take, for example, the following simple function to calculate two numbers:

var result = function (a, b) { return a + b;};

In many languages, the result passed back from the function will contain the sum of the values of the arguments, a, and b. In JavaScript; however, there is more to the story. Opening any browser’s developer tools and inspecting the code, shows the type as an “Object (Function)” and its value as the function itself.

SNAGHTML45e09f_1

You don’t need to, but you can, define and name functions. If you don’t provide a name when creating an inline function, it’s an anonymous function.

Having the knowledge that functions are objects allows you to better understand and work with Open Source or 3rd Party libraries, such as jQuery or Script.aculo.us. Consider jQuery’s chaining feature, that allows you to “tack on”, i.e., chain, other methods to the end of the previous method, in a single statement. Since the function is also an object, you can expect to call methods on it using dot notation, as the following simple jQuery chaining example demonstrates:

$("#inputBox").removeClass("normal").addClass("error");

In addition to function behavior, it’s necessary to know how to write good, clean, functions. Since JavaScript throws everything into a global namespace, you’ll want to encapsulate your functions into namespaces with classes and members (see below). And watch out for globals…

A variable of global proportions.

The authors of JavaScript intended it to be a language with a very low barrier for entry for the internet pioneers circa 1995. Because of this, they made the decision to allow, and even encourage, globally scoped variables. One or two global variables in a very small program can be useful, even manageable, and was certainly not a big issue at the time since HTML had only a few tags and the DOM a handful of nodes. However, JavaScript has grown into arguably the most popular language in the world, and has powered a spectrum of applications from the smallest to the largest. Anything other than the simplest of sites can contain nasty bugs because of the global space.

When possible, avoid global variables, and here’s why:

  • It’s too easy to have variable naming clashes in large applications.
  • It’s too easy to overwrite the wrong variable, or the right variable at the wrong time, when there are many variables accessible from anywhere.
  • Not needing to declare variables means there are often “floaters” hanging around in globally-scoped memory, but doing nothing.

A good workaround to this language gotcha is to create your own namespace and classes in it, and store any would-be global variables as properties of that object instead. Though they’re not real namespaces, they are objects that can behave like namespaces, making it easier for you to organize your code. The code below provides an outline of how you can create and access your own namespace:

var SampleNamespace = new function () { };
SampleNamespace.SampleGlobalObject = new function () {
 
    // Private function 
    var privateFunction = function ()
    { }
 
    // Public function
    this.publicFunction = function ()
    { }
}
// Calling the public function 
var publicFunctionTest = function () {
    SampleNamespace.SampleGlobalObject.publicFunction();
}

Global variables aren’t the only problematic variables in JavaScript. JavaScript doesn’t perform block scope, so variables you define can inadvertently become as error prone as global variables. The only scope smaller than the global scope is function scope. This means that you can access variables where you might expect otherwise, such as outside an if/else or for loop.

Although JavaScript is a dynamic, expressive, language, you need to organize it into namespaces, classes, and other units for a solid maintenance experience.

Summary

Watch out for some of the most common pitfalls that developers encounter, even while using Open Source libraries such as jQuery. There are, of course, many more language quirks and features that can also cause trouble, as with any language. If you want to go deeper into JavaScript, here are two highly recommended books.

JavaScript: The Good Parts by

JavaScript Patterns by Stoyan Stefanov

Use Windows Azure Mobile Services to power Windows Store and Windows Phone apps

New to the Azure family, Windows Azure Mobile Services is that all-in-one place for everything backend – data storage, authentication, push notifications, jobs. WAMs provides the tools to build and target cross platform apps for the Windows Store, Windows Phone, iOS, Android, and even plain old web sites.

Why Azure Mobile Services?

Here’s what you get upon creating your WAMS service:

  • Underlying SQL database, but you can also do NoSQL (BLOB storage, etc..)
  • A REST API, along with managed and JavaScript client libraries.
  • Administration via the Azure portal, command line, or SQL Management Studio
  • Server side logic via JavaScript or SQL
  • Push notifications

and…

A bunch of big-name authentication providers:

  • Microsoft acct (aka Windows Live)
  • Twitter
  • Facebook
  • Google acct

WAMS contains basically everything necessary to power an app or web site quickly. It doesn’t matter what you’re developing on the front end, it’s great to have a single point for all things backend.

Connect to Azure Mobile services

Once you have installed the Azure Mobile Services SDK for Visual Studio and setup and configured your mobile service at the Windows Azure Portal, you can download complete project templates or just blocks of the required code to connect and access WAMS on any platform. This is the same portal for all of Azure’s other services. 

Find your URL and key in the Azure portal by selecting the cloud icon next to the Dashboard option (see image below). This page allows you to choose your platform and download complete Visual Studio 2012 projects for Windows Store or Windows Phone in the language of your choice. There are also templates for iOS and Android available at the Azure portal. If you are integrating WAMS into an existing project there are code snippets for the MobileServicesClient (more on this below) you can copy and paste. The below image shows the key highlights:

 image_6

  1. Quick Start menu option.
  2. Choose your poison.
  3. Get the code.

The downloadable projects from the Azure portal contain the appropriate client lib references and code to connect to WAMS, depending on the language. For C#/VB you need a reference to the “Windows Azure Mobile Services Managed Client” extension. For JavaScript, reference the “Windows Azure Mobile Services Javascript Client” extension, as well as a script reference to MobileServices.js in the default.html file. Both dependencies ship with the Azure Mobile Services SDK.

In WAMS projects, you must create an instance of a MobileServiceClient that acts as a proxy to the Azure service, somewhat like a connection that manages itself.

C#

public static MobileServiceClient MobileService = new MobileServiceClient(
    "https://your-site.azure-mobile.net/", "your-key-here"
);

and Javascript

var client = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
    "https://your-site.azure-mobile.net/", "your-key-here"
);

Your site URL and key, both MobileServiceClient constructor arguments are available at the Quick Start page (above image) in the Azure portal. Now that you have a proxy to a mobile service, you can perform all CRUD operations as well as some DDL code locally on the client by populating a IMobileServiceTable<T> with a call to MobileService.GetTable.  Once you do that you can then perform data binding and other CRUD operations.

Work with data in Windows Azure Mobile Services

In C#  you must use a class to represent the data item, while in JavaScript you do not. For example, the below code shows populating & data binding to TextBox inside a XAML ListView control.

<ListView Name="ListItems" Margin="62,10,0,0" Grid.Row="1">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBox Name="NameTextBox" Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

The C# code, below.

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
}

private IMobileServiceTable<Person> peopleTable = App.MobileService.GetTable<Person>();
private void RefreshTodoItems()
{
    var results = await peopleTable.ToListAsync();
    persons = new ObservableCollection<Person>(results);
    ListItems.ItemsSource = persons;
}

Additions and updates (but not deletions) to properties of the Person class in client code affect the underlying SQL database. This means that if you add another property to the Person class, such as a FavoriteColor property, the WAMS libraries will automatically infer the type and create the underlying SQL entities. Of course not everything can be done in client code so there are server side alternatives (see below, under Manage WAMS Data Stores)

Below is the equivalent code in Javascript, starting with HTML for data binding.

<div id="TemplateItem" data-win-control="WinJS.Binding.Template">
    <div style="display: -ms-grid; -ms-grid-columns: auto 1fr">
        <input class="itemCheckbox" type="checkbox" data-win-bind="checked: complete; dataContext: this" />
        <input type="text" data-win-bind="text: Name" />
    </div>
</div>
<div id="listControl" style="-ms-grid-row: 2; margin: 20px 0px 0px 0px; -ms-grid-row-align: stretch"
    data-win-control="WinJS.UI.ListView"
    data-win-options="{ itemTemplate: TemplateItem, layout: {type: WinJS.UI.ListLayout} }">
</div>
var peopleTable = client.getTable('People');
var peopleList = new WinJS.Binding.List();
var refreshData = function () {
    peopleTable.read()
        .done(function (results) {
            peopleList = new WinJS.Binding.List(results);
            listControl.winControl.itemDataSource = peopleList.dataSource;
        });
};

As you can see, you do not need to setup a class since Javascript is not strongly typed but WAMS will still create objects and SQL mappings as needed. However, you can use something like TypeScript to create classes to be more like classes in C#. Either way, once you have a reference to the MobileServiceTable, all required functionality is accessible through that object. For example, insertions are just a simple call from the MobileServiceTable object:

C#

private async void InsertTodoItem(Person person)
{
    await peopleTable.InsertAsync(person);
}

Javascript

var insertPerson = function (person) {
    peopleTable.insert(person).done(function (item) {
        peopleList.push(person);  // push items onto List object for binding
    });
};

The other CRUD methods are just as easy and also belong to the MobileServiceTable object. Notice that C# uses the await/async keywords and JS uses the done function to implement asynchronous operations (async is 1st class citizenry in Windows Store & Phone apps).

While the Javascript code will not run on Windows Phone, the C# code does and is easily ported between Windows Store and Windows Phone. You can download templates at the Azure portal specifically for Windows Phone (iOS and Android too).

Of course you need to also manage the data on the backend, regardless of the type or number of front end clients.

Manage WAMS data stores

While there are benefits to automatic creation, mapping, and type inference between client objects and WAMS databases, you can perform any sufficiently advanced db management using Javascript on the server such asvalidation, constraints, etc…. Here’s an example of server side validation in WAMS:

function insert(item, user, request) {
    if (item.text.length > 10) {
        request.respond(statusCodes.BAD_REQUEST, 'Text length must be under 10');
    } else {
        request.execute();
    }
}

This is straight-up Javascript. You can run it at the portal or upload the .js files directly to WAMS by using the WAMS command line tools:

azure mobile script upload <service-name> table/<table-name>.<operation>.js

azure mobile script upload NotablePeople people/people.insert.js

This makes it easy to incorporate scripts into source control, and using Javascript on the backend makes it easy to develop cross platform solutions.  

Summary

WAMS is a backend to everything, and is for the most part a turn-key operation, and using WAMS is really as simple as setting up the WAMS service, referencing the proper Visual Studio client libs, and coding against a small and clear set of APIs. Despite all this goodness, WAMS is still a young technology so it does need some polish. I’d like to see server side JS debugging and more SQLesque type utilities, as well as additional data types like binary/BLOB support (which I am told is coming soon, yay!).

When to use ViewBag, ViewData, or TempData in ASP.NET MVC 3 applications

“When should I use a ViewBag vs. ViewData vs. TempData objects?” — a frequent question in online forums, during presentations, and at events. There are enough similarities and differences between these objects that warrant a closer look to see exactly how you can use each of these objects while developing MVC applications.

All three objects are available as properties of both the view and controller. As a rule of thumb, you’ll use the ViewData, ViewBag, and TempData objects for the purposes of transporting small amounts of data from and to specific locations (e.g., controller to view or between views). Both the ViewData and ViewBag objects work well in the following scenarios:

  • Incorporating dropdown lists of lookup data into an entity
  • Components like a shopping cart
  • Widgets like a user profile widget
  • Small amounts of aggregate data

While the TempData object works well in one basic scenario:

  • Passing data between the current and next HTTP requests

If you need to work with larger amounts of data, reporting data, create dashboards, or work with multiple disparate sources of data, you can use the more heavy duty ViewModel object. See my detailed blog post on ViewModels for more details on working with ViewModels.

ViewData & ViewBag objects

  • ViewData
    • ViewData is a dictionary object that you put data into, which then becomes available to the view. ViewData is a derivative of the ViewDataDictionary class, so you can access by the familiar “key/value” syntax.
  • ViewBag
    • The ViewBag object is a wrapper around the ViewData object that allows you to create dynamic properties for the ViewBag.

Both the ViewData and ViewBag objects are great for accessing extra data (i.e., outside the data model), between the controller and view. Since views already expect a specific object as their model, this type of data access to extra data, MVC implements it as a property of both views and controllers, making usage and access to these objects easy. 

The syntax and usage of the ViewBag, ViewData, and TempData objects are outlined in the following code sample, which populates a featured product object that a view renders as in a bakery’s home page:

public class HomeController : Controller

{

    // ViewBag & ViewData sample

    public ActionResult Index()

    {

        var featuredProduct = new Product

        {

            Name = "Special Cupcake Assortment!",

            Description = "Delectable vanilla and chocolate cupcakes",

            CreationDate = DateTime.Today,

            ExpirationDate = DateTime.Today.AddDays(7),

            ImageName = "cupcakes.jpg",

            Price = 5.99M,

            QtyOnHand = 12

        };

    

        ViewData["FeaturedProduct"] = featuredProduct;

        ViewBag.Product = featuredProduct;

        TempData["FeaturedProduct"] = featuredProduct;  

    

        return View();

    }

}

The Index.cshtml view renders the Product object by accessing the code with the same syntax as in the controller. Notice that you’ll have to cast the ViewData and TempData objects, but not the ViewBag.

@using FourthCoffee.Models;

@{    

    ViewBag.Title = "Home Page";

    var viewDataProduct = ViewData["FeaturedProduct"] as Product;

    var tempDataProduct = TempData["FeaturedProduct"] as Product;                

}

<h2>Welcome to Fourth Coffee Bakery</h2>

<div>

    <a href="/Products">

    <img src='@Url.Content("\\Content\\Images\\cake.jpg")' alt="Fourth Coffee Bakery"/>    

    </a>

    <div>

        Today's Featured Product is!

        <br />

        <h
4>@ViewBag.FeaturedProduct.Name</h4>

        <h3>@viewDataProduct.Name</h3>

        <h2>@tempDataProduct.Name</h2>

    </div>

    @Html.ActionLink("Test Tempdata","Featured")

</div>

The ViewBag object lets you add dynamic properties to it which makes it a very versatile tool.

Although all three display something when this view renders, but the TempData can be troublesome when used in this manner, and here’s why…

TempData

TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only! Since TempData works this way, you need to know for sure what the next request will be, and redirecting to another view is the only time you can guarantee this. Therefore, the only scenario where using TempData will reliably work is when you are redirecting. This is because a redirect kills the current request (and sends HTTP status code 302 Object Moved to the client), then creates a new request on the server to serve the redirected view. Looking back at the previous HomeController code sample means that the TempData object could yield results differently than expected because the next request origin can’t be guaranteed. For example, the next request can originate from a completely different machine and browser instance.

As described below, the syntax for using TempData is the same as ViewData.

// TempData sample

public ActionResult Featured()

{

    var featuredProduct = new Product

    {

        Name = "Assorted Cupcakes",

        Description = "Delectable vanilla and chocolate cupcakes",

        CreationDate = DateTime.Today,

        ExpirationDate = DateTime.Today.AddDays(7),

        ImageName = "cupcakes.jpg",

        Price = 5.99M,

        QtyOnHand = 12

    };

 

    ViewData["FeaturedProduct"] = featuredProduct;

    ViewBag.Product = featuredProduct;

    TempData["FeaturedProduct"] = featuredProduct;

 

    //After the redirect, the ViewBag & ViewData objects are no longer available

    //Only TempData survives a redirect

 

    return new RedirectResult(@"~\Featured\");

}

However, once the controller redirects, the ViewBag and ViewData will contain null values. If you inspect the TempData object with debugging tools after the redirect you’ll see that it is fully populated with a featured product. This is because the redirect is that only, subsequent, request, so only it can access the TempData object without worry.

@using FourthCoffee.Models;

@model FourthCoffee.Models.Product

@{

    ViewBag.Title = "Details";

    var featuredProduct = TempData["FeaturedProduct"] as Product;

}

The customary Session object is the backing store for the TempData object, and it is destroyed more quickly than a regular session, i.e., immediately after the subsequent request. Because of its short lived scope, it’s great for passing error messages to an error page.

Greg shackles has a very comprehensive blog post that covers just about everything you need to know about TempData.

Now that you’ve seen how and when to use ViewData, ViewBag, and TempData objects, you might be wondering what to do when using larger sets of data or more complex scenarios. Fortunately, MVC has ways to deal with these commonly needed scenarios.

Thinking outside the ViewBag

Your requirements might need you to represent the following types of data, which do not fit in well when using ViewBag, ViewData, or TempData objects. The MVC 3 framework contains ViewModel objects for when you need more than ViewData. The type of data that suits ViewModels well is as follows:

  • Master-detail data
  • Larger sets of data
  • Complex relational data
  • Reporting and aggregate data
  • Dashboards
  • Data from disparate sources

You’ll likely run into these or similar scenarios during the app development process.

Summary

The ViewData and ViewBag objects give you ways to access those extra pieces of data that go alongside your model, however for more complex data, you can move up to the ViewModel. TempData, on the other hand, is geared specifically for working with data on HTTP redirects, so remember to be cautious when using TempData.

Introducing MVC Development w/the Razor View Engine for Visual Studio Developers

The Razor View Engine is a precise, useful, light language that enables you to create views for MVC projects in ASP.NET still while keeping a separation of concerns, ability to test, and pattern based development.  ASP.NET MVC developers looking for a more concise syntax now have another option that’s built-in (of course, there are many 3rd party view engines out there) with the language being a familiar light version of C#.

The Razor View engine is used to create WebMatrix sites or Visual Studio MVC applications.  When using ASP.NET MVC with either engine, you’ll stick to a style of development called “convention over configuration”, meaning that you’ll use certain naming conventions to name files, models, views, controllers, and other key application elements rather than storing lots of metadata about these same elements in a configuration file.  When using MVC in Visual Studio 2010, it’s is setup so that you’ll be guided to use convention over configuration, which becomes evident when exploring an ASP.NET MVC project.

Getting Started

Before you start, go and download these two things (as of this post; things are subject to change – these could end up in VS at some point):

You can also find the Razor Syntax Highlighter by choosing Extensions Manager from the Visual Studio Tools menu.  Once installed, MVC 3 project templates are available from Visual Studio.  The MVC 3 Web Application template allows you to use either the Web Forms View Engine or the Razor View Engine, while MVC 2 Applications contain only the WF View Engine.

image_2

When creating a new MVC 3 project a new dialog box appears asking which application type, view engine, and testing framework you’d like to use.  You can and should add a test project so you can test your code, then actually write some tests in it.   The image below demonstrates selecting the internet application project template using Razor as the view engine, as well as the test framework.  The internet application MVC template adds in ASP.NET membership & security features to the project by creating the necessary model, view and controller for logging on and registering as a site user.

image_6

Verify that the project is created with three folders, one each for Models, Views, and Controllers which is the same folder structure as a MVC 2 site.  The project also contains auxiliary folders and files needed for the application such as the Content & App_Data folders.   Since this is an MVC application using the Razor View Engine, you will see a different file extension – .cshtml.  The .cshtml files are Razor View Pages written using the Razor View Engine.  If you’re not familiar with Razor syntax, I’ve blogged about it here, and the online documentation has more information as well.

image_11

The application template sets up some models, views and controllers to start with, and is now ready for new models, views, and controllers.  I’ve found the easiest way to work with MVC in VS is to start with the model, move to the controller, then create the view, so we’ll look at models first.

Models

A model is a representation of an underlying data store.  Models can be almost anything from any data source; EF or Linq2Sql Models, or a simple class.  The code the builds the model below consists of two classes, a ProductModel class and a Product class.  The ProductModel class returns a List<t> of Product objects in a property aptly named Products that represents one or more products in the data store .  Product objects contain ProductNumber, Name and Price properties and represent an individual product in the data store.  The model code representing these product objects is below:

using System.Collections.Generic;
namespace AdventureWorks.Models
{
    public class ProductModel
    {
        public List<Product> Products { get; set; }
        public ProductModel()
        {
            Products = new List<Product>();
            this.Products.Add(new Product("AB-00-J1" ,"Super Fast Bike" ,1000M));
            this.Products.Add(new Product("EE-9-OL"  ,"Durable Helmet"  ,123.45M));
            this.Products.Add(new  Product("MMM99-54" ,"Soft Bike Seat"  ,34.99M));
        }
    }

    public class Product
    {
        public Product(string productNumber, string name, decimal price)
        {
            Name = name;
            Price = price;       
            ProductNumber=productNumber;
        }
        public string ProductNumber { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
       
    }
}

Models are handed over to views by controllers so the views can render the data from the model.  The model will extend business logic (of course, this is a simple example, business logic will likely be spread out into other applications & tiers). Models also provide validation information to the view via metadata & code.  You can add the model to the \Models folder or you can reference an external data model library.  In this case, the model’s been added to the \Models folder.

Controllers

Controllers are objects that inherit from the System.Web.Mvc.Controller class that match models with views.  During incoming requests, MVC’s routing system kicks in and determines which controller method to use based on routing code set in the global.asax.cs file.  A default route is set in the global.asax.cs file that works for most of the routes you’ll need, however, if need be then you can modify/add/delete your own routes.

Staying within convention, controller code files should go in the \Controllers folder. The controller class must follow the naming convention of YourNameController, i.e., ProductsController.  The controller’s Index method, again following convention, must be named the same name as its view but without the file extension.  By following this pattern, the controller can have multiple actions that deliver data to multiple views, making code easier to write, maintain, and test.

namespace AdventureWorks.Controllers
{
    public class ProductsController : Controller
    {
        public ActionResult Index()
        {
            ProductModel p = new ProductModel();           
            return View(p.Products);
        }
    }
}

By observing the previous code sample and the conventions that it follows, it’s clear that the Index method maps to the \Views\Products\Index.cshtml view.  The Index() method’s return type is an ActionResult from the System.Web.Mvc namespace.  There’s many different results that you can use for different scenarios such as ContentResult, FileResult, RedirectResult, ViewResult and others depending on your view’s needs

Views

Views are a mechanism to format and render data in a browser from the model, as specified by the @model attribute (or @inherits) at the top of the view.  Views in ASP.NET MVC with either the ASPX or Razor View engines use a code-based way to render the page rather than relying on declarative controls, which create tight coupling and are hard to test.  Using the MVC approach creates cleaner output in the browser as well as cleaner and more terse syntax in the views as well.  Views are meant to only render the markup, code and data; they’re not meant as a place to store business logic. The model and tiers accessed by the model, are the appropriate places to host business logic.  The view can have a small amount of UI validation logic,as a first line of defense for input sanitation, e.g., required, regex and range validators.

To add a view to your project, right click on the controller and select Add View.

image_4

Visual Studio will need some information about the view, which is supplied in the Add View dialog box:

  1. Specify whether you want a strongly-typed view or not.  Creating a strongly-typed view allows you to refer to the underlying data structures in the classic object.property syntax.
  2. Specify the view data class.  The dropdown list displays classes in your project that are part of the data model.
  3. Specify the view engine.  ASPX and Razor are the options.
  4. Specify the view content.  Choices are list, details, edit. etc…  Choosing this option creates .cshtml or .aspx view pages that do page rendering for you.

image_12

Here’s what choosing these options will produce in a Razor view page named \Views\Products\Index.cshtml:

@model List<AdventureWorks.Models.Product>
@{

View.Title = "Index";
Layout =
"~/Views/Shared/_Layout.cshtml"
;
}


<h2>Index</h2>
<
p>
@Html.ActionLink("Create New", "Create")
</p
>
<
table>
<tr>
<th>Edit/Details/Del</th>
<th>Product Number</th>
<th>Name</th>
<th>Price</th>
</tr>

@foreach (var item in
Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
<td>
@item.ProductNumber
</td>
<td>
@item.Name
</td>
<td>
@String.Format("{0:F}", item.Price)
</td>
</tr>
}
</table>

Since the view is strongly typed, the data structure can be accessed as it is – an object with properties.  The code above loops through the model and renders a <TR> for each entity that the model holds along with <TD> tags and the actual data in them (ProductNumber, name and Price).  The result is a simple list of the three products in model with accompanying action links.

image_14

The HTML source shows a clean, precise table rendered to the browser.

image_8

Summary

Rendering a list of products is very easy using MVC and the Razor View Engine, as is updating/manipulating the data (logically what you’d do next if following this example).   If you’re digging deeper into learning MVC w/Razor the next topics you’ll want to get into are jQuery and HTML validation helpers for client side validation, and decorating the model with data annotations (also for validation).  The MVC web site has a ton of great examples and tutorials.

Although many ASP.NET MVC samples use the ASPX/Web Forms view engine they’re easily compared & converted to razor pages – so don’t avoid them, it’s still a great way to learn both MVC w/Razor and the ASPX engine.

Getting Familiar with Razor Language Syntax, Features and Rules

All languages have syntax rules, and ASP.NET Web Pages with Razor is no different.  The syntax is meant to be light and concise and simple, yet powerful enough to allow you to move to ASP.NET development using Visual Studio easily . Having said that, let’s take a look at a few key features of the language and some of the simple ways to write Razor code.

What exactly IS Razor and WebMatrix?

If you need the introduction on WebMatrix & Razor, no worries, I’ve already written a post on why, who and when WebMatrix & Razor are good choices and what they are intended for here.  Otherwise, continue on…

Basic Principles (Code/Script Blocks)

The @ character designates inline code, which is code that’s right inside of HTML  while the @{ with and ending } designates multiple lines of code.  Inline code can be anywhere – mixed inline with HTML, as HTML attribute values or page content. It can be multiple lines of code (a code block) as well when more functionality is needed.  Here’s a single inline statement sample with the actual code highlighted:

<li class=”price”>$@string.Format(“{0:f}”, p.Price)</li>

And here’s a what a block of code looks like:

@{

    LayoutPage = “~/_Layout.cshtml”;

    PageData[“Title”] = “Home”;

}

 

Each executable statement ends with a semicolon (;).Whitespace is ignored, but case is not.

Literal strings (or literal text) are put in double quotations (“), while numbers, if used mathematically, use none.

Comments

A Razor single line comment marker: @//

A Razor multi-line comment marker: @/* and */

Variables & Data Types

Use the var keyword to declare variables, or use the classic typed syntax.  The new operator is also supported.

var db = Database.Open(“bakery”);

string name = “Stephen”

int rating = 5;

var grid = new WebGrid(data, defaultSort: “Na
me”, rowsPerPage: 5);

Razor supports all the standard .NET framework simple data types and allows developers to take advantage of consuming objects and collections, using the classic dot notation, as shown below:

Mail.SmtpServer = “smtp.live.com”;

Mail.SmtpPort = 25;

Mail.EnableSsl = true;

Mail.Send(to: customerEmail, subject: “New Order”, body: body);

Paths

Use the ~ operator to get to the virtual root of the web site.  The virtual root is top level folder of your site, installed to here by default:

C:\Users\<YourUserName>\Documents\My Web Sites\Bakery

Where <YourUserName> is your Windows login name.  The Server.MapPath() method is also available, to help you when you need to convert physical paths to virtual paths for use on a web server.

Code constructs

Razor supports conditions and loops, so you can make decisions in your code.  You can use if blocks & switch blocks, for & foreach loops and while loops too.  Despite being a language that uses curly brace and is case sensitive, it’s very easy to read and write from a syntactic angle, as demonstrated here with a foreach loop, if statement and using the Mail object:

@foreach (var p in db.Query(“SELECT * FROM PRODUCTS”)) { … }

–and–

if (Mail.UserName.IsEmpty() || Mail.Password.IsEmpty() || Mail.From.IsEmpty()) {

        <h2>Please set up Mail!</h2><p>Please set your Hotmail Username, Password, and From Address in OrderSuccess.cshtml to send mail</p>

}

else {

    Mail.Send(to: customerEmail, subject: “New Order”, body: body);

    <h2>Thank you for ordering!</h2>

} 

Some other notable code constructs available in Razor are Try/Catch exception handling and arrays.  I just wanted to highlight a few of the popular ones here in this blog post. You can get a lot more information on the language features in the ASP.NET Web Pages with Razor Syntax eBook.

Helpers

Razor helpers allow you to encapsulate and condense complex tasks into a single line of code.  Some baked in helpers are used for …

  • Google Analytics
  • Facebook Integration
  • Twitter Integration
  • Sending Email
  • Validation
  • There’s lots more…

You can also create your own helpers, and there’ll be more helpers brought to you by Microsoft in the future.  Helpers are a big part of the Razor API.

The Razor API

This is where’s it at, in the API.  APIs (Application Programming Interfaces) contain functionality that you can tap into and use, rather than having to build it yourself.  The Razor API includes an extensive of helpers and activities like file uploading, data collection w/HTML Forms, charting, sending email, website analytics, etc…are all in the Razor API, and most only take a single or few lines of code to use.

You can browse the online API documentation here.

There’s More!

Of course, there’s a lot more you can do with Razor syntax; listed in this post are just some of the basics and features that you can take advantage of when building small, highly functional, easy to use web sites.

Stats, data, and answers, as to why there are so few women in technology fields.

Women today represent an abysmal percentage of the population of most STEM fields (Science, Technology, Engineering, and Math), and that number is shrinking, rather than expanding. At the same time, fewer young women are entering the STEM workforce than in previous years.

Why are women leaving STEM fields?

Researchers have been gathering volumes of data as to the why there are fewer women are staying in, or entering STEM fields, and from that data we can see many issues that cover a spectrum from that need to be addressed:

  • Sexism: overt and subtle (hostile macho cultures)
  • Harassment, threats, or potential or actual violence toward women
  • Childcare
  • Financial Independence
  • Gender Stereotyping
  • Work-life balance

Considering the number of challenges, addressing the lack of women in technology is a multifaceted phenomenon with no single solution, with each matter deserving attention. The primary goals of this post will focus on demonstrating…

  1. Incidents of sexism at industry events, and online conversations, and their link to the decline of women in STEM fields.
  2. The effects sexism has on women and the STEM industries as a whole, both now and in the future.
  3. A call to action to drive awareness and take a proactive stance in promoting women friendly STEM workplaces, conferences, schools, and meeting places.

By understanding these influences women in technology, particularly in software development, we can take corrective and proactive stances, in the retention, engagement, and attraction of top female talent.

Incidents of sexism are major contributors to a declining female STEM workforce.

The National Center for Women In Technology describes sexist incidents [.pdf] in various ways including,

“experienced/observed exclusionary cliques, unwanted sexual teasing, being bullied, and homophobic jokes”.

Consider that  between January and October 2011, women reported 20 sexist incidents to the Geek Feminism Wiki, with some common themes: 

  • Several talks at tech conferences contained pornographic style imagery, or sexual imagery.
  • Multiple presentations referenced women in a derogatory or demeaning way, (e.g., “women can’t program”, “women are stupid”) or by overt or subtle objectification of women.
  • Overt harassment, inappropriate touching, and groping are still commonplace at technical conferences.

Roughly one incident every two weeks this year means that this happens more than we’d like to think – and that’s only the reports from a single website.

Exclusionary, offensive, incidents at conferences, along with threats, violence, and harassment, against women in technology (and women in general) are simply not isolated occasions. They have profound implications that directly impact the declining numbers of women in technology. The Washington Post outlines some statistics demonstrating this, in a study on interactions between men and women during online chat sessions.

“A 2006 University of Maryland study on chat rooms found that female participants received 25 times as many sexually explicit and malicious messages as males. A 2005 study by the Pew Internet & American Life Project found that the proportion of Internet users who took part in chats and discussion groups plunged from 28 percent in 2000 to 17 percent in 2005, entirely because of the exodus of women.” [emphasis mine]

Those numbers have barely improved, five years later. Additionally, the participants in this study belong to a general online audience and not solely the STEM fields, so one must consider the fact that STEM fields are male dominated, resulting in a larger amount of sexist behavior.

Though not the only reason, the numbers show that in software development specifically, sexist and overtly offensive behavior (both online and off) is one of two key factors as to why women are leaving technical fields as reported by ABC News. This article quotes Laura Sherbin, director at the Center for Work-Life Policy, who published a study in the Harvard Business Review titled “Reversing the Brain Drain in Science, Engineering, and Technology”. Laura goes on to explain the primary reasons women leave STEM fields…

“The top two reasons why women leave are the hostile macho cultures — the hard hat culture of engineering, the geek culture of technology or the lab culture of science … and extreme work pressures”

Sherbin also highlights just how critical and surprising the numbers are, even to researchers.

“The dropping out was a surprise to us. We knew anecdotally that women were leaving these careers. We didn’t expect to see the number 52 percent.”

To reiterate: 52% or just over half, of the female STEM workforce leaves because of hostile macho cultures.

Let’s do the math:

  • Assume the average tech conference has 300 attendees.
  • The average turnout of females at a technical conference is at about 15%, or 45 women in this example.
  • 52%, or 23 of the women at that event will leave the industry[1].
  • At a rate approximately of 26 events per year affecting 23 women each time, 598 women will be subjected to a hostile environment each year[1].

The cost in human terms and individual well-being is immeasurable.

A look at the negative effects and human cost of sexist behavior in STEM fields.

Considering the above numbers, try out this thought exercise, showing the implications of sexist incidents on women in software.

  1. Think of the names 23 women developers that you work alongside, have worked with, or know. Try it without looking at social networks, checking address books, etc…
  2. Think about these women. Are they your coworkers? Presenters you admire? Are they women with whom you enjoy having technical conversations, perhaps at conferences, code camps, or over social networks?
  3. There’s essentially a 50/50 chance, or the same chance as the toss of a coin, that those 23 women won’t be developers for much longer.

Once they’re gone, can you name 23 more women to replace them? It won’t be the younger girls entering the field.

The consequences have a stifling effect on younger girls wanting to enter the technology fields before they have a chance to start. Numbers show that a huge impasse in attracting young girls into the STEM fields, is a serious lack of women role models in those fields. Less women staying in the field means fewer role models for young girls, which in turn means fewer STEM girls overall.

It’s not just about sexist incidents though, subtle sexism can bleed into the everyday atmosphere of in tech fields and cause the same amount of negative barriers. While the day to day activ
ities of most technical women might not vary much from that of men, as far as actual programming, sitting in meetings, mundane business tasks, etc… What do differ are the interactions between the sexes, as well as both overt and subconscious behavior that manifests as sexist incidents, though primarily non-malicious, and most often subconscious. For example, here are some commonplace scenarios where subtle sexism happens in companies large and small[2][3]:

  • Men who repeatedly ask only the women attending meeting to take notes, or get coffee, when the woman is not a secretary or in a similar role.
  • Colleagues that routinely ignore women during meetings, or a female states an idea that is promptly ignored, then raised again by a man who gets the credit. (in a consistent, frequent, pattern)
  • Women, rather than men, are routinely stuck into “softer” positions, often to answer phones. Management gives women more remedial tasks that are clearly not aligned with their job description or what they were hired to do.

The sentiments above are detailed in a report by Level Playing Field Institute titled “The Tilted Playing Field: Hidden bias in information technology workspaces”  [.pdf]. Reading about recent events and stories of everything from demeaning comments, to outright harassment, stalking, and groping, are still commonplace in the tech industry. I must agree that I’ve personally been privy to a number of these types of scenarios, but that’s not all…

When an incident at a conference happens, I inevitably get a call or email from a female colleague who has just given up, and is now looking at non-technical career alternatives.

If we are to keep our technical industries healthy, and full of diverse creativity, things must change, and soon. So what can you do?

A Call to Action: Drive awareness and take the lead to promote diversity in STEM fields.

Below are just some of the things you can do to drive diversity and promote women in STEM fields:

Drive awareness.

It may seem obvious, but without awareness, it’s impossible to know there’s a problem.

You can drive awareness by blogging, tweeting, or otherwise telling your story, or commenting on blogs to show your support. The Level Playing field’s report shows a real lack of awareness in populations at large. The more blog posts, articles, and events, mean more information people can use to take proactive stances to create technical communities and workspaces that are welcoming to everyone.

Be proactive.

  • Does your company have a diversity and inclusion policy? Even if you work for a small business or startup, a formal policy of inclusion fosters a welcoming environment for everyone. If you company doesn’t have one, get involved and ask your HR department to work on one with you. Don’t let your policy be a paper form of lip service, make it part of how you do business.
  • Does your HR department have a clear open door policy, with a trusted employee to listen to concerns?
  • Attend women in technology events. Hint: Take your favorite gal developer with you. At the Code Camp NYC 2011 WIT luncheon, a healthy mix of men and women joined in for a productive, round-table discussion.
  • Ask technical women work on a joint talk with you for a user group or code camp, and invite them to technical events.

Awesome guys like John Zablocki and coworkers like Joe Healy, Peter Laudati, and Brian Prince, are just a few of the many guys I see at WIT related events.

Presenters & conference organizers:

Speakers can use the Windows Phone 7 app content guidelines, or the Android app marketplace rating guide when s/he’s not sure what material should be considered offensive.

Organizers can create written guidelines to ensure a harassment-free environment for everyone at your conference, user group, or other meeting.

CodeStock 2010 set a perfect example to follow by embracing a WIT centered theme, including a female keynote speaker (*ahem* that would be me 🙂 ).

Summary

I would love to see every company behave as MS DPE East does, and I hope that you, dear readers of this blog, will step up to foster an environment in your workplaces and homes that support and celebrate women and diversity in STEM fields.

Should an incident occur at an event you’re attending, take corrective action as soon as possible. If you’re in a conference session and you feel offended or uncomfortable, walk out calmly, and write down exactly what you feel is offensive or inappropriate. Take the evaluation to the conference staff, and ask that they check out the session in question.

[1] The numbers in this sample represent one source of reports, so the actual numbers are much higher. Additionally, the number 23 is rounded from 23.4. Also assuming a single track conference, which is fairly common.

[2] These aren’t just manufactured scenarios – they’re real life stories from female contemporaries.

[3] As for large companies, my experiences at Microsoft DPE have been great!. I work on an highly functioning team with awesome people who celebrate diversity in technology and are quite supportive of each other.