JavaScript Strict Mode Explained

JavaScript is everywhere. It’s run in web sites, as utilities on many operating systems, and in any host, like IE, Firefox, or Chrome and it’s a first class citizen in Windows 8 Metro style app development. Since JavaScript has been around for a long time, it still has a lot of baggage from when it was immature. Because of this, Strict Mode has become a feature in ECMAScript 5, or ES5 (JavaScript).

What is Strict Mode and why use it?

Because Strict Mode is ECMAScript, it is a standard, and a best practice, and highly recommended that you use it. In the future, Strict Mode will be your only choice, which is certainly for the best. Strict Mode offers up these enhancements to the JavaScript language:

  • JavaScript throws errors if you try to use deprecated language elements
  • Variable declaration is mandatory
  • Disallows duplicate property and parameter names
  • The eval() method is safer to use, but still considered evil in some cases.
  • Deprecates the with statement
  • JavaScript throws errors if you try to assign a value to a read only property
  • Decreases the global namespace pollution

Most ES5 compliant JavaScript runtimes support Strict Mode, and you can get full details at this in-depth article on Strict Mode at MSDN.

Where can I use Strict Mode?

You can use strict mode in any JavaScript host or engine that supports ES5 standards, and specifically, Strict Mode. Check out this comprehensive ES5 Compat Table on Github to see if your browser supports strict. You will see a lot of green lights, so there is wide support across browsers. This means if you are a web developer you can start using Strict Mode today.

If you are a Windows 8 Metro style apps HTML/JS developer, Strict Mode is automatically added to the project templates in Visual Studio 11 as WinJS supports Strict Mode.

Enabling Strict Mode

Applying Strict Mode is very easy to do. Just add the “use strict” directive to your code (it’s a string literal so include the quotes). The physical location of the strict directive determines the scope of Strict Mode. Below is a table showing the relationship between Strict Mode and scope. This means you can turn Strict Mode on and off granularly in code.

Code location Scope
Beginning of any .js file Global
Beginning of the script inside a <script> element. <script> element
Preceding function block
First line in function block
Function

As you can see, Strict Mode is flexible but try to keep Strict Mode out of a global setting where possible when dealing with Web pages (HTML, ASP.NET, PHP, etc…). If other scripts include your script using Strict Mode, then Strict Mode could apply to the included scripts and that can create problems. However, you can get the same effect as global Strict mode by wrapping your code like so:

$(function () {
    “use strict”;
    function strictFoo() {
        alert(“I am in strict mode”);
    }
    function strictFoo2() {
        alert(“Me too!”);
    }
});

This creates a block around both functions and Strict Mode appears global to to the all code that exists in that block, essentially making strict container for that code. 

Summary

Strict Mode is great because it catches common programming ID10T errors. These are the kind of errors everyone makes, regardless of experience, and often because of experience. It’s very easy, especially when moving from a compiled language, to miss some of the finer nuances of JavaScript. Strict Mode helps smooth out those JS language kinks.

Create mobile site layouts with CSS Media Queries

Web sites and apps need to deal with the challenge of serving content to a multitude of browsers and devices. People access web sites and apps via tablets and mobile phones more than ever before, and smart phone usage numbers are growing exponentially. In some populations, mobile Web traffic is higher than traffic from desktops. Technology nowadays means devices and machines range in size from quite small to quite big, and as a result, you the developer must format the content appropriately for each device type. You can accomplish this task by using CSS Media Queries, as they are the best foundation of a responsive UI.

What is a CSS Media Query?

In the past, in order to serve browser or device specific content, we would write code that determines which style sheet to use based on feature detection (or UA detection on older Web sites). Now, instead of having to write code, we can use declarative CSS Media Queries to apply rules to an HTML page based on the requesting device’s characteristics. CSS Media Queries are a way to apply different styles when the requesting browser or device matches the conditions within the media query. With media queries you can target various screen sizes, orientations, and form factors including TV and print, and serve tailored content to them. For example, the media queries below apply a different layout to the tablet sized, landscape screen (768 x 1366 ), vs. the phone sized, portrait screen (320 x 480):

@media screen and (min-width: 768px) and (orientation: landscape)

{
    /* CSS layout for screens with minimum 800px width, landscape */

} @media screen and (max-width: 320px) and (orientation: portrait)

{
    /* CSS layout for screens with maximum 320px width, portrait */
}

While multiple media queries can exist side by side in a single .css file (like the example above), maintenance can be easier if you create one .css file for each type of device you want to support. Doing so allows you to swap style sheets based on the media query defined in the media attribute of the <link> tag.

<link rel=”stylesheet” type=”text/css” href=”smartphones.css” media=”only screen and (max-device-width: 320px)” /> <link rel=”stylesheet” type=”text/css” href=”tablets.css” media

="screen and (min-device-width: 800px)" />

Effectively, media queries rid you of the long lines of “if then” statements otherwise required as conditional logic to figure which style sheet to use for which occasion. You no longer need to resort to using JavaScript to swap style sheets by querying user agents, media types or common device form factors.

Design a page layout with CSS Media Queries

