Sunday, September 29, 2013 #

XAML Mood Wheel / Spinner Wheel Control for Windows 8/Store Apps

Have been wanting to revive this blog for a long time but haven’t properly invested the time.  So thought of kicking this off with a control I worked on recently.

One of the requirements for a Windows 8 App was to create a Mood Wheel or rather a Spinner Wheel Control.  Something like below.

image

Now, this is not something that ships out of the box in the XAML control set.  Not even in the Windows 8.1 which has truck load of enhancements in Visual Studio editor for XAML Developers.

I first looked up if there is someone out in the community who has built something similar.  I landed in Diederik Krols Blog. It came close to what I was looking for but more meant towards a roulette and also had challenges when using a single finger to flip it.

Next I looked at Jerry Nixon’s Sweet Dial Control  which looked neat for a Dial.

Combining ideas from both, I built this mood wheel which can be rotated with single finger on touch devices and also mouse on non-touch devices.  The co-ordinates are ascertained using the Grid_ManipulationDelta Method which provides the Angle and the amount of deviation.

Jerry Nixon’s excellent “GetAngle” method helped in identifying the Angle and thereafter, it was pretty simple to use an enum and identify the message to be displayed based on range.

I have uploaded the sample to skydrive and linked here.

Most of the work is in the MyDial.xaml file and is pretty self-descriptive.  If you have  query do drop in the comments and would be glad to clarify.

Cheers!!!

 

Posted On Sunday, September 29, 2013 10:38 AM | Comments (3)

Sunday, April 7, 2013 #

TechEd India Data: Exposing Azure Mobile Services through Web API

For those who attended my session at TechEd India 2013, one of the topics I presented was, on Azure Mobile Services.  I also presented on new enhancements to ASP.NET with the Visual Studio 2012 Fall Update. 

As a mixture of both the sessions, I mentioned about building a Web API feed for Tech Ed Data that could be consumed through Azure Mobile Services.

If you are new to Azure Mobile Services, you can read up about from http://www.windowsazure.com/en-us/develop/mobile/

Azure Mobile Services is best consumed through client apps such as Windows 8, iOS and Android Apps.  Recently, we also launched the HTML5 Apps template for Azure Mobile Services and CORS Support.

However, if you would like to use this in a ASP.NET Application, particularly, Web API, there are a few hops to make.

I decided to expose TechEd India data (Speakers, Schedule, Sessions, Tracks and Sponsors data) as an Azure Mobile Services.  That was good for me to build a Windows 8 App.

When I wanted to expose this in Web API, I had to do couple of things

1. Create Client Classes for each of the Mobile Service Tables. 

2. Create a Web API Controller for each of these classes which would make a HTTPClient request to the Azure Mobile Services.

I found this article handy http://www.strathweb.com/2012/09/using-azure-mobile-services-in-your-web-apps-through-asp-net-web-api/

I pretty much created an API Controller each for Speakers, Tracks, Sessions, SessionsBySpeaker etc.,

Note that, in Azure Mobile Services, these are dummy tables that build upon the original tables to query a JOIN between related tables.

Finally, once you create the API Controllers for each of these classes, I hosted the app on Azure so that it can be consumed as JSon Data.  Note that, if you enable “Read” access for Everyone in the Permissions tab for Azure Mobile Service Table, you can achieve the same functionality.  However, Web API allows you to, a. add a logical layer between Mobile Service and Client Apps.  b. It also allows you to expose OData Queries on top of the Data.  I have provided the currently available URLs. Requesting them should provide you jSon Data.  Hope you find it useful.

Events: http://techedindia2013.cloudapp.net/api/events  

Speakers: http://techedindia2013.cloudapp.net/api/speakers

Sponsors: http://techedindia2013.cloudapp.net/api/sponsors

Track Sessions: http://techedindia2013.cloudapp.net/api/tracksessions  

You could do a OData Query on this, for example, http://techedindia2013.cloudapp.net/api/speakers?$top=1

As of now I have only exposed the GET Methods.  In future, I would refine it to allow all operations.

I don’t know how long I would be able to host this service.  Till then, enjoy!

Cheers!!!

Posted On Sunday, April 7, 2013 8:58 PM | Comments (1)

Monday, April 1, 2013 #

Updated Windows Blog Reader Sample with Background Task

I had earlier posted the Blog Reader Sample with Search Implementation.  The Blog Reader is an excellent place to start to build XAML Windows 8 Apps. I had customized it to include Search and a few other things.

As much as we would love to open the Blog Reader and have it running all the time to check new feeds, it would be nice if we can get those as a part of the Live Tiles.  Live Tiles in Windows 8 allows people to get a peek of what’s happening new and thereafter pre-empts the users to click the Live Tile and get into the application to read the rest of the stuff.

