Sudhindra Kovalam's Blog

My Geeky Blog

My Experiences in Silverlight 4 : Writing re-usable Controls

with one comment

These days I am working on Silverlight and creating Custom controls which would be re-usable in another projects. And when you set out to write re-usable Silverlight controls, Silverlight toolkit is the best code to look up to.

When you download the Silverlight toolkit. The toolkit installer also copies source code of the toolkit at           “%Program Files%\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Source” folder. When you start exploring the source code, you will notice a peculiar way the source code for toolkit is arranged. Every control in toolkit is written as a content control and has a resource dictionary that has a default style.


So, inspired by this style of writing custom controls, I set out. Now the reason why you want write a custom control is you require certain custom fields and a custom style and behaviors. So when you define these controls and the style, you also want your custom properties to appear in your style(Or else why would you define those additional controls. Typically your style for your control would look something like this.


and the your custom control would look something like this.

<ResourceDictionary   xmlns=""

  <Style TargetType="my:CustomControl1">
    <Setter Property="Foreground" Value="#FF000000" />
    <Setter Property="BorderBrush" Value="#FFEAEAEA"/>
    <Setter Property="HorizontalAlignment" Value="Left" />
    <Setter Property="Template">
        <ControlTemplate TargetType="my:CustomControl1">
          <Grid x:Name="Root">
              	BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}" 
              	BorderBrush="{TemplateBinding BorderBrush}">
						<TextBlock Text={TemplateBinding MyCustomProperty1}

And your .cs file would look something like this. Notice that there is a peculiar way I chose to name the Dependency Property. You might want to follow this pattern (i.e. your DependencyProperty should be named your Variabale Name suffixed with “Property”.

You must adhere to this Naming convention if you intend to use Blend in your Project. (If your Dependency Property is named otherwise, You might not be able to Use Blend to set these template Bindings.)

  public class MyCustomControl1 : ContentControl

			public string MyCustomProperty1
            get { return (ExpandDirection)GetValue(MyCustomProperty1Property); }
            protected internal set
            { SetValue(MyCustomProperty1Property, value); }

        public static readonly DependencyProperty MyCustomProperty1Property=
                        new PropertyMetadata(ExpandDirection.Down, OnExpandDirectionPropertyChanged));


Now my control should show the value I set in MyCustomProperty1 on the UI right?. Something like this:

<Grid x:Name="LayourRoot">
	<my:CustomControl1  MyCustomProperty1="Hello Content Control"/>

But this does-not seem to happen. After searching for sometime on Silverlight .Net forums, I could not exactly find out what I was doing wrong here. After some Binging on Bing and Binging on Google Smile with tongue out . I found that for custom properties, TemplateBinding doesnot seem to work the way I expect it to work.

So instead as per the suggestions on the Silverlight .Net forums, I modified the template of the control by replacing TemplateBinding. Now My TextBlock Markup looks something like this.

<TextBlock Text={Binding RelativeSource={RelativeSource TemplatedParent},Path=MyCustomProperty1} />


Now My Template binding works as I expect it to work. Essential what has changed in the previous representation and the new representation is still a matter of research for me. Will Keep posting more about this as and when I discover more about it.

If I have made any mistakes, feel free to write Comments about what I am mistaken about. I’ll Happily Correct it 🙂


Written by sudheerkovalam

April 4, 2011 at 6:43 pm

Using Open XML SDK v2.0 on Windows Azure

with 2 comments

Hello folks,

Its been really long that I have written a post. And I have no excuses, Just couldn’t find the right time and the right topic to blog on Open-mouthed smile.

Generating Word/Excel reports is a fairly common requirement. Now that we intend to migrate our application to cloud, we realize that on Windows Azure, You do-not have  Office DLLs or infact, any other (unnecessary from Azure’s perspective) DLLs available to you. You can always package Office DLLs with your app deployment package and use them in you application on Windows Azure (You can find articles on the blogosphere about how this can be done).

I opted for using Open XML SDK v2.0. Using Open XML SDK for .NET available here . I Can generated Word / Excel reports on the fly.

Here’s a sample code to write to create a Word Document

//Using Statements Required 
using DocumentFormat.OpenXml;    
using DocumentFormat.OpenXml.Packaging;    
using DocumentFormat.OpenXml.Wordprocessing;      

