Archive for category Asp.net

IIS 7.x and HttpResponse.Headers

Today I was debugging some application I wrote that was written with an application pool’s mode set to Integrated mode in mind. One of my colleagues told me I needed to test it running in an application pool with its mode set to Classic.

And guess what? Boom… it blew up in my face! After cursing around a bit I discovered in my log files the following message:

ERROR An Exception was thrown:System.PlatformNotSupportedException: This operation requires IIS integrated pipeline mode.
at System.Web.HttpResponse.get_Headers()

The defect piece of code was this:

HttpContext.Current.Response.Headers.Add("Some-Header","Some-Value");

Apparently to do that you need the IIS integrated pipeline mode. Well if you really need to run your app pool in Classic mode just replace your code with the following and all is well:

HttpContext.Current.Response.AppendHeader("Some-Header","Some-Value");

I know it’s kind of silly from Microsoft to not make this both ways compatible.

, , ,

2 Comments

Connect to Facebook using ASP.NET, Facebook Graph API & Hammock

UPDATE: Hammock moved to github https://github.com/danielcrenna/hammock

A while ago I wrote a post on how to perform oAuth authentication against the LinkedIn API using Hammock. Today I want to show you how to use Hammock with the Facebook Graph API. The Graph API is a new way a developer can read and write data to Facebook. Facebook uses oAuth 2.0 which is a simpler version of the oAuth authentication I used in my previous article with LinkedIn. It uses SSL instead of relying on the URL signature schemes and token exchanges you see in oAuth 1.x

There are 3 steps:

  1. Redirect the visitor to the authorization page over at Facebook.com
  2. Handle the callback from Facebook.com
  3. Get an access_token from Facebook.com using the code parameter returned by Facebook.com in step 2

For more information about the exact details on authorization in the Graph API go to: http://developers.facebook.com/docs/api

So let’s begin. I created a Web application in Visual Studio .Net 2010 that looks like this:

As you can see there is not much on the page except for a button, an empty image and some text with “Unknown” values. The goal is that when your visitor clicks the “Connect to Facebook” button he/she gets redirect to Facebook.com to authorize your application and then you can get the profile picture, name and the visitor’s about text he/she filled in on Facebook.

When the visitor clicks the “Connect to Facebook” the following code is executed:


   protected void Button1_Click(object sender, EventArgs e)
   {
            string callbackUrl = "http://localhost/FacebookConnectWithHammock/";
            //Request offline access and publish to the users stream access.
            Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope=offline_access,publish_stream", ConfigurationManager.AppSettings["FacebookClientId"], callbackUrl));
   }

What this does is it will redirect the visitor to facebook to the authorization page. This specific authorization request asks foor “offline_access” and “publish_stream” rights. This means that the application can access your Facebook account while you are offline and it can also publish updates to your Facebook account. Other parameters are the “client_id” which you need to set to your application’s client id that was assigned to your application when you created it and the “redirect_uri” which tells Facebook where to redirect the visitor after he/she granted your application access. When this is the first time the visitor is authorizing your application he/she will see the following authorization page:

When the visitors clicks on the “Allow” button Facebook will redirect the visitor back to the “redirect_uri” parameter. Then arriving on the web server we will receive a code parameter that we need to use to get the access_token. Here is how the callback code looks:

First in the Page_Load we check if the current request is a callback from Facebook by verifying if the Request["code"] querystring parameter is not null or empty and when it is not we call the callback handling code:


 protected void Page_Load(object sender, EventArgs e)
 {
     if (!string.IsNullOrEmpty(Request["code"]) && !Page.IsPostBack)
     {
          HandleFacebookCallback();
     }
 }