image

Above is my Start screen in which you can see there are Live Tiles for most of the apps including Travel App which has an exciting location picture which induces me to click and find more about the place.

Now, for our Blog Reader sample, we can implement Live Tile such that it keeps checking for new feeds and presents it within our Tile.  Once I find something interesting, I can click and launch the Blog Reader to read about the same.

This obviously involves a service running in the background and keep poling the feeds.  That would make it an ideal candidate for background task.  Background Tasks in Windows 8 allows a process to run in the background while the app may/may not be active.  They are very handy in a variety of scenarios, particularly for the fact that Apps in Windows 8 gets pushed to suspended state in 2 seconds and there is really no way to keep them running infinitely and keep checking for new stuff.

In our case, I have added a Background Task Project and a class which implements the Run method to keep checking for the feeds.  This is based on the Background Task Sample QuickStart

The actual implementation is 3 methods in the Background Task and a method in the ItemsPage.xaml in the main project.

In principle with DRY (Do not Repeat), I am going to again point to the link here

The only change I have made is to make the feed check the ASP.NET Main Page RSS Feed.

You can download the completed project from here

Cheers !!!

Posted On Monday, April 1, 2013 8:44 AM | Comments (2)

Wednesday, March 6, 2013 #

Charting in Windows 8 Store Apps

One of the queries I received from a partner was to have charting implemented in their Windows 8 Application.  While by default there are no chart controls, there are a lot of third party controls such as Telerik, Component One, providing charting for Windows 8.

However, there is also the WINRTXamlToolkit, available in CodePlex.  It provides a bunch of useful controls that are not available, by default, in XAML for use in Windows 8 Store Applications.

http://winrtxamltoolkit.codeplex.com/releases/view/99868

Also, specifically for Chart, you can install it from the Package Manager Console. 

Visual Studio 2012 –> View –> Other Windows –> Packager Manager Console

It opens up the Package Manager Console.  In the prompt, type

Install-Package WinRTXamlToolkit and then

Install-Package WinRTXamlToolkit.Controls.DataVisualization

Once you install this, you can start referencing the Chart Controls in your XAML Page.

The complete sample can be downloaded from the above codeplex link which also includes a sample project with all the controls.

But, for our simple demonstration purposes, I created a Blank Windows Store Application. 

Visual Studio 2012 – File – New Project – Visual C# – Windows Store – Blank App (XAML)

I then opened the Package Manager Console and ran the above PowerShell commands.

Just to verify the assemblies are ordered open “References” to see the WinRTXamlToolkit and WinRTXamlToolkit.Controls.DataVisualization

Open up MainPage.Xaml and add the following lines to the Page Declarations in top

xmlns:datavis="using:WinRTXamlToolkit.Controls.DataVisualization"    xmlns:charting="using:WinRTXamlToolkit.Controls.DataVisualization.Charting"
    xmlns:Series="using:WinRTXamlToolkit.Controls.DataVisualization.Charting
"

Then, within the Grid, add the following snippet

<charting:Chart
                x:Name="PieChart"
                Title="Pie Chart"
                Margin="70,0">
            <charting:Chart.Series>
                <Series:PieSeries
                        Title="Population"
                        ItemsSource="{Binding Items}"
                        IndependentValueBinding="{Binding Name}"
                        DependentValueBinding="{Binding Value}"
                        IsSelectionEnabled="True" />
            </charting:Chart.Series>
        </charting:Chart>

In the codebehind of MainPage.xaml, add the following

public class NameValueItem
       {
           public string Name { get; set; }
           public int Value { get; set; }
       }

We are simulating X,Y axis using a generic Text and Random Number.  Hence we need

private Random _random = new Random();

private void UpdateCharts()
       {
           List<NameValueItem> items = new List<NameValueItem>();
           items.Add(new NameValueItem { Name = "Test1", Value = _random.Next(10, 100) });
           items.Add(new NameValueItem { Name = "Test2", Value = _random.Next(10, 100) });
           items.Add(new NameValueItem { Name = "Test3", Value = _random.Next(10, 100) });
           items.Add(new NameValueItem { Name = "Test4", Value = _random.Next(10, 100) });
           items.Add(new NameValueItem { Name = "Test5", Value = _random.Next(10, 100) });

((PieSeries)this.PieChart.Series[0]).ItemsSource = items;

}

Modify the Constructor to include the UpdateCharts method

public MainPage()
        {
            this.InitializeComponent();
            UpdateCharts();
        }

That’s it, you are set to run the Project and when you run it, you will see the output below

image

There are Bar Charts, Bar Series Charts, Line Charts, Scatter Charts and many other types.  

