header bg
 

Sl.ayer's layer

It looks like you're writing a blog...

Silverlight Color Picker is now on CodePlex

by admin 9. June 2011 06:52

Upon receiving numerous requests (or three, to be precise) for source code for my color picker control (see http://youpvp.com/blog/post/Color-picker-control-for-Silverlight.aspx), I’ve decided it’s time to  try one of those open source repositories, and have created a fresh new project on the CodePlex: http://colorpickr.codeplex.com. Currently it is just source code, but I’m going to create a NuGet package and link it from the projects home page.

Facebook announces its first official .Net SDK

by admin 17. July 2010 00:35

For quite some time now, .NET developers have been left out in the cold without official support from Facebook. No more, my friends! Today, Andrey Goder announced the first release of Facebook’s official C# SDK in his blog post. For many of us, this raises the following questions: what does it mean for all the unofficial .Net SDKs floating around? Do I keep using my own Facebook library or should I switch to the official SDK?

The decisive factor in answering this question for all Silverlight developers is, of course, Silverlight support. Based on the first look, the official SDK is not Silverlight ready, although it should be easy enough to add support for an asynchronous communication model.

Also, Facebook SDK is quite similar to GraphLight, in that neither provides any help with Facebook authentication. All in all, the alpha state of the first official .Net SDK is pretty obvious. For now, I will stick with my own GraphLight, but I will keep an eye on the Facebook SDK to see how its Silverlight support progresses.

Protecting your Silverlight application from a hijacking

by admin 14. July 2010 06:15

First, let me clarify what I mean by “application hijacking.” The traditional definition of hijacking is the following:  “To seize control of a vehicle by use of force, especially in order to reach an alternate destination.” By modifying the definition to make it appropriate for web applications we get the following:  Copying or embedding an application in a way that is not intended or permitted by the owner, with the goal of attracting users to the hijacker’s website. This issue is not new, nor is it exclusive to applications. Sites have being battling “deep linking,” copying of images, and other copyrighted materials for a long time now. Fortunately, a Silverlight application can be hardened to resist hijacking in a way that image or other passive content cannot.

Below, I review different forms of application hijacking and explain how to detect them.

Xap hijacking

This most brazen form of application hijacking is done by downloading an application file (.xap) and placing it on the hijacker’s server. Guarding from this type of hijacking is important because it cannot be detected by analyzing web server logs.

Luckily, detecting xap hijacking is pretty easy. Simply compare the location reported by  App.Current.Host.Source to your own. If the location is not the one you expect then, your application has been hijacked. Comparing domains should be sufficient for most cases.

if (App.Current.Host.Source.Host != "mydomain.com")
    //sound the alarm!

Application “deep linking”

This happens when an application is embedded into the page of an unauthorized website (using <object> tag or silverlight.js) while pointing to the original xap file. This is probably the most common form of unauthorized embedding. It requires very little effort on the part of the hijacker, and leaves the owner with the bill for consumed bandwidth.

To detect if an application is deep-linked, check HtmlPage.Document.DocumentUri to see if the hosting page is located on the authorized domain. Watch out for InvalidOperationException! If you get it while trying to access HtmlPage’s properties, that means that the host webpage and your application are being served from different domains. See Security Settings in HTML Bridge for explanation. If you want to perform a deep-linking check on your own application hosted from a different domain (for example CDN), then you need to add the enableHtmlAccess parameter to your <object> tag.

While working on sample application, I noticed that xap files hosted on dropbox.com appear to be immune to deep-linking. I am not 100% sure why, but my current theory is that it is due to Content-Type set to “application/octet-stream.” You can also use more traditional techniques to fight deep linking, such as checking http referrer.

Iframe embedding

This situation is not specific to Silverlight apps, but to web pages in general. The solution to fight iframe embedding is often called “frame busting.” To bust out of iframe, all you need to do is to put the following javascript code in you page:

<script type="text/javascript">
  if(top.location != location)
  {
     top.location.href = document.location.href;
  }
</script>

Deterrents

If you detect that your application is hijacked, you have a few choices:

  • Disable application without any explanation to the user
  • Show user a message with hyperlink button offering to go to the application’s original site
  • Keep working as if nothing happened, but send information about the hijacker’s website to your own web service (think of it as a Lojack for your app).

Whatever measure you choose, be considerate to your users. They are not the ones responsible for your application hijacking.

Conclusion

All this work wouldn’t be worth much if a hijacker can disassemble your application, and easily locate and neutralize your countermeasures. That is why I would recommend to always obfuscate your application if you are going to place anti-hijacking code in it.

It is worth remembering that embedding is not always bad; in fact some websites rely on embedding in their business model and actively encourage it. If your application is a popular target for embedding, you may want to consider making use of it rather then trying to fight it.

Implementing Facebook authentication in a Silverlight out-of-browser application

by admin 10. July 2010 22:29

In my previous post about the GraphLight library, I mentioned that the first step in using the library is to supply it with an access token. What I conveniently skimmed over is the explanation of what an access token is and how does one get a hold of it.  I did this because answering those questions isn’t simple, and would benefit from dedicated elaboration.

According to Facebook: “An access token allows an application to perform authorized requests on behalf of the user by including the access token in Graph API requests.” You can read about the process of obtaining an access token on the Facebook Developers Site. Although Facebook documentation provides a good starting point, it does not account for peculiarities of Silverlight. In this post, I will go over issues I encountered while implementing Facebook authentication in a Silverlight OOB application, and offer my solutions.

Facebook documentation outlines two main flows of authentication available to applications:  The first method utilizes sequence of redirects to Facebook site and back; the second method uses single sign-on with the JavaScript SDK. Of the two, only the former method can be used in a Silverlight OOB application due to restrictions on access to the hosting page’s DOM. Upon closer examination, the Desktop Application Authentication process emerges as the most obvious choice for an OOB application.

Implementing a desktop authentication flow in accordance with Facebook documentation is quite straightforward:

  1. Create WebBrowser control in code or in XAML
  2. Navigate to https://graph.facebook.com/oauth/authorize
  3. Intercept the redirect to login_succes.html using LoadCompleted event and read the access token out of the URL

Problem #1

WebBrowser control needs Full-Trust to show pages from sites other then application’s origin. Because the Facebook authentication process requires redirect to facebook.com, the OOB application must be in full-trust mode! After many different attempts to find an acceptable workaround for standard OOB applications, I came to the conclusion that although it can be done, the resulting user experience is so poor that it is simply not worth it.

Resolution: Configure application to require Full-Trust.

Problem #2

Using the LoadCompleted event to intercept the redirect to login_succes.html doesn’t work because the Uri property of NavigationEventArgs is always null. If one is unable to read the access token out of the URL, using the Desktop Application Authentication process is no longer an option.

Resolution: An alternative approach comes in the form of an authentication flow recommended for Web Applications and Mobile Applications. Web application authentication uses a two-step process, with the first step similar to that of desktop authentication, but instead of an access token, it returns code that can be exchanged for an access token in a separate step.

In order to detect redirects and pass code to the Silverlight application, following steps need to be taken:

1. Create success.html page

<html>
  <head>
   <title>Facebook Login Callback</title>
   <script type="text/javascript">
      window.external.notify(window.location.href);
   </script>
  </head>
  <body />
</html>

2. Success page should be hosted on the same domain as the application and its url should start with Connect URL (see Facebook connect settings). Both conditions are sine quibus non.

3. Point redirect_uri parameter to the location of the success page

4. Add ScriptNotify handler to WebBrowser control:

  browser.ScriptNotify += (a, b) =>
  {
     int n = b.Value.IndexOf("?code=");
     if (n > 0)
     {
         //extract code from b.Value
         //exchange code for access token as described in Facebook documentation
         WebClient wc = new WebClient();
         wc.DownloadStringAsync(new Uri(
              string.Format(token_xchange, app_id, redirect_url, secret, code)));
         wc.DownloadStringCompleted += (c, d) =>
         {
             //extract access token from d.Result
             LoginSuccess(access_token);
         };
     }
     else
     {
         if (b.Value.IndexOf("user_denied") > 0)
         {
             LoginFailed();
         }
     }
  };

At last a bit of good news: The method described above actually works, but…

Problem #3

Doing a token exchange from a Silverlight application requires a secret key to be stored inside of the package redistributed to the end users, which is inherently not secure.

Resolution: Replace success.html with success.aspx or success.php or any other technology that allows one to execute code server-side. Perform token exchange on the server and simply pass the access token to ScriptNotify handler.

In an attempt to find a simpler solution, I found a post on the Facebook developers forums showing a way to get an access token in one step, without going through a token exchange. Unfortunately, that method relies on undocumented features and looks kind of “hacky,” so I am not going to present it here.

Postmortem

Implementing Facebook authentication in an OOB silverlight application turned out to be a challenge. Most of the issues I encountered were related to limitations of the WebBrowser control. Some security restrictions were expected and quite reasonable, while others appear to be to overreaching. It would be nice to see Microsoft considering use cases for Silverlight applications needing to login to OAuth based services (Facebook, Twitter, Flicker…).

Bonus feature: Logout or “What goes up must come down“

After all the trouble with authentication, it would be nice if logging out was simple… and it mostly is. Presently the only way to properly log a user out of Facebook is by redirecting the user to logout.php with app id and session as parameters. One little problem is how do we get a hold of the session? Well, as it happens, session is part of the access token and can be extracted from it with little effort.

private string logout_format = 
    "http://www.facebook.com/logout.php?app_key={0}&session_key={1}&next={2}";

public void Logout(string access_token)
{
    access_token = HttpUtility.UrlDecode(access_token);
    int s = access_token.IndexOf("|");
    int e = access_token.LastIndexOf("|");
    string session = access_token.Substring(s + 1, e - s - 1);
    browser.Navigate(new Uri(string.Format(logout_format, app_id,
        session, HttpUtility.UrlEncode(OAuthUrl))));
}

GraphLight - Lightweight Facebook library for Silverlight.

by admin 2. July 2010 17:12

If you are developing applications for Facebook, then you know that the old Facebook REST API has been replaced with the new Graph API. To make sure that my Facebook applications keep working, and considering the uncertain future of the Facebook Developer Toolkit, I decided to write my own Graph SDK - GraphLight.

In designing GraphLight, my major goals were to make it small and simple to use, and to be compatible with the asynchronous programming model supported by Silverlight. After some experimentation, I decided to use Reactive Extensions Library to make the most of the asynchronous nature of Silverlight.

GraphLight is very easy to use, as I will demonstrate with the following samples:

First, let’s initialize GraphLigh by providing it with a valid access_token and then get information about the current user:

    Profile Me;
    public MainPage_Loaded()
    {
        GraphApi.access_token = access_token;
        GraphApi.Me.Subscribe(OnMe);
    }
    private void OnMe(Profile profile)
    {
        me = profile;
        name.Text = me.name;
        about.Text = me.about;
        pic.Source = new BitmapImage(new Uri(me.Picture));
    }

Next, let’s get the list of friends:

    Me.Friends.Subscribe(
        freinds =>
        {
            foreach (Profile friend in friends)
                // do something application specific
        }
    );

Uploading a photograph is also quite easy:

    album.Upload(“Me wrestling with polar bear”, photoStream)
         .Subscribe(pid => status.Text = "Upload succesful pid=" + pid);

You can use reactive extensions to simplify complex asynchronous scenarios. For example, you can use ForkJoin to wait for all asynchronous downloads to finish, and then call the subscriber with the results:

    List<Photo> allPhotos = new List<Photo>();
    albums.Where(a => a.name != "Profile")
          .Select(b => b.Photos)
          .ForkJoin().Subscribe(
               v =>
               {
                   foreach (var photos in v)
                   {
                       allPhotos.AddRange(photos);
                   }
               }
          );

Fair warning:  GrahLight is not a fully supported, take-care-of-it-all library. If you like to tinker with your code and modify your library to meet your needs, then GraphLight could be for you. I would also recommend looking at similar libraries on CodePlex, for example Facebook Graph Toolkit.

Silverlight, meet Shell.Application

by admin 1. January 2010 03:09

Silverlight 4 is coming, and with it a controversial ability to call local automation objects. In this post, I will review some of the standard automation objects that can be used from Silverlight 4.

Shell.Application

Shell Automation enables access to features of Windows shell. This includes displaying standard dialogs, arranging windows, starting applications, starting and stopping services, and more.

Probably the most useful function of Shell.Application is ShellExecute. Using ShellExecute, it’s possible to run executable or open or print a document.

dynamic shell = AutomationFactory.CreateObject("Shell.Application");
shell.ShellExecute("notepad.exe", "", "", "open", 1);

More...

Comic Composer for Facebook

by admin 9. November 2009 18:54

If you visited my projects page then you know about silverlight comic builder I am working on. Comic Composer for Facebook is the latest development bringing user created comics strips to Facebook platform. I am currently looking for beta testers to help me to prepare application for general release. Please, leave your comments and suggestions in this post.

  • Comic Composer for Facebook
  • Facebook Toolkit
  • Image tools

  • LuaParse. C# parser for World of Warcraft saved variable files

    by Admin 30. August 2009 04:43

    It is a common task for developers creating add-ons for World of Warcraft to process wow lua files on the server side. YouPVP, for example, receives lua files generated by an add-on and parses battlegrounds data into the database. Since I was building a website on an asp.net platform, I needed lua parser in C#. Unfortunately, after spending some time on the internet, I couldn’t find any .net solutions that would work for me, so I wrote my own. If you need to parse warcraft lua files in a .net environment, I hope you will find my LuaParse class to be useful.

    Dynamic resizing of ActiveX controls hosted by ATL Composite Control

    by Admin 19. August 2009 00:10

    Introduction

    Did you cheer when you found out that ATL 3.0 would support ActiveX control hosting? I did. This functionality was at the top of my wish list for ATL. ATL 3.0 has finally arrived. What now? In one news group, I saw the following question: "How do I resize ActiveX controls hosted by Composite Control?” The answer to this question is very simple, but the reasoning behind it is not. Therefore, I decided to write this article to share my knowledge of the inner workings of ATL’s hosting of ActiveX controls.

    How does ATL implement the hosting of ActiveX controls

    If you will look in ATL code, you will notice that code for CComCompositeControl takes less then two hundred lines. How is it possible to fit all hosting support into two hundred lines of code? Well, the answer is quite simple--CComCompositeControl does not have support for ActiveX hosting. The real hero behind the scenes is CAxHostWindow.

    CAxHostWindow implements necessary interfaces in order to support the hosting of common ActiveX controls (including windowless) and Microsoft Web Browser control. In case you do not need to host a Web Browser control, you can define _ATL_NO_DOCHOSTUIHANDLER in your project and save about 4K in release dll. CAxHostWindow derives from CWindowImpl, and this means it needs a window to operate. CAxHostWindow can host only one control at a time, and as a result, one CAxHostWindow is required for each hosted control. Without going into all the aspects of implementation (look into atlhost.h for more details), I would like to concentrate here on the way CAxHostWindow handles WM_SIZE and WM_PAINT.

    More...

    How to extend CAxHostWindow to support new functionality

    by Admin 18. August 2009 23:36

    There are two major methods that you can use to support control containment in your control using ATL 3.0. One method is to use the support provided by ATL, namely CAxHostWindow. The other method is to write everything from scratch. By far, using ATL is easier then writing tons of code yourself, but what if CAxHostWindow doesn’t support the functionality that you need? Is following the second method your only option? Most likely, the answer is no. In most cases, the result can be achieved just by extending the functionality of CAxHostWindow, which I will be discussing as the main topic in this article.

    The most obvious way to extend the functionality of CAxHostWindow is to modify its code in atlhost.h, but it should be done with care because changes you make will reflect on every user of CAxHostWindow, such as Composite Control. An alternative solution is to derive a new class from CAxHostWindow and override its methods and message handlers. Below, I will demonstrate in more detail how to modify CAxHostWindow to support new functionality.

    More...
    header bg