Sudhindra Kovalam's Blog

My Geeky Blog

Archive for the ‘Application Design’ Category

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!! )

5488.image_thumb_0D9FC62A

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!!)

4606.image_4D69ACAF

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"] = "http://schemas.microsoft.com/sharepoint/soap/Login";
      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=""http://www.w3.org/2001/XMLSchema-instance""
               xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
                xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
          <soap:Body>
            <Login xmlns=""http://schemas.microsoft.com/sharepoint/soap/"">
            <username>{0}</username>
            <password>{1}</password>
            </Login>
          </soap:Body>
          </soap:Envelope>";

      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);
      _body.Close();

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

      //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

Windows Phone 7 Design Considerations

with 4 comments

Windows Phone 7 is an amazing platform. It delivers what it promised. But the experience is not 100% complete. Now it’s up to us to complete the experience by developing some cool apps.

Now We all are aware that a Silverlight developer can easily develop apps for Windows Phone. Yeah, we still have all the Drag and Drop goodness, but we need to keep into consideration , when we are designing the application, that the target device is a phone with 1 GHz  single core processor , Most of us will develop apps on a Core 2 Duo machine.

Since, I have been playing around with Silverlight development experience, am not sure about whether these points are exactly applicable( as is) to XNA game development. But still, here it goes:

1. Keep the User Experience simple:

The Silverlight runtime on the phone does not exactly have a lot of raw processing power available, so it has been optimized accordingly. There are certain points that you need to take into consideration when designing UI for the phone.

– Keep it simple

Less Elaborate UI means Less Code means less activity which will lead to better performance

– Limit the activity on the UI thread

The UI thread must be limited to User interaction , accepting input etc.

– Leverage the Render thread

The render thread, is separate thread that will take care of simple animations etc. This will result in smoother User Experience ( Remember, customer experience comes first)

– Leverage the GPU of the phone

We have a dedicated GPU on the phone. Use it! And Since yours is the only program that runs in the foreground, you can design your app to leverage the GPU (and by that I meant justifiable usage , remember you are running on a small handheld device )

If you are interested in drilling down more, there was a nice session at MIX’10 on Silverlight performance on Windows Phone. Seema Ramchandani’s session on Silverlight performance on Windows Phone.

2. Make sure you only upload necessary data:

As you must be aware that on a small radio device, transmitting from the device can always prove to be more costly as compared to receiving transmission ( in terms of battery life). The Same principle applies here too.

Upload/ Send to server only the data you need to, Say for example, In your app, you receive an array if  say tasks, in which say you update some of these tasks, instead of sending the entire updated array to the server ( or your backend service) send across only some information, such as only the ID of the Task, property changed and the updated value.

This will result in overall better application performance as well as better battery life on the phone ( Very crucial IMO)

3. Deactivate Quickly

In WM 6.x, apps never had an exit option, There never was an event that would let us know that the app is about to get killed. So in order to overcome this danger, what people did was to save state of the application periodically.

Well in Windows Phone 7, You do have an App Closing and App Deactivating event. ( Not sure about what that means? , read my post on WP7 app life cycle). When you receive this event, you save data to the phone’s isolated storage/ or some backend service  and retrieve it back when the app activates again.

Now If your app is mammoth and needs to save a lot of data in the deactivating event, Your app will take time to tombstone. What this will lead to is a delay in the launched/chooser to show up making the phone run sluggish.

What we can do to overcome this is  to save state  periodically ( When people say OLD IS GOLD, they aren’t kidding, are they?)

We can do something on these lines:

    // Constructor
    public App()
    {
        UnhandledException += Application_UnhandledException;

        // Standard Silverlight initialization
        InitializeComponent();

        // Phone-specific initialization
        InitializePhoneApplication();

        // Add a Timer to save state Periodically
        DispatcherTimer dt = new DispatcherTimer();
        dt.Interval = new TimeSpan(0, 0, 0, 10); // 10 seconds
        dt.Tick += new EventHandler(dt_Tick);
    }

    void dt_Tick(object sender, EventArgs e)
    {
        //Dirty Flag is set, when something that has to saved 
        // in the application's state has changed.
        if (_dirtyFlag)
        {
            // Save state incrementally.
        }
    }

    // Code to execute when the application is deactivated (sent to background)
    // This code will not execute when the application is closing
    private void Application_Deactivated(object sender, 
        DeactivatedEventArgs e)
    {
        System.Diagnostics.
            Debug.WriteLine("Go to sleep...zzz");
        if (_dirtyFlag)
        {
            // Only save state if there is a change.
        }
    }


Well these are all the points i can think off as of now.

These may not be applicable to all apps that we will write on WP7 , But i believe it is “Good to Know / Things to ponder on, when designing my WP7 app” stuff.

Any suggestions/ comments/ thoughts/ abuses are welcome.

Written by sudheerkovalam

July 26, 2010 at 5:14 am