I have extract the above sample code from the large sample repository at http://winrtxamltoolkit.codeplex.com/SourceControl/list/changesets

You can download this sample from http://sdrv.ms/13G8Si0

Cheers!!


 

Posted On Wednesday, March 6, 2013 4:31 PM | Comments (6)

Sunday, February 17, 2013 #

ASP.NET SignalR “SCRIPT5007: Unable to get property 'client' of undefined or null reference” error

I was playing around with ASP.NET SignalR and while trying to use Hubs, stumbled upon this error.  Much as I would know that I was doing all the wrong things, I could recognize it has something to do with the line I had to embed in script

<script src="/signalr/hubs"></script>

When I added the above line, I was wondering where does this reference come from.  I assumed this must be one of the script bundling techniques of ASP.NET that would be resolved in the runtime from server.

However, found that the error occurred since I had not mapped the MapHubs in the Global.asax.

so, all I had to do was open up the Global.asax (create one if you don’t have it yet in the project) and in the Application_Start Method, add the following line.

 RouteTable.Routes.MapHubs();

With that, this error resolved.

Quick learning thought worth sharing.

Cheers!!!

Posted On Sunday, February 17, 2013 4:49 PM | Comments (9)

Friday, December 7, 2012 #

Implementing Search for BlogReader Windows 8 Sample

The BlogReader sample is an excellent place to start speeding up your Windows 8 development skills.  The tutorial is available here and the complete source code is available here

Create a project called WindowsBlogReader and create pages for ItemsPage.xaml, SplitPage.xaml and DetailPage.xaml and copy the corresponding code blocks from the sample listed above.

Created a class file FeedData.cs and copy the code.  Finally, create a class DateConverter.cs and copy the code associated with it.

With that you should be able to build and run the project.  There seems to be one issue in the sample feeds listed that the first week (feed1) doesn’t seem to expose it.  So you can skip that and use the second feed as first feed.  You will end up with one feed less but it works.

I had demonstrated this in the recent TechDays at Chennai.  How we can use the Search Contract and implement Search for within the Blog Titles.

First off, we need to declare that the App will be using Search Contract, in the Package.appmanifest file

image

Next, we would need a handle of the Search Contract when user types on the search window in Charms Menu.

If you had completed the code sample from the link above, you would have ItemsPage.xaml and ItemsPage.xaml.cs.  Open the ItemsPage.xaml.cs.

Import the namespaces using System.Collections.ObjectModel and System.Linq.

in the ItemsPage() constructor, right after this.InitializeComponent(); add the following code

Windows.ApplicationModel.Search.SearchPane.GetForCurrentView().QuerySubmitted += ItemsPage_QuerySubmitted;

This event is fired when users open up the Search Panel from Charms Menu, type something and hit enter.

We need to handle this event declared in the delegate.  For that we need to pull the FeedDataSource instantiation to the root of the class to make it global.

So, add the following as the first line within the partial class

FeedDataSource feedDataSource;

Also, modify the LoadState method, as follows:-

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
       {
           feedDataSource = (FeedDataSource)App.Current.Resources["feedDataSource"];

           if (feedDataSource != null)
           {
               this.DefaultViewModel["Items"] = feedDataSource.Feeds;
           }
       }

Next is to implement the ItemsPage_QuerySubmitted method

void ItemsPage_QuerySubmitted(Windows.ApplicationModel.Search.SearchPane sender, Windows.ApplicationModel.Search.SearchPaneQuerySubmittedEventArgs args)
        {
            this.DefaultViewModel["Items"] = from dynamic item in feedDataSource.Feeds
                                             where
                                             item.Title.Contains(args.QueryText)
                                             select item;
        }

As you can see we are almost using the same defaultviewmodel with the change that we are using a linq query to do a search on feeds which has the Title that matches QueryText.

With this we are ready to run the app.

Run the App.  Hit the Charms Menu with Windows + C key combination and type a text to search within the blog.

You can see that it filters the Blogs which has the matching text.

We can modify the above Linq query to do a search for the Text in other attributes like description, actual blog content etc.,

I have uploaded the complete code since the original WindowsBlogReader Code is not available for download.  You can download it from here

note:  this code is provided as-is without any warranties. 

Cheers!!!

Posted On Friday, December 7, 2012 1:20 PM | Comments (23)

Monday, June 25, 2012 #

FTP Publishing with the new Windows Azure Release

There is a good chance you might have stumbled upon the new Windows Azure Release that we made on June 6th.  Scott Guthrie’s Post quite summarizes the overall new features.

One of my favorite features is the Windows Azure Websites and the ability to do publish files to Azure using your FTP Client.

