Windows 8 store apps using async and await

Using async and await in windows 8 store apps bit tricky sometimes. Here I’m listing below some of the do’s and don’ts when working with async and await.

1) Always use void type for  top level async method. Don’t use return type Task for top level async method i,e. the method called by some app handler  for example click, onnavigatedfrom, onloaded etc.  This may not be same for console apps, where the top level method should always return Task in order to put wait instruction from Main method. Using same Task.Wait() in store apps blocks the UI thread and enters into deadlock.

   void Page_Loaded(object sender, RoutedEventArgs e)
public static async void TopLevelMethod()
     var response = await PostAsync(url, content);

Without any top level async method

 async void Button1_Click( object sender, RoutedEventArgs e)
 var response = await PostAsync(url, content);

2) To update UI before and/or after async operation, include update code in the async method but not in its caller for example showing/hiding progress ring or some alert after receiving response etc.

3) If your top level async method is called by timer event or some other scheduler  event and it is accessing any UI related stuff, then use Dispatcher.RunAsync to run that method uses same thread context.

Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, TopLevelMethod);

4)  Utilize features of newly introduced simplified HttpClient class for all asynchronous get and post methods. You can use httpwebrequest async methods but same can be achieved with lesser code using HttpClient.


Example using httpclient post async (fewer lines )

public static async Task PostAsync(string url, string postContent)
            using (var httpClient = new HttpClient())
                var httpContent = new StringContent(postContent, Encoding.UTF8, "text/xml");

                using (var response = await httpClient.PostAsync(url, httpContent))

                    string content = await response.Content.ReadAsStringAsync();

                    return content;

5)  Use always async and await for all anything that reads/writes from/to media(disk i/o etc.).


var file = await Package.Current.InstalledLocation.GetFileAsync("Data\\Groups.txt");
var result = await  FileIO.ReadTextAsync(file);
var xml = await reader.ReadToEndAsync()

URL Rewrite outbound rule examples

Here I’m providing short examples with ui rules only. I’ll assume you have some knowledge in URL Rewrite otherwise I’ll suggest you to read official documentation at

I’m listing below some examples in the form of questions and how to solve them

Outbound rules

Note: in some of the outbound rules precondition responseHtml1 configured as below

1) Add custom script at the end of the response html

2) Add custom script at the beginning of response html

3) Rewrite subdomain with different domain with same URL path and query

Example:  I want to rewrite


Only domain part is changing, path and query is same.

4) Modify redirect location domain to a different domain with same path and query only when particular words exists.

For example:

Modify response header location if path starting with accounts or customer to different domain  or

to or

5) Remove body onload function in response html





6) Find all the links with some text and prevent click on them


Click here to visit;


Click here to visit

Alternatively, you can attach some javascript(preventDefault or something) to href

I’ll update more examples asap.

Portable class library with asmx soap service

Recently I was working on a portable class library(PCL) example in VS2012 to create a proxy class for an external asmx soap service with return types DataTable and DataSet. The easiest way to create a proxy class to add a service reference. In my case, it failed. The add service reference generated code  contains XmlElement and failed to generate response messages with DataTable and DataSet. VS2012 gives a warning for Xml Element.

The alternative way to add service reference is to create a HttpWebRequest to asmx service wsdl and use System.ServiceModel.Description.ServiceDescription to load response xml and parse WSDL. This is one too not supported in PCL.

Because of these limitations, What I think a work around for this is to create a custom wsdl parser or manually construct soap envelopes and parse responses but its not an easiest way to do it and a time consuming.

Some of the limitations of PCL are

1) PCL doesn’t support System.Xml.XmlElement, instead use System.Xml.Linq.XElement

2) PCL doesn’t support System.Data.

3) PCL doesn’t support some of the member classes of System.ServiceModel.Description for example ServiceDescription, WSDLImporter etc.

My project target settings as below

Windows 8 store apps

I love these store apps. The most interesting and promising feature is integration of html, css technologies as well as support for .Net languages like C# etc.

Windows 8 store apps are nothing but those acquired from Windows store and are different from desktop applications. All the store apps runs in a restricted app container.

Html/Jscript based apps mainly aimed at jscript/html developers. These apps uses WinJS toolkit and WinRT(windows run time). WinJS toolkit provides JS classes, helpers, patterns, html implementation of controls etc where as WinRT javascript api provides api to access platform features.

Windows 8 provides WinRT api to access platform core features like networking, storage, media, graphics etc. This api can be accessed from Javascript, C#, C++ and VB.




I’m a web developer and is flexible with html/jscript, xaml/c# apps. I choose xaml/c# if advanced functionality and behaviour are required in my app. Html/jscript apps are simple and quick to develop(you just need a html and jscript files).


MVC3 – Passing dynamic objects to views

In this post, I’ll explain how to pass a model with dynamic objects to a view.

If you are new to C# 4 features like dynamic objects, ExpandoObject etc I suggest to visit below links to get familliar with the concepts.

By using dynamic and ExpandoObject, you can pass a runtime object with some dynamic properties to a view and use them efficiently.

Controller Action

 public ActionResult DisplayDynamic()
      dynamic obj = new ExpandoObject();
      obj.FirstName = "Raj";
      obj.LastName = "Bandi";
      obj.Country = "Australia";

      return View("DynamicView", obj);

//here I’m creating a simple view without any layout just to explain how to use the object