Layouts that fit traditional landscape screens work horribly on smart phones, and thus the need for a responsive layout. A responsive layout is fluid and adaptable, and needs flexible elements such as grids and images that can automatically resize based on the form factor of the requesting device. In addition to resizing elements, you must adapt the page to remove content or unnecessary navigation, because space is at such a premium on small devices.

CSS Media Queries are the foundation of responsive layouts that work across devices. Let’s start with an example of a simple web page with a two column layout in which there is a container <div> and two child <div> tags that render the columns. This layout is for desktop browsers, and later we’ll modify it to run on a phone.

#wrapper 

{ margin:0 auto; height:768px; } #sidebar { background-color:#2885c9; width:24%; height:600px; float:left; } #content { background-color:#229731; width:75%; height:600px; float:right

;
}

<!DOCTYPE html> <html xmlns=”http://www.w3.org/1999/xhtml”&gt; <head> <title>CSS Media Queries</title> <link href=”default.css” rel=”stylesheet” /> </head> <body> <div id=”wrapper”> <div id=”sidebar”><span>Side bar</span></div> <div id=”content”><span>Content goes here.</span></div> </div> </body> </html>

The code above looks like this in IE 10, a desktop browser. There is a column to the left (side bar) and one on the right (content).

 

image_thumb3_2

Of course, this layout just won’t work in a small, portrait, screen. Most side bars are for navigation, that when mobilized is painful to use in such a small form. Repositioning the elements so that the side bar is on top of the content is a much better layout for smart phones, because of the change in orientation. We can do this by creating a media query and modifying the CSS to fit smart phone dimensions. Below is a media query definition containing the same three selectors in the previous sample, but modified for a smart phone layout. What was the leftmost column (the side bar) is now positioned at row #1, and its adjacent content area is now positioned at row #2. As you might expect, the sizes of the elements are smaller than in the desktop version.

@media screen and (max-width: 320px) and (orientation: portrait) { #wrapper { width:320px; height:480px; margin: 0 0 0 5px; } #sidebar { width:320px; height:90px; float:left; margin: 0 0 5px 0; } #content { width:320px; height:380px; float:left

;
    }
}

 

image_thumb2_2SNAGHTML103a6a17_thumb1_2

The media query works great in IE10 desktop when resized to smart phone dimensions (left side, above image). However, in some phones or emulators, the above media query does not work (right side, above image). This is because we are missing a key component in mobilizing content – the <viewport> meta.

Mobilizing sites with the viewport meta

When mobile devices receive content formatted for the desktop or larger sized browsers, their default action is to zoom out to show all the content. The phone browser tries to show the page as a desktop browser does but condensed into its tiny, portrait, view. They do this for backward compatibility of the many non-mobilized sites that phones otherwise render incorrectly and break. We can change this behavior and tell phones to optimize their default zoom for mobile by using the viewport meta element. The viewport meta instructs mobile devices to resize the content to fit on their screen or to a certain scale based on the tag’s attribute values. Below is an all-purpose viewport that resizes content to fit the device:

<meta name=“viewport” content=“width=device-width”/>

If you aren’t sure what attributes to use, use the above as the default, as it renders the page to fit the device. Now because the phone will render the content correctly, and the output looks like the following:

SNAGHTML9843bc_thumb1_thumb

Notice the browser has applied the media query this time. This is because the phone’s browser took a cue from the viewport and rendered the page like a mobile browser rather than a desktop browser.

Summary

As you can see, CSS Media Queries are the best way to deliver perfectly fitted content to any device, with less maintenance hassles. Media queries aren’t just for the Web either – you can write Windows Store apps in HTML/CSS/JavaScript and use media queries for Windows 8 features like Snap-View. If you are working cross platform, don’t worry about support as CSS Media Queries have a wide adoption across desktop and mobile browsers.

Lastly, if you would like to go mobile but must support the older-than-dirt browsers like IE8 and below then check out Respond.js. Respond is a polyfill for CSS Media Queries (a mechanism for backwards compatibility), enabling their use in old or unpopular browsers.

Write Object-Oriented JavaScript with TypeScript

TypeScript, Microsoft’s new language, is proving to be a popular choice amongst ASP.NET and Windows developers. Of course, those coming from the Microsoft stack are used to working with Object Oriented languages, except with significantly differing syntaxes. TypeScript brings familiar OOP constructs to JavaScript. TypeScript is not a new language as it is a superset of JavaScript that generates plain JavaScript. There are four main principles to Object Oriented Programming: Encapsulation, Inheritance, Abstraction, and Polymorphism. TypeScript can implement all four of them with its smaller and cleaner syntax.

For a primer on TypeScript, read TypeScript, A New Language For .NET & JavaScript Developers.

Encapsulation