Windows Azure Websites offers low cost (free upto 10 websites) web hosting where you can deploy any website that can run on IIS 7.0, quickly.

The earlier releases of Azure SDKs and the Azure platform support .NET 3.5 & above for running your applications.  This was a constraint for many since there are/were a lot of ASP.NET 2.0 applications built over time and simply to put it on Azure, many of you were skeptical to migrate it to .NET 4.

Windows Azure Websites offer the flexibility of running IIS 7.0 supported .NET Versions which means you can run .NET 1.1, 2.0, 3.5 and .NET 4.  Not just that! You can also run classic ASP Applications.

Windows Azure Websites don’t need you to go through the complexity of adding the Cloud Project Template and then publishing the Configuration Files.  Lets take a step by step understanding of Websites and publishing using FTP.

I downloaded the Club Website Starter Kit from http://www.asp.net/downloads/starter-kits/club

It also requires a database and I downloaded the SQL Scripts and created a SQL Server Database called Club.

This installs a Web Site Project Template.  Note that I am running Windows 8 Release Preview and Visual Studio 2012 RC.  After installing the template, select File – New – Website and don’t forget to choose the Framework version as .NET 2.0

image

You can see the “Club Website Starter Kit” .  Once you select the Website gets created.  You would encounter a warning indicating that the Club Website Starter Kit uses SQL Express and the recommended database is LocalDB Express.  Click ok to continue.  Once the Website is created open up the Web.config and locate the “ClubSiteDB” connection string.  By default, it points to a SQL Express Database.  Instead configure it to use your local SQL Server.

Also, open up Global.asax and comment out the following line

if (!Roles.RoleExists("Administrators")) Roles.CreateRole("Administrators");

There seems to be an issue in the code that doesn’t create the role. 

Post that, hit CTRL+F5 and you should be able to see the Website Running, as below

image

So, now we have the Club Starter Kit site up running locally. 

Moving to Azure

Visit http://manage.windowsazure.com/ and sign up for a trial account.  This allows you to host up to 10 websites for free and a host of other benefits.  The free Websites can be extended to an year without any charge.  Once you have signed up, sign in to the portal using the Live ID used for sign up.

After signing in, you would be presented with the “All Items” listing page which lists, Websites, Cloud Services, Databases etc.,  If this is the first time, you wouldn’t find anything.

Click on the “Websites” link from the left menu.  Click on “New” in the bottom and it should show up a dialog.  In the same, select Website and click on “Quick Create” and in the URL Textbox, specify “MyFirstDemo” and click the “Create Web Site” link below.

image

It should take a few seconds to create the Website.  Once the Website is created, click on the listing and it should open up the Dashboard.  Since we haven’t done anything yet, there shouldn’t be any statistics

image

Click on the “Download publish profile” link in the right bottom.  This file has the FTP publishing settings.

Also, if you scroll down you can see the FTP URL for this site.  It should typically start ftp://waws-xxxx-xxx-xxxx

In the downloaded publish profile file, you can also find the ftp URL.  Pick the following from this file

publishUrl (the 2nd one, the one that features after publishMethod =”FTP”) and the userName and userPWD that follows.

Note that we have everything required to publish the files.  But since the Club Starter Kit uses Databases, we need to have the Database running on SQL Azure. 

Go back to the Main Menu and click on “New” in the bottom but this time select “SQL Database” and provide “Club” as Database name for “Quick Create”

image

If this is the first time a Server would be created.  Otherwise, it would pickup the existing server name.

Once the database is created, you can use the SQL Azure Migration Wizard http://sqlazuremw.codeplex.com/ and provide the credentials to connect to local database and then the SQL Azure database for migrating the “Club” database.  The migration wizard UI hasn’t changed much and is the same as explained by me in one my posts earlier http://geekswithblogs.net/ranganh/archive/2009/09/29/taking-your-northwind-database-to-sql-azure-and-binding-it.aspx

Once the database is migrated, come back to the main screen and click on the Database base in the Azure Management Portal.  It opens up the dashboard of the database.  Click on “Show connection Strings” and it would popup a list of connection string formats.  Choose the ADO.NET connection string and after editing the password with the password that you provided when creating the database server in the Azure Portal, paste it into the config file of the Club Starter Kit Website.  Just to reiterate, the connection string key is ClubSiteDB.

Try running the Website once to ensure that the application though running locally could connect to the SQL Database running on Azure.

Once you are able to run the website successfully, we are all set to do the FTP Publishing.

Download your favorite FTP tool.  I use http://filezilla-project.org/

In the Host Textbox, paste the FTP URL that you picked up from the publish profile file and also paste the username and password.  Click on “QuickConnect”.  If everything is fine, you should be able to connect to the remote server.  If it is successfully connected, you can see the wwwroot folder of the Website, running in Azure