//Code to Create a Word Document at the provided File Path    
using (WordprocessingDocument wordDocument =
    	WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
   			mainPart.Document = new Document(
   				new Body(
   					new Paragraph(
   						new Run(
   							new Text("Report Generated by Open XML SDK ")))));

ok. Now that we have everything in place, We’d want to deploy this “Report Generation Solution” to the cloud. But First , run it locally on the compute Emulator.

Everything seems to be working, Next step is to deploy your application to your azure account.

This blog post talks about a known issue on using Open XML SDK in  .NET 4 Roles on Windows Azure.

When you right click your solution to do a publish


Windows Azure would ask you for the Hosted service where you want to deploy the solution, If you have not already set that up, the dialog box also has a provision to do that for you.


Please Remember to UnCheck, (you read that right) “UNCHECK” Enable Intellitrace for .NET 4 roles.

You may want to argue that Intellitrace helps us in historical debugging in an event  of a fatal crash, but for now you will have to live with the Windows Azure Diagnostics Logging for now.

The reason, why this needs to be disable is, “Enabling Intellitrace for .NET 4 roles when using the OPEN XML SDK seems to freeze your web/worker role.”

I Learnt this the hard way (after being billed for a week for a  (Frozen, just because I Enabled Intellitrace and am using Open XML SDK in my azure app) Extra Large VM ). In other words, that’s a lot of money. Crying faceCrying faceCrying face 

Keep reading this space for such posts to come. I am working on Windows Azure now, So I am sure there are many such topics on which I can post. Smile. Thank You.

Written by sudheerkovalam

February 19, 2011 at 3:38 am

Community Techdays Mumbai

leave a comment »

I am travelling to Mumbai tomorrow. I would be speaking at community tech days there along with mayur tendulkar. My session is called

Developing Line of Business applications for Windows Phone

Hope to catch some of you folks there 🙂

For more details visit :

Those who are attending , Lemme assure you, You folks are in for a treat 🙂

See you there.

Also, if you are keen on learnign windows phone development, there is an ongoing screencast series (organised by Pune User Group) on windows phone 7 development. you can find more info at

Also stay tuned on this blog.

 Some really really cool articles are in the works 🙂

Written by sudheerkovalam

November 26, 2010 at 4:49 am

Posted in Windows Phone 7

Writing windows phone apps for SharePoint

with 6 comments

Writing a blog post after quite some time. (Well frankly was thinking on what sort of post to write)

We have heard / seen / read about how windows phone has good SharePoint 2010 integration features as to how the office hub can integrate with your corporate intranet SharePoint site and how, you can leverage the SharePoint workspace capabilities in windows phone.

after reading about this, you’d say cool, can i write an app which speaks to my SharePoint site. Well the answer is Yes. But there are some changes that you need to to do on SharePoint site configuration.

“Argh!!, making changes on SharePoint site, My boss(and/or system admin) will kill me! “.

Was this your reaction ? (at least, that was my initial reaction).

In that case, this post might not be of that much help.

However, we can always host a cloud service that would help you get data from SharePoint and you can consume the data from this “middle man” cloud service. ( Off course this does add up expenses that at the end of the day needs to be taken care off by some one)

So, why is that I cannot consume SharePoint service directly from my windows phone.

Well it all began, when windows phone SDK team decided to omit NTLM auth support from the SDK, thus preventing us 3rd party developers from directly writing cool apps that speak to your SharePoint site.

“Why did they do this to us? “ you ask!!, Well frankly, i don’t have an answer to that.

But, There is a way out of this. How is that? Well , all you got to do is enable Forms based authentication for your SharePoint site.

How do I do that? There is a good article here. (Remember, you need to be very very strong hearted to take up all these changes, as these changes might literally take down your SharePoint site. )

Here’s a pictorial representation of auth mechanisms and SharePoint support for the same.

(Stolen from Paul Stubbs blog on MSDN, Sorry!! )


Well what story, the above diagram is trying to tell is:

SharePoint 2010 supports two different authentication modes.

1. Classic mode (The Loner left side branch, support NTLM authentication only)

2. Claims based mode (The right side branch of the diagram above)

What you can realise is that if you use the claims based mode for creating your SharePoint web application, you can use any of the claims providers to authenticate yourself (in this case, your phone app’s code) to your SharePoint site. (Off course, your system administrator can have hard time configuring the same, but lets not get into that Open-mouthed smile)

Once you have the infrastructure in place. All you got to do is use the SharePoint 2010 Web services to access SharePoint lists etc.

In SharePoint, you cannot make any changes to a spsite until you are an authenticated user. So You need to log in programmatically to make changes such as adding list items, modifying ‘em etc.

For Logging in , you can use the authentication.asmx web service to authenticate yourself.

(the spsite you are trying to access via your code needs to allow form based authentication.) The Authentication site is available at : http://[YourSiteName]/_vti_bin/authentication.asmx

Logging into SharePoint

Here’s what happens when you visit a SharePoint site: (Again stolen for Paul stubbs’ blog , sorry again!!)


1. you visit a SharePoint site page.

2. you are redirected to the login page(this internally uses the authentication web service), you enter your credentials here.

3. the authentication service returns a security token(FEDAUTH).

4. this security token is passed for all subsequent calls to the SharePoint site.

5. this security token is verified by the server for validity and then the server returns the requested resource.

How Do I do this Programatically?

Well, for programmatically mimicking the above mentioned behaviour, you can write  code that looks something like this:

CookieContainer cookieJar = new CookieContainer();
    private void Authenticate()
      System.Uri authServiceUri = new Uri("http://[YourSPSite]/_vti_bin/authentication.asmx");

      HttpWebRequest spAuthReq = HttpWebRequest.Create(authServiceUri) as HttpWebRequest;
      spAuthReq.CookieContainer = cookieJar;
      spAuthReq.Headers["SOAPAction"] = "";
      spAuthReq.ContentType = "text/xml; charset=utf-8";
      //spAuthReq.Accept = "text/xml";
      spAuthReq.Method = "POST";

      //add the soap message to the request
      spAuthReq.BeginGetRequestStream(new AsyncCallback(spAuthReqCallBack), spAuthReq);

    private void spAuthReqCallBack(IAsyncResult asyncResult)
      string envelope =
          @"<?xml version=""1.0"" encoding=""utf-8""?>
          <soap:Envelope xmlns:xsi=""""
            <Login xmlns="""">

      UTF8Encoding encoding = new UTF8Encoding();
      HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
      Stream _body = request.EndGetRequestStream(asyncResult);
      envelope = string.Format(envelope, "userName", "password");
      byte[] formBytes = encoding.GetBytes(envelope);

      _body.Write(formBytes, 0, formBytes.Length);

      request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);

    private void ResponseCallback(IAsyncResult asyncResult)
      HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
      HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
      Stream content = response.GetResponseStream();

      if (request != null && response != null)
        if (response.StatusCode == HttpStatusCode.OK)
          using (StreamReader reader = new StreamReader(content))
            //Put debugging code here
            string _responseString = reader.ReadToEnd();

      //authentication complete
      //Use the Cookie Container for all subsequent calls