The HandleFacebookCallback method will use the “code” parameter to get an access token and then call the DisplayUserInformation method passing the received token. The DisplayUserInformation will make a request to the Graph API requesting information about the visitor that just authorized the application. It will show the profile picture, name of the visitor and the about text that is filled in on his/hers Facebook profile.


        private void HandleFacebookCallback()
        {
            string CallbackUrl = "http://localhost/FacebookConnectWithHammock/";
            var client = new RestClient { Authority = "https://graph.facebook.com/oauth/" };
            var request = new RestRequest { Path = "access_token" };

            request.AddParameter("client_id", ConfigurationManager.AppSettings["FacebookClientId"]);
            request.AddParameter("redirect_uri", CallbackUrl);
            request.AddParameter("client_secret", ConfigurationManager.AppSettings["FacebookApplicationSecret"]);
            request.AddParameter("code", Request["code"]);

            RestResponse response = client.Request(request);
            // A little helper to parse the querystrings.
            StringDictionary result = ParseQueryString(response.Content);
            string aToken = result["access_token"];

            DisplayUserInformation(aToken);
        }

        private void DisplayUserInformation(string sToken)
        {
            var client = new RestClient { Authority = "https://graph.facebook.com/" };
            var request = new RestRequest { Path = "me" };
            request.AddParameter("access_token", sToken);
            RestResponse response = client.Request(request);

           JavaScriptSerializer ser = new JavaScriptSerializer();
            var parsedResult = ser.Deserialize<FacebookUser>(response.Content);

            ProfilePic.ImageUrl = string.Format("http://graph.facebook.com/{0}/picture?type=large",parsedResult.id);
            NameLabel.Text = parsedResult.name;
            AboutLabel.Text = parsedResult.about;
        }

When all goes well it should a little like the picture below.

Okay the formatting may not be optimal, but you get the point on how you can use Hammock to interact with the Facebook Graph API.

You can download the sample code here: Download
Downloaded 1751 times

NOTE: if you want to use the sample you will need to create an application first to get your application client id and secret. For more on this go to: http://www.facebook.com/developers/

, , , , ,

14 Comments

Increase Kooboo performance in IIS 7

Lately I’ve been working with the Kooboo CMS which is built using ASP.NET MVC. I really like the speed Kooboo allows you to build a website with dynamic content. All that fancy footwork comes with a downside. The first time you call a Kooboo application it is really and do mean REALLY slow to start. Cause? Well the Asp.net MVC framework, Microsoft Entity framework and most of all I think the extensive caching mechanism.

I’ve experienced waiting times up till 30 seconds for the first page to appear, now this is not really acceptable for any site I admit. I remembered that there is IIS 7 extension called application warm-up tool that you can configure to call a certain url when the worker process recycles. This will trigger the site to startup again and load up all the caching and stuff. I’m not saying that the next call will be blazingly fast but at least your request will be served much faster.

I’m currently developing several sites using the Kooboo platform and I’m pleasently surprised of the possibilities of the platform. Thumbs up for the creators!

, , , ,

No Comments

Microsoft Tag Rest API & Silverlight

Recently I was contacted by a developer that was working with my MS Tag REST service. He was was calling the REST API from within silverlight. I helped him out with some questions and in return I got a sample project that I can distribute as reference sample. The sample will allow you to create a vcard Tag from within a silverlight application and then display the generated tag.

Live demo : http://tag.ws.suddenelfilio.net/demo/silverlight/Default.aspx

Source Code: Download
Downloaded 152 times

I would foremost like to thank Brian King for his effort in creating this sample for everyone that is interested in it. If you like it, please leave a comment to thank him!

,

3 Comments

Dynamic Data Controls (ASP.NET Futures CTP)

If you want a small introduction for the dynamic data controls that exist in the ASP.NET Futures CTP. You can watch the webcast below:

No Comments

Visual Studio Orcas Beta available !!!

I saw the notice on Informationweek that Microsoft released a beta of the VS.net Orcas.

Find out more here.

No Comments

How to: Print from ASP.Net on a network server

Yesterday we had a small problem with a project of ours. We have a reporting system that server side will process the report and if configured it will print this on a printer somewhere in the network.

When we first tried this every time we printed to a network attached printer we got an error saying that we did not have access to this printer. This behavior is actually normal if you think about it. The server side code runs through an ASP.NET Web Service which in our case runs under it’s native aspnet account. Since this is a local account it does not have access to the network printer.

A solution could be impersonation or just simply make sure the web service runs as a dedicated domain account that has access. This however was not an option for us so we had to look for something else.

The solution I came up with was creating a local printer, but instead of letting it print to a local port like LPT1 I created a new standard TCP/IP port. This allows you to enter an IP and port for the networked printer. The advantage is that this printer is a local printer which requires no authentication at all, so asp.net can use it to print without knowing that it is actually being sent to a network printer.

1 Comment