image

Make sure on the “Local Site” in the left, you choose the path to the folder of your Website.  Open up the Website folder on the left such that it lists all the files and folders inside.  Select all of them and click select “Upload” or simply drag and drop all the files to the root folder that is listed above. 

Once the publishing is done, you should be able to hit the SiteURL that you can find the dashboard page of the website.  In our case, it would be http://MyFirstDemo.azurewebsites.net

That’s it, we have now done FTP publishing in Azure and that too we are running a .NET 2.0 Website on Azure.

Cheers !!!

Posted On Monday, June 25, 2012 10:09 PM | Comments (55)

Friday, June 15, 2012 #

Multi-monitor support in Windows 8


Posted On Friday, June 15, 2012 11:33 AM | Comments (24)

Saturday, April 21, 2012 #

JsonValueProviderFactory in MVC 2

Today we were rebuilding an old project which used MVC 2.  There were a bunch of build errors, which I quickly figured was because of the reference to Microsoft.Web.MVC assembly which was a part of the Futures Preview for MVC 2 before MVC 3 came.

I removed the reference and secondly, I installed MVC 3 on the machine.  After that I removed all references to MVC 2 assemblies and added reference to the System.Web.Mvc dll version present in C:\Program Files(x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies.

With that, some of the errors went off.  But upon further building the project, I ran into quite a few issues with respect to Razor Views and existing MVC 2 codebase.

My colleague, as paranoid as always wanted to revert back to MVC 2 given that, there would be more work in changing all of them to suit MVC 3 assemblies and it wasn’t required at this time for a project which was working fine.  Typical customer style.

Then, I went ahead and removed the reference to MVC 3 and added back the MVC 2 assembly.

Bang came back the error on JsonValueProviderFactory references in Global.asax.  After scratching around for sometime, I figured that this assembly is now part of the System.Web.Mvc in MVC 3 whereas if we have to use it in MVC 2, we need to explicitly download and add the MVC 2 Futures Preview available at http://aspnet.codeplex.com/releases/view/41742 

Since the code was ported from another machine, this wasn’t copied and just MVC and required assemblies were installed.

I went ahead and installed the MVC 2 features which had the DLL Microsoft.Web.Mvc and after adding a reference to that DLL in the project and then putting up a using Microsoft.Web.Mvc, the error on line JsonValueProviderFactory vanished.

Please note, this is only required if you stick to use MVC 2 and with MVC 3 and above, this is not required.

Also, the MVC 2 futures was an experimental release, so I would assume it wouldn’t be supported and one has to use at one’s own risk.

Cheers !!!

Posted On Saturday, April 21, 2012 9:57 PM | Comments (11)

Friday, April 20, 2012 #

Single Page Application and why is it becoming more and more popular

One of the key trends becoming more and more popular is the Single Page Application Framework and building applications that behave as native applications running on the machine.

SPA’s have been tried and tested for a while now and with libraries like Knockout.js, Backbone.js becoming more and more capable, it becomes feasible to create SPA’s.

What is an SPA?

I can describe in length but falling in line with DRY principle, here is the Wiki Link http://en.wikipedia.org/wiki/Single-page_application

But in short, it is a framework that builds highly responsive web applications that don’t infuse post backs and page reload. 

I can almost hear you say.

“Wait!! Isn’t that what AJAX and XMLHttpRequest promised?”

“Can’t I do it with Iframe?”

Hence this post, “Why SPA” now

Traditional web developers have tried using a variety of means to do this Single Page Application using Iframes, XMLHttpRequest, AJAX, jQuery and a variety of libraries.  There are caveats to each of these approaches.

First major issue with Iframes is the ability to communicate between the parent and the iframe.  80% of questions about Iframe in various forums (including my most popular blogpost on iframe) are about communication between the page in iframe and the parent.

The next with respect to asynchronous call backs is that, the URL doesn’t get updated and this causes 2 issues

1. There aren’t much URLs and hence the website isn’t search engine friendly

2. Users press the “Back” button and get an unexpected behaviour since the browser history is not updated and hence takes them to different locations instead of the previous stage.

How Single Page Application solves these issues?

Single Page Applications use a parameterized URL which defines various operations that you do.  For example, it may append an action to the base URL as below

http://localhost:2015/Task/?editItem=added5

Secondly, SPAs use history.js library (native.history.js) for maintaining the state of the page, so even though all the operations happen quickly and on the client side, the browser’s back button behaves normally and the page state is saved.

In addition to solving the above problems, SPA’s use a combination of template binding scripts, Data Model Scripts, Services and Data Templates making it all the more richer in functionality, to build.

Finally, SPAs integrate well with the new HTML5 features such as LocalStorage and Application Cache for building Offline Web Applications and make it easy to build apps that behave the same when not connected.

What does Microsoft have for developers?

In MVC4 Beta, there is Single Page Application Template that allows you to build SPAs with minimal effort.  The default template comes with all the required libraries wired up and a sample ToDoItem.cs file which is the model for data.  Upon building the solution and creating a TasksController which is based on the ToDoItem Model, one can navigate to the base URL + Tasks to experience creating /editing Tasks all of it in a Single Page Experience, both quick and elegant.

And since this post has been all talk and no technical tip, here below is one.

The Default SPA Template that comes up when you create a “File – New – ASP.NET MVC 4 Web Application – Single Page Application” Project which was released along with VS11 Beta is a bit out dated now.

Once the SPA Template Project is created, we need to run the NuGet command line utility (Tools – Package Manager Console) and type Install-Package SinglePageApplication.CSharp

This gives a much improved SPA Template to work with as outlined by Steve Sanderon himself, in his blog post.

Cheers !!!

Posted On Friday, April 20, 2012 12:14 AM | Comments (39)

Saturday, February 25, 2012 #

Building a Northwind Single Page Application using ASP.NET MVC 4 Beta - Part 2

This post is in continuation with my earlier post, so you may want to read that first before continuing.

Once I removed all the TasksController files and the TodoItem, I chose the Models folder, right click and “Add New Item” and searched for “ADO.NET Entity Model” and added it to the folder.

image

It allowed me to connect to the Northwind database through “Generate from database” and I selected just three tables “Products”, “Categories” and “Suppliers” table for simplicity.  At the end of the wizard, we get a EDMX design file with the 3 tables.  On this screen I right clicked and choose “Add Code Generation Item” as below

image

and then in the dialog that came up, chose the “ADO.NET DbContext Generator” and Added (note, if you don’t see this template, you probably don’t have Entity Framework 4.1 installed)

This step created the Model1.Context (not required for us though Smile) and the Model1.tt template which groups the individual class files for each of the tables above (these are required Smile)

The next thing I did, was to remove the NorthwindEntities connectionstring that got automatically added when we followed the ADO.NET Entity Model wizard.  We don’t need this connection string.

Also, I deleted the Model1.Context file and also the Model1.cs files which are not required (we will be generating a new context to suit our database name)

image

Note that these files are not required only for our SPA approach here and they are required when working with EF CodeFirst normally as they do the DbSet Tracking and whole bunch of things

So, we now have the basic model classes required for wiring up our Controller required to create the SPA Pages.   One important thing I learnt in this process was that, I had to edit the Model classes as follows:-

In Supplier.cs added the “private” keyword to the ICollection<Products> property.  Same is the case with Category.cs.  Otherwise you would run into an error explained here.

image

After this, I added Controller for Products as per the settings below (Right Click Controller – Add –Controller)

image

Note several important things.  I have chosen the “Single Page Application with read/write actions and views, using Entity Framework” template under Scaffolding options.  Also, I have edited the Data context class and made it simply MvcApplication126.Models.Northwind.  This would be referenced in the web.config connection string as well so that SPA picks up our existing Northwind database instead of creating a new one.

Once you click “Add” the following files are generated. 

Under Controllers

  • NorthwindController.cs
  • NorthwindController.Product.cs
  • ProductsController.cs

Under Scripts

  • ProductsviewModel.js

Under Views

  • Products folder and the Views and Partial Views required

Repeat the steps for adding Controllers for “Categories” and “Suppliers” and the only change would be the respective Model Classes.

One important thing to do is to add the following connectionstring to the web.config file

<add name="Northwind" connectionString="Data Source=SERVERNAME;Initial Catalog=Northwind;User Id=YOUR USER NAME;Password=YOUR PASSWORD" providerName="System.Data.SqlClient" />

Then, when you run the project, it opens up the default Home Page. 

  • Navigate to /Products and it should load the list of Products from Northwind database.
  • Click on each product and edit and note that everything happens in a single page inline. 
  • Just notice the URLs change in pattern with hash tags. 
  • Notice that the Categories and Suppliers are wired up as dropdownlists since these are foreign key references.
  • Notice that all the items load asynchronously

I went ahead and edited the Shared –> Layout.cshtml under Views folder to add Menu Items for Products, Categories and Suppliers, as below:-

<ul id="menu">
         <li>@Html.ActionLink("Home", "Index", "Home")</li>
         <li>@Html.ActionLink("Products", "Index", "Products")</li>
         <li>@Html.ActionLink("Categories", "Index", "Categories")</li>
         <li>@Html.ActionLink("Suppliers", "Index", "Suppliers")</li>
         <li>@Html.ActionLink("About", "About", "Home")</li>
         <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>

Now, we have our full blown Northwind Traders Application running as a SPA. 

You can download the sample from https://skydrive.live.com/redir.aspx?cid=069f94a102eff49a&resid=69F94A102EFF49A!919&parid=root

I have also hosted the sample online at http://northwindspa.cloudapp.net/ 

Cheers !!!

Posted On Saturday, February 25, 2012 6:53 PM | Comments (21)

Building a Northwind Single Page Application using ASP.NET MVC 4 Beta - Part 1

Single Page Application Frameworks are gaining popularity in the ever evolving web community with lot of libraries such as JavaScriptMVC, Backbonejs and many other libraries.  ASP.NET MVC 4 introduces experimental support for building single page application (SPA) through a template.  Much of the plumbing work of wiring up the client side scripts, javascript modelviews and the controllers is automated, making it a quick start to develop SPAs relatively easier.  Lets examine a scenario where we are building a Northwind Store using SPA.

I installed the ASP.NET MVC 4 Beta for Visual Studio 2010 and the Northwind Sample Database for SQL Server

Post that I did a “File – New Project – ASP.NET MVC 4 Web Application”

image 

In MVC 3 we are used to see a screen with 3 options i.e. Intranet, Internet and Empty templates.  In MVC 4 we have additional templates as you can see below and I chose the “Single Page Application” template and created the project template.

image

The default template creates the scaffolding templates for Models, Views and Controllers as it would do for any regular ASP.NET MVC Project.  The differences with SPA template is that, it adds a Model class “ToDoItem.cs” and opens it up by default.  The next step as outlined here in the ASP.NET Site Getting Started with SPA Page is to build the solution as this Model gets registered into the Models dictionary and then adding a Controller named “TasksController” which would use this “ToDoItem” as Model class and creating a new DataContext class and then running the solution.  When you run the solution and navigate to /Tasks, you get to see nice javascript based Tasks Page where one can create Tasks, Edit Tasks etc.,  I went little into examining the kind of files created and found that it creates a ContextNameController and ContextNameController.Model.cs file inside the Controllers in addition to the actual Controller we created which in our case is TasksController.

image

Next, the important folder Smile is the Scripts folder and there I found that it creates a <Modelname>ViewModel.js file that holds all the observer pattern script required.  In addition, this folder contains a truckload of JavaScript files including jQuery, Knockout, upshot and modernizr.

image

Finally, inside the “Views” folder, it creates the necessary Partial Views and Index View for Tasks.   Once you build and run, you can experience all of this SPA for your TodoItem Model without having written a single line of JavaScript code yet.

Now, things I learnt

1. The ContextName that you select when creating the TasksConroller (inour case it is MVCApplication126Context)is important for you to work with other Databases.  By default when you run this solution, Visual Studio would create a SQL Express Database in C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA folder with the name MVCApplication126Context. 

The way I see the SPA framework identifies is, if you don’t have a connectionstring by the name of the Context, it defaults to creating a database in SQL Express with the ContextName in the above mentioned path.

If you have a connectionstring mentioned with the same contextname, it tries and uses that Database (SQL Express, SQL Server). However, when you are running for the first time, if you create a Database and point it in the connectionstring, it would expect that the Table (mapped to the model i.e. TodoItems) need to exist.  Otherwise, it throws an exception.  So best, is to either use a Model for which there is a Table that already exists in the Database or provide a new Database name in which case, VS would create the Database with the TodoItems Table as well.   There must be someplace to configure all of these, but for the lack of time I didn’t delve deep into these things for now.

So, coming to our Northwind Sample.  Northwind has been Developers’ best friend to experiment new things and the saga continues here.

I had to do a couple of things though.  First I removed the TodoItem.cs class and also removed the TasksController, Views since we don’t need them.  So, for all practical purposes, it is now a plain MVC 4 Application with the default Home & Account Controllers and their respective Views.   I also removed the Contextfiles created inside the Controllers Folder.

A bit of analogy on how I built this Northwind App before I explain the actual steps.

The TodoItem is a simple class file and can be hand wired.  However, in real world, or for that matter, a simple Northwind database table has a lot of columns and hence properties to be wired up.  Also, it requires to map foreign relationships and other things.  So, I decided to use the ADO.NET Entity Data Model first to create a model class for the Northwind Database.    This would help me in generating DbContext classes using EF CodeFirst Template, which are much simpler than the complex EDMX file that is created by the ADO.NET Entity Model.  Thereafter, I can use the class files generated to create the Controller, View and JS ViewModels.

More on these in the next part!!!

Posted On Saturday, February 25, 2012 6:51 PM | Comments (24)

Monday, January 16, 2012 #

Diving Deep: ASP.NET Membership and the new Universal Providers


Posted On Monday, January 16, 2012 4:23 PM | Comments (28)

Tuesday, January 10, 2012 #

'Microsoft.ServiceBus.TransportClientCredentialType' is obsolete

Once you upgrade to the Windows Azure SDK 1.6 you also get the updated Microsoft Service Bus assemblies (version 1.6.0.0) that you can use for working with Windows Azure Service Bus (yeah, no longer AppFabric Service Bus)

One of the standard implementations of Service Bus is  to use the CredentialType, Credentials (the service bus namespace and the issuer key and issuer name) to create the service bus namespace URI.

Once you upgrade to Windows Azure Service Bus (Microsoft.ServiceBus) version 1.6.0.0, the following are the errors you might encounter.  These are rather warnings.

'Microsoft.ServiceBus.TransportClientCredentialType' is obsolete

'Microsoft.ServiceBus.TransportClientEndpointBehavior.CredentialType' is obsolete: '"This property is deprecated. Please use TransportClientEndpointBehavior.TokenProvider instead."'

'Microsoft.ServiceBus.TransportClientEndpointBehavior.Credentials' is obsolete: '"This property is deprecated. Please use TransportClientEndpointBehavior.TokenProvider instead."'

'Microsoft.ServiceBus.TransportClientEndpointBehavior.Credentials' is obsolete: '"This property is deprecated. Please use TransportClientEndpointBehavior.TokenProvider instead."'

While this is nicely documented in the release notes, the new equivalent for this is Token Provider.  So here below is a sample implementation code which uses Token Provider and TransportClientEndPointBehaviour namespaces.

Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "SERVICE NAME”);

// create the credentials object for the endpoint

TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

TokenProvider tokenProvider = tokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);

sharedSecretServiceBusCredential.TokenProvider = tokenProvider;

// create the channel factory loading the configuration

ChannelFactory<IDirectoryService> channelFactory = new ChannelFactory<IDirectoryService>("DirectoryEndpoint", new EndpointAddress(serviceUri));

channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);

Cheers!!!

Posted On Tuesday, January 10, 2012 10:51 PM | Comments (4)

Windows Azure Service Bus November 2011 Release

I have been working on Windows Azure Service Bus for the recently concluded Azure Camps 

Yes, it is no longer referred as “Windows Azure AppFabric Service Bus”.  All the 3 components i.e. Service Bus, Access Control and Caching are hereinafter referred to as simply Windows Azure Service Bus, Caching & Access Control Service, to minimize the complexity in referring to them.

Also, Service Bus and the related releases usually come as an out of bound release and are usually behind in terms of the Windows Azure SDK releases.  The Windows Azure SDK latest release is the 1.6 version and along with, there is also a new version of the Service Bus.  Earlier, the Service Bus assemblies sit inside the C:\Program Files\Windows Azure AppFabric SDK folder.

With the 1.6 version of the release of SDK, the Service Bus assemblies also sit inside the regular Windows Azure SDK folder.  Therefore, you can find the latest version of Service Bus i.e. Microsoft.ServiceBus sits inside C:\Program Files\Windows Azure SDK\v1.6\ServiceBus\ref folder.