Encapsulation is a key part of Object Oriented Programming that is a way to structure code so that a certain block of code has specific access points for external code. The term for this is “visibility” or “accessibility”. Visibility defines what code from one method, property, or class can call code in another method, property, or class. In other words, if we were to interact with a real world object like a car, we do so by using only certain parts of the car that are there for that purpose. These components of the car communicate to parts inside the car that perform the actions on our behalf. In the case of a car, these external parts are the pedals, steering, and dashboard controls, while the internal ones are in the engine. This means we don’t need to know what goes on under the car’s hood to make the car go, stop, or turn, all we need to do is interact with the correct component, called an interface. (i.e., the pedals, steering, dashboard controls). To enforce encapsulation in many languages, we use methods and properties. Both are blocks of code, although they differ mostly in syntax rather than conceptually. Behind each method or property is logic that often hides private data and performs complex tasks. The calling code shouldn’t and doesn’t need to know about those things.

In TypeScript, we enforce encapsulation with methods and properties that only allow access to data that we control. The Withdraw method below does that by doing the calculation and updating the class level _balance field. The Balance property then returns the private _balance field to the calling code.

Withdraw(amount: number): boolean
{
    if (this._balance > amount)
    {
        this._balance -= amount
        return true;
    }
    return false;
}

private _balance: number;
get Balance(): number {
    return this._balance;
}

This encapsulates the account’s balance as business logic and validation code can run and access the private variables to formulate something to return to the client. In turn, the client never needs to know what goes on behind the scenes, just how to interact with the object. TypeScript’s syntax is similar to that of a statically typed language like C#, by using constructs like setters and getters.

Inheritance

It’s quite easy to create an object model and inheritance chain with TypeScript. Just start with the familiar class keyword to create classes. The extends keyword causes the child class to inherit from the denoted base class. For example, we can build out a very simplistic SavingsAccount and CheckingAccount classes that derive from a BankAccount class, like so:

module Bank {
    class BankAccount { }

    class SavingsAccount extends B
ankAccount { }

    class CheckingAccount extends BankAccount { }
}

The two above TypeScript samples generate the JavaScript below. It’s very clear in TypeScript sample above that inheritance is happening, but not as clear in straight up JavaScript sample below. Sure, you could write this yourself, but as you can see, TypeScript generates the code you’re supposed to write, but without all the typing involved. There are only three lines of code needed for Bank class, but thirty for JavaScript. That’s a difference of ten times as much.

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Bank;
(function (Bank) {
    var BankAccount = (function () {
        function BankAccount() {
        }
        return BankAccount;
    })();

    var SavingsAccount = (function (_super) {
        __extends(SavingsAccount, _super);
        function SavingsAccount() {
            _super.apply(this, arguments);
        }
        return SavingsAccount;
    })(BankAccount);

    var CheckingAccount = (function (_super) {
        __extends(CheckingAccount, _super);
        function CheckingAccount() {
            _super.apply(this, arguments);
        }
        return CheckingAccount;
    })(BankAccount);
})(Bank || (Bank = {}));

TypeScript classes make it easy to map properties to JSON or XML data, common in web sites and apps. Looking at the above sample, you can see that it does adhere to the module pattern. TypeScript supports single inheritance.

Abstraction

There is no formal mechanism for creating an abstract class in TypeScript, although a request to implement abstraction in TypeScript has been issued. Not to worry, for now we can use interfaces as a way to abstract class members. For example, a bank might have an Fee interface
(their favorite one!) or an Interest interface that all account objects must implement. The Fee interface has members such as ChargeFee and the Interest interface contains one named CalculateInterest. When classes implement these interfaces, they must implement all of the members of the interface, as interfaces serve as digital contracts that classes can adhere to.

You can use the implements keyword to implement an interface in TypeScript, as shown here:

export module Bank
{
    export interface Fee { ChargeFee(amount: number); }

    export class BankAccount implements Fee {
        ChargeFee(amount: number) { }
    }
}

It’s syntactically like the extends keyword.

Polymorphism

TypeScript enables polymorphism via method overrides as you can see in the example below. The Withdraw and Deposit methods of the CheckingAccount and SavingsAccount classes derive from the parent BankAccount class. In the child classes, we can override these methods and add our own business logic customizations, such as waving a fee if the balance is more than a specified amount.

class SavingsAccount extends BankAccount
{
    ChargeFee(amount: number)
    {
        if (this.Balance > 1000) { amount = 0; }
        else { amount += 1.00; } 
         
        this.Balance =+ amount;
    }
}

In this case, we overrided the ChargeFee that was originally part of the Fee interface. Polymorphism is an essential characteristic of OO programming, as code would be quite redundant without it.

Summary

As you can see, TypeScript enables all four of the primary object oriented programming techniques with easy to use keywords and syntax. TypeScript is a bit of a syntactic sugar sprinkled on top of JavaScript, and it fits in many developer scenarios since OOP is such a popular and reigning paradigm. Using TypeScript doesn’t mean you’re off the hook of knowing JavaScript well – the better you know JavaScript is the better you’ll know TypeScript.

To see how you can apply the OOP principles of TypeScript in Windows Store apps, check out my article on MSDN Magazine about Using TypeScript in Modern (Windows Store) apps and my blog posts tagged as TypeScript.

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 ViewsShared 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: ViewsShared. Use the Add New View dialog by accessing the context menu from the ViewsShared 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)

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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;};

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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");

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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"
);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

and Javascript

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

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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;
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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;
        });
};

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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);
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Javascript

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

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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();
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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.