@model dynamic

  1. First Name: @Model.FirstName
  2. Last Name: @Model.LastName
  3. Country: @Model.Country


Source Code

MVC3 Posting form data without refreshing a page

In this post, I’ll explain how to post form data without refreshing a page using JQuery ajax and JSON.

Here, I assume a model is used to render form(form elements names same as model properties).

**Step 1:**

Define an action that takes Model as parameter and returns a json object along with attribute HttpPost(simple way)

public JsonResult PostMethod(YourModelType m)
   // Do something with the model, all the form elements posted are available in the model

   //return json string. Json method that serializes any C# object to json format.
   return Json(your object, JsonRequestBehavior.AllowGet);

**Step 2:**

Add javascript function to post data

function PostData(form)
  //use only if you wish to validate the form before posting, requires JQuery.validate plugin
 if (!$(form).valid()) {


    // use $.post, $.ajax can also be used but with some additional parameters
    // 1st parameter is form action to submit, 2nd parameter serialized form data
    // 3rd parameter is the function to be called after successful post and return value
    $.post($(form).attr('action'), $(form).serialize(), function (data) {

           alert('Posted successfully and received data...'+data);


Call PostData function to post data on any element action i,e. click etc.

Sharepoint 2010 Dialogs

In Sharepoint, SP.UI script namespace provides required methods and classes for showing different types of dialogs.

The following are the list of various dialog methods available under class ModalDialog

1) showModalDialog: To show a modal dialog with some options.


2) ShowPopupDialog :

To show a modal dialog with an url and without any options.

3) showWaitScreenSize : this one is used to show a wait screen dialog with a close button


for more information on options visit

4) showWaitScreenWithNoClose:

To show a wait screen without any cancel button.


5) commonModalDialogOpen(url,options,callback,args)

To show a modal dialog with url, options, callback, parameters.

SP.UI.ModalDialog.commonModalDialogOpen(url, options, callback, parameters);

ModalDialog class provides other non dialog methods

1) RefreshPage:


2) close:
To close a dialog.

for showModalDialog and commonModalDialog, there are two ways to pass the options

//generic way

var options = { title: ‘Dialog1’ .height: 300 ,width:300
,url : ‘’

//with DialogOptions class

var options = SP.UI.$create_DialogOptions();
options.title = ‘Dialog1’;
options.height = 300;
options.url = ‘’;

You can also display html string instead of url but have to do in indirect way. Options html property takes a DOM element as an input. When html and url properties are provided, url takes precedence.

var div = document.createElement('div');
div.innerHTML = 'Dialog html demo Dialog html takes an DOM object but not an html string';
var options = {    title: 'Dialog1',
width : 300
,html = div

To refresh a page after dialog ok clicked.

Sharepoint 2010 Registering script files in a WebPart

Sharepoint 2010 provides a custom tag ScriptLink to register script files in a webpart. This can also be done using simple html script tag but using ScriptLink ensures all the sharepoint script namespaces are available for your custom script.

All the scripts that are to be registered should be placed in Layouts/ProjectName folder of your project. By default, when you create a project Layouts folder will not be added.

To add it, right click on your project –> add –> SharePoint “Layouts” Mapped Folder

A default folder with project name will be automatically created under Layouts folder.

Add your custom script files in Layouts/ProjectName/Scripts folder (create Scripts folder if not exist, it can be any name like JS etc.).

Add your code in the script file, here in this example I have added some alert code which is opened by clicking on web part button ‘click here’

Now add ScriptLink tag in your visual web part (i,e. .ascx control)
If you want to do the same in a standard web part, add the below code in OnPreRender method

ScriptLink.register(page,”RajWebPartsDemo/Scripts/RajDemoScript.js”, false);

Deploy your solution and add a your webpart in a page (say home page).

On clicking button ‘Click Here’ an alert is displayed.

Rendering Bing search with JSRender using API

JSRender is a jscript template engine very much similar to JQuery templates. It is replacing JQuery templates in the near future and still in beta. The main advantage of any template engine is to reduce the jscript code for rendering dhtml with some data. JSRender can be used with or without using JQuery.

Please visit below link to know more about JSRender


Here, in this example, I will try to explain how you can use Bing Search API to render a search interface with JSRender.

Bing Search API exposes http endpoints that can provide results in XML or JSON. Please visit below link for more information on Bing Search API


Bing API URL format



Bing Search API request consists of following required and optional parameters


1) AppID : Your site application key provided by Bing.

2) Query: Search text

3) Sources: Web or Images etc..


1) Web.Offset: Offset 0 means first page

2) Web.Count: Total number of records to be fetched.

>Please note that in order to hide my APPID and misuse, I have installed an application on my server to reverse proxy bing api. What I mean is in the example code there is no direct api calling to bing website but it has to go through my site.


All the api requests initiated to my site doesn’t require any APIID but Query and sources parameters are required.




Access source at

IIS ARR/URL Rewrite wish list

Its nice to have the following features in the next release of ARR/URL rewrite

1) Ability to include complete list of IIS Server Variables.

2) Ability to define a rule to or not to rewrite request headers based on a condition (either POST value or request header value)

What I noticed is ARR rewrites request headers but with rules we cannot modify certain request headers like HTTP_REFERER etc.

3) Ability to inject C# code for pre and post request, response. The only way possible to do this is to define a HTTP module(only response stream can be modified not request).

4) Ability to define a rule that rewrites request header based on response stream matched value (with regex). Its not possible to modify response header by searching a response stream value.