Now that you have the FEDAUTH token in the CookieContainer instance, you can pass it around to access other list services.

System.Uri listServiceUri = new Uri("http://[YourSpSite]/_vti_bin/lists.asmx");
HttpWebRequest spAuthReq = HttpWebRequest.Create(listServiceUri) as HttpWebRequest;
spAuthReq.CookieContainer = cookieJar;


Will try and post up a complete working sample of the same very very soon! Till then keep checking this space for more updates Smile

Written by sudheerkovalam

November 4, 2010 at 3:03 pm

Posted in Application Design, Windows Phone 7

Tagged with

two minutes to PDC10

leave a comment »

Here we are at microsoft mumbai office waiting for PDC 10 Keynote to begin.

SteveB is expected to make some major announcements.  (lets hope its free  windowsphone 7 for everyone in india 😉 )

SteveB is pumped up as he claims . But no Developer Prance ??  😦

lets hope my dream comes true. will keep tweeting about it

Written by sudheerkovalam

October 28, 2010 at 4:03 pm

Posted in Uncategorized

A Windows Phone Twitter Application : Part 2 of 2

with 33 comments

(Update : For trying out code posted on this blog post, Kindly use the official/ locked emulator . The unlocked emulator images have a known issue with HTTPS )

This is the second post in the series of posts explaining how you can build your own twitter application on Windows Phone 7

Post(s) in this series:

Part 1: Understanding oAuth

As explained in part one, the hard part of writing a twitter application is, to figure out/ understand the authentication/ authorization mechanism. Once You have done that, you can pretty much write an app for any service that has oauth as its authentication/authorization mechanism.

Now that we have obtained all the necessary authorization token(s), we can now access the protected resources on the user’s behalf.

How to Post a Tweet on a User’s behalf?

Using the access token and our app’s consumer secret , we need to make a POST request to twitter’s API to post a tweet from our app.

Using Hammock’s REST Library, You would do something like this :

if (txtBoxNewTweet.Text.Trim().Length == 0) { return; }
var credentials = new OAuthCredentials
      Type = OAuthType.ProtectedResource,
       SignatureMethod = OAuthSignatureMethod.HmacSha1,
       ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
       ConsumerKey = TwitterSettings.consumerKey,
       ConsumerSecret = TwitterSettings.consumerKeySecret,
       Token = this.accessToken,
       TokenSecret = this.accessTokenSecret,
       Version = "1.0"