Similarly, the Caching assemblies sit inside C:\Program Files\Windows Azure SDK\v1.6\Cache\ref folder.

The latest version of ServiceBus is hence 1.6.0.0 and hence if you are installing, you need to make sure you update the assembly version in the config files. 

Otherwise, you would typically get the wrong assembly referenced error, as follow

Exception type:   System.Configuration.ConfigurationErrorsException
Message:          Configuration binding extension 'system.serviceModel/bindings/netTcpRelayBinding' could not be found. Verify that this binding extension is properly registered in system.serviceModel/extensions/bindingExtensions and that it is spelled correctly.

Particularly, if you are using the http://www.microsoft.com/download/en/details.aspx?id=19925 Azure AppFabric samples, they reference the older version of the assembly.  And you need to update them. The release notes http://msdn.microsoft.com/en-us/library/windowsazure/hh667331.aspx covers pretty much line by line on the binding changes to be included in the config file. 

So, now, whether you develop for Windows Azure Hosted Services, Storage Services or Windows Azure Service Bus you need to install, just one SDK and all of them reside under the C:\Program Files\Windows Azure\SDK folder.

In my subsequent post, I want to cover a specific deprecated assembly, its implementation and the new equivalent.

Cheers !!!

Posted On Tuesday, January 10, 2012 9:04 PM | Comments (4)