var restClient = new RestClient
        Authority = TwitterSettings.StatusUpdateUrl,
        HasElevatedPermissions = true,
        Credentials = credentials,
        Method = WebMethod.Post

restClient.AddHeader("Content-Type", "application/x-www-form-urlencoded");

// Create a Rest Request and fire it
var restRequest = new RestRequest
       Path = "1/statuses/update.xml?status=" + txtBoxNewTweet.Text

var ByteData = Encoding.UTF8.GetBytes(txtBoxNewTweet.Text);
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));

Now that you are able to make posts, you need a way to see the posts you have made on the user’s twitter account!

Well For looking at status updates, you don’t need authorization. You can directly give a call to the twitter api and you will get your status updates. ( This sample code is as demonstrated on Scott Gu’s blog )

 private void GetUserTimeLine()
            WebClient wcTwitterTimeline = new WebClient();
            wcTwitterTimeline.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wcTwitterTimeline_DownloadStringCompleted);
            wcTwitterTimeline.DownloadStringAsync(new System.Uri("" + userScreenName));

        void wcTwitterTimeline_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
            if (e.Error != null)
            { return; }
            XElement Tweets = XElement.Parse(e.Result);
            listboxMyTimeline.ItemsSource = from tweet in Tweets.Descendants("status")
                                            select new TwitterItem
                                                UserName = tweet.Element("user").Element("screen_name").Value,
                                                Tweet = tweet.Element("text").Value,
                                                ImageSource = tweet.Element("user").Element("profile_image_url").Value
            Dispatcher.BeginInvoke(() =>
                listboxMyTimeline.Visibility = Visibility.Visible;
                txtBoxNewTweet.Visibility = Visibility.Visible;
                btnPostTweet.Visibility = Visibility.Visible;

With this, you are pretty much able to make a basic twitter app, that allows you to post tweets.

Using the Twitter api (Found here) You can create a full fledged twitter app.

As promised, I am uploading the source code for the app. You can download the source here.

(UPDATE : I have updated the code snippet, so that the app now runs on the public beta of the tools , Thanks Don for pointing this out )

Once again, Thanks for your support. With the final SDK Bits coming out this September 16th and with WP7 hitting the RTM status (Congratulations to the Windows Phone team @MSFT, Will be  queuing up the store when, it hits retail Smile), The next couple of weeks seem to be really really interesting.  Stay tuned for more exciting WP7 stuff

Written by sudheerkovalam

September 5, 2010 at 2:12 pm

A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding oAuth)

with 59 comments

(Update : For trying out code posted on this blog post, Kindly use the official/ locked emulator . The unlocked emulator images have a known issue with HTTPS )

As Promised in the previous post(I Know it was very long ago), We will try to build a Twitter application. Building a twitter app is a very easy task, and this post intends to guide you Step by step in creating your first twitter application. This post will speak about getting the app authenticated/authorized using the oAuth Mechanism.
The target platform is Windows Phone 7  in  this post, but you can pretty much a build a twitter app on any other platform based on this tutorial
Step 1: Register Your Twitter app on
Twitter needs to know that You are writing an app which accesses/posts tweets on your behalf. You tell this to twitter by registering your app on twitter.
When Registering your app, ensure that You set the Application type to browser and specify a call-back URL. (Twitter has certain requirements on Call-back URLs, i.e. it will not accept non HTTP URLs ( You need to ask twitter specially for  that ). For Demo purposes, i have specified as my default call-back URL.You can specify your custom page hosted on your domain, if you want to
This is how your app settings on twitter would look like:
Make a note of the highlighted URLs and your consumer key and secret.( Wondering what these are? Continue Reading or Read about oauth here)
Now comes the fun part, As usual fire up Visual studio 2010. Do a File | New Project. Select a Windows Phone Application from Silverlight for Windows Phone Section.
Twitter exposes a RESTful Service to access a user’s tweets etc. Twitter as of now only allows oAuth and XAuth as the only authorization mechanism. Since we have to have to consume a REST service along with oAuth, we will be  using a REST Client helper, that abstracts a lot of the hard work for me. (Such as adding the necessary headers, Computing oAuth Parameters such as Signature, Nonce, Timestamp etc. etc.)
For this demo, we’d be using the Hammock REST client available for download here. (Ohh BTW, Hammock is a very good example as to how same source code can target multiple platforms and multiple .net versions. Curious , about knowing how ? Go straight to the site and download the source code and have a look for yourselves.)
Now Lets get our hands dirty with some code for our first Twitter Application on Windows Phone 7 Smile
First Using the consumer Key and consumer key secret that you got by registering your application on twitter’s site, you need to request for a request token and request token secret
Request Token and request token secret are temporary set of credentials that let you acquire oauth access Tokens. The access token and access token secret are needed to access a user’s tweets.
To do this, I will use some neatly written helper classes in the Hammock library.( Else I would be actually writing code to do a lot of ugly stuff)

 var oauth = new OAuthWorkflow
     ConsumerKey = TwitterSettings.consumerKey,
     ConsumerSecret = TwitterSettings.consumerKeySecret,
     SignatureMethod = OAuthSignatureMethod.HmacSha1,
     ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
     RequestTokenUrl = TwitterSettings.RequestTokenUri,
     Version = TwitterSettings.oAuthVersion,
     CallbackUrl = TwitterSettings.CallbackUri

var info = oauth.BuildRequestTokenInfo(WebMethod.Get);
var objOAuthWebQuery = new OAuthWebQuery(info);
objOAuthWebQuery.HasElevatedPermissions = true;
objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";
objOAuthWebQuery.SilverlightMethodHeader = "GET";

What this helper class does is, hide a lot of stuff from the end user that needs to be done to acquire the request token and secret. Using the oauth WebQuery object all i have to do is to instantiate  a Hammock Rest Client object to fire a request to twitter’s servers.

 var requestTokenQuery = oAuthHelper.GetRequestTokenQuery();
 requestTokenQuery.RequestAsync(TwitterSettings.RequestTokenUri, null);
 requestTokenQuery.QueryResponse += new EventHandler(requestTokenQuery_QueryResponse);
In the response received event, I parse the response sent across by twitter. This should have the request token and request token secret in the response body.
var parameters = HelperMethods.GetQueryParameters(e.Response);
OAuthTokenKey = parameters["oauth_token"];
tokenSecret = parameters["oauth_token_secret"];
var authorizeUrl = TwitterSettings.AuthorizeUri+ "?oauth_token=" + OAuthTokenKey;

Now using the request token and secret, we need to get our app authorized to read/write data from the end user’s twitter account. To do this, we need to open a web browser and redirect the end user to twitter’s sign-in/ authorize page. To do this, I will be using a Web browser control and redirecting it to the authorize URL I have created above.

Dispatcher.BeginInvoke(() =>
      this.objAuthorizeBrowserControl.Navigate(new Uri(authorizeUrl));
The XAML for the browser control would look something like this:

The User sees the twitter page, where s/he signs in to twitter. Here, s/he is asked to authorize our twitter app.
After you have authorized the application to access your data on your behalf, twitter will send the oauth request token (you received in the previous step) and a verification pin. Using these tokens, you can now request for the access token and access token secret. ( Arrgh!!! another set of tokens….)
Using the Hammock helper class that we used to get request tokens, we can acquire Access tokens as follows:
 var AuthorizeResult = HelperMethods.GetQueryParameters(e.Uri.ToString());
var VerifyPin = AuthorizeResult["oauth_verifier"];
this.objAuthorizeBrowserControl.Visibility = Visibility.Collapsed;

//We now have the Verification pin
//Using the request token and verification pin to request for Access tokens

var AccessTokenQuery = oAuthHelper.GetAccessTokenQuery(
                                             OAuthTokenKey,     //The request Token
                                             tokenSecret,       //The request Token Secret
                                             VerifyPin         // Verification Pin

AccessTokenQuery.QueryResponse += new EventHandler(AccessTokenQuery_QueryResponse);
AccessTokenQuery.RequestAsync(TwitterSettings.AccessTokenUri, null);
In response twitter sends us the access tokens, the userID and the user’s screen name. I am going to store ‘em all, (Can prove to be very handy.)
var parameters = HelperMethods.GetQueryParameters(e.Response);
 accessToken = parameters["oauth_token"];
accessTokenSecret = parameters["oauth_token_secret"];
userID = parameters["user_id"];
userScreenName = parameters["screen_name"];

HelperMethods.SetKeyValue("AccessToken", accessToken);
HelperMethods.SetKeyValue("AccessTokenSecret", accessTokenSecret);
Dispatcher.BeginInvoke(() =>
    MenuItemSignIn.IsEnabled = false;
    MenuItemSignOut.IsEnabled = true;
    TweetButton.IsEnabled = true;
Phew!!! Now we are authenticated. We can now use the tokens we have received till now and the app can now access the user’s data(such as tweets, timeline etc.)

Written by sudheerkovalam

August 28, 2010 at 7:58 am