Archive for the ‘Tech Recipes’ Category

How to ask Facebook users for permissions using JavaScript API

In this short post I’ll write the JavaScript code required to ask users to grant stream reading, stream publishing and offline access permissions for your application.

var read = "read_stream";
var offline = "offline_access";
var publish = "publish_stream";
FB_RequireFeatures(["Api"], function() {
    FB.Facebook.init("API_KEY", "xd_receiver.htm");
    var api = FB.Facebook.apiClient;
    FB.Connect.requireSession(function() {
        var session = api.get_session();
        api.users_hasAppPermission(read, function(hasRead) {
            api.users_hasAppPermission(publish, function(hasPublish) {
                api.users_hasAppPermission(offline, function(hasOffline) {
                    var permissions = [];
                    if (!hasRead) permissions.push(read);
                    if (!hasPublish) permissions.push(publish);
                    if (!hasOffline) permissions.push(offline);
                    if (permissions.length > 0) {
                        FB.Connect.showPermissionDialog(permissions.join(","), function(authorized) {
                            alert("Authorized: " + authorized);
                        });
                    }
                    else {
                        alert("Has Permissions");
                    }
                });
            });
        });
    });
});

Facebook Javascript Api

The Facebook JavaScript client library allows you to access various features of Facebook Platform through JavaScript. So you can develop rich ajax applications with the integration of any JavaScript library as jQuery and this Api.

Setting up the JavaScript client:

1. Go to your facebook application configuration and set the “Connect Url” to the url where your code is hosted, usually is the same URL for your “Canvas Callback URL” as seen on the post “Setup a facebook application”.
2. Create a file called xd_receiver.htm. this file handles the cross domain communication and must contain the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

<title>Cross-Domain Receiver Page</title>

</head>

<body>

<script src="http://static.ak.facebook.com/js/api_lib/v0.4/XdCommReceiver.js?2" type="text/JavaScript"></script>

</body>

</html>

3. For the user’s browser to correctly recognize XFBML tags, you need to specify that the page is in XHTML. IE loves to bug around if you don’t include this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">

4. Include the following script on the <body> not on the <head> since it loads some features and this can cause issues and errors with some browsers:

<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/JavaScript"></script>

5. And finally include the following script in the body after all the xFBML tags that you want to load:

<script>

FB_RequireFeatures(["Api"], function(){

FB.Facebook.init("YOUR_API_KEY_HERE", "<relative path from root>/xd_receiver.htm");

});

</script>

Working Example:

<script type="text/javascript">
    FB_RequireFeatures(["Api"], function() {
        FB.Facebook.init("yourapikey", "xd_receiver.htm");
        FB.Facebook.get_sessionState().waitUntilReady(function() {
            var api = FB.Facebook.apiClient;
            uid = api.get_session().uid;//get the current user uid
//get the info of the user given the uid, pass the current user uid to get current’s user info
            api.users_getInfo(uid, ['name'], function(user, exception) {
        var name  = document.getElementById("uname")
        //we get the 0 position since it returns a list of users information
                name.value = user[0].name;
            });
        });
    });
    </script>

More Methods of the api client can be found here:

http://developers.facebook.com/docs/?u=facebook.jslib.FB.ApiClient

with this api you can do pretty much everything.

Facebook xFBML render on an Iframe Application

Facebook uses XFBML as a way for you to incorporate FBML (Facebook Markup Language, an extension to HTML) into an HTML page on a Facebook Connect site or an iframe application.

~Facebook wiki.

The list of available tags that can be used as xFBML are here:

http://wiki.developers.facebook.com/index.php/XFBML
if you need to use FBML that aren’t listed on that place you can ever use the fb:serverfbml tag wich is able to render any FBML inside it. Typical FBML tags you would wrap within fb:serverfbml are those that require user input, like fb:request-form. The contents of fb:serverfbml are rendered in a Facebook iframe.
Rendering xFBML steps:
1.    Go to your facebook application configuration and set the “Connect Url” to the url where your code is hosted, usually is the same URL for your “Canvas Callback URL” as seen on the post  “Setup a facebook application”.
2.    Create a file called xd_receiver.htm. this file handles the cross domain communication and must contain the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

<title>Cross-Domain Receiver Page</title>

</head>

<body>

<script src="http://static.ak.facebook.com/js/api_lib/v0.4/XdCommReceiver.js?2" type="text/JavaScript"></script>

</body>

</html>

3. For the user’s browser to correctly recognize XFBML tags, you need to specify that the page is in XHTML. IE loves to bug around if you don’t include this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">

4. Include the following script on the <body> not on the <head> since it loads some features and this can cause issues and errors with some browsers:

<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/JavaScript"></script>

5. And finally include the following script in the body after all the xFBML tags that you want to load:

<script>

FB_RequireFeatures(["XFBML"], function(){

FB.Facebook.init("YOUR_API_KEY_HERE", "<relative path from root>/xd_receiver.htm");

});

</script>

Alternatively if you don’t want to use the xFBML tags and use just html ad JavaScript you can render the xFBML in this way:

http://wiki.developers.facebook.com/index.php/Using_HTML_to_Imitate_XFBML

Facebook Iframe canvas application: Authentication and session with Microsoft Facebook SDK.

SDK: http://msdn.microsoft.com/en-us/windows/ee388574.aspx

Setting up the application and visual studio for debugging:

Debugging in visual studio is just possible on Iframe canvas applications, if you want to develop from localhost you need to change a bit the setup of your facebook application and apply some changes to the visual studio application’s options:

  1. Canvas: you must change the “Canvas Callback URL” to http://localhost:port/ i.e: for port 63919, then our url would be http://localhost:63919
  2. The render method must be Iframe, FBML doesn’t support debugging neither work on localhost since you need a host so it can be embed on facebook.
  3. Edit Settings in web.config : In the project, open web.config. In <appSettings> element. Change the values for those settings to the following:
  • APIKey: your API key
  • Secret: your application secret
  • Callback: your callback URL
  • Suffix: The suffix of your canvas page URL. For example, for a site located at http://apps.facebook.com/myapp/, the suffix is myapp.

Example:

<appSettings>

<add key="APIKey" value="yourapikey" />

<add key="Secret" value="yoursecret" />

<add key="Callback" value="yourcallbackurl" />

<add key="Suffix" value="yourappsufix" />
</appSettings>

4. Set Up Project Port Number:

      • Open the project properties (right-click the project, click Properties).
      • Click the Web tab on the left side.
      • In the Servers section on the page, select “Use Visual Studio Development Server”.
      • Select “Specific Port”, and enter the port number from your callback URL.

5. Run Application

      • Start the Web application (click Debug menu, click Start Debugging).
      • Close the browser window that opens, since it doesn’t open your app within the Facebook context.
      • Go to your canvas page URL (http://apps.facebook.com/yourapp).
      • On the “Allow Access?” page, click “Allow”.
      • Now you can debug your application.

Authentication

To take care of authentication in facebook we are going to use the microsoft’s facebook SDK, we are going to use the CanvasIFrameMasterPage This class takes care of the entire authentication process, all you have to do is give the application your API key and secret, as we did in the web.config.

To use this class we create add references to the facebook.dll and facebook.web.dll then call them as using withing the code behind of the masterpage  after this the custom master page is set to inherit from CanvasIFrameMasterPage.

then we set the RequireLogin attribute to true so the application calls for login whenever user is logged off.

Example:

using Facebook;

using Facebook.web;

public partial class CustomMasterPage : Facebook.Web.CanvasIFrameMasterPage{

public CustomMasterPage()

{

RequireLogin = true;

}

}

Finally, each page is set to use this custom master page by setting the MasterPageFile attribute in the Page directive as well as creating a MasterType directive. The easiest way to set up the content pages is to create them through the master page: just right-click on the master page in Solution Explorer and select “Add Content Page”. The new page will have the correct MasterPageFile attribute set as well as each of the <asp:Content> elements used by the master page, although you will have to set the MasterType directive manually:

<%@ Page AutoEventWireup="true" MasterPageFile="~/CustomMasterPage.Master"
CodeBehind="Default.aspx.cs" Inherits="IFrameSample.Default" %>
<%@ MasterType VirtualPath="~/CustomMasterPage.Master" %>

After all this you have a working iframe canvas application that handles authentication, session and can be debugged on visual studio.

Setup a Facebook application

How to setup an application on facebook on 4 easy steps:

Step 1

Go to: http://www.facebook.com/developers/

Once there click on the “Set up New Application” button.

Step 2:

Fill the fields on this page, also agree with the “Facebook Terms” (there is a link to read it) then click on “Create Application”.

Step 3 Basic Information:

Api Key: You must save this on since you are going to need it on the future for your application’s development.

Secret: also needed for application development.

Bookmark URL:  URL of your application so the users can bookmark it on facebook, usually http://apps.facebook.com/myappname

The other information to fill is just informative or aesthetic since it references to the description and icons to use in your application, the User-Facing URL are set according to your help, privacy and conditions of your application.

Step 4 Canvas:

Canvas Page URL: The base URL for your canvas pages on Facebook.

Render Method:

IFrame:

  • Are easier and faster if you have an existing application, widget, or website if the application utilizes XFBML
  • Let you use the JavaScript, HTML, and CSS that you are used to
  • Debugging regular HTML and JavaScript is easier than for FBML and FBJS given the tools available today
  • Allow you to use popular JavaScript libraries like jQuery in your code

FBML:

  • Lets you quickly start building an application from scratch, which is good for a new Facebook developer.
  • Is likely to be faster on first page loads
  • Has fewer moving parts and the paradigm is closer to that of the traditional Web
  • Gives you easy access to lots of Facebook elements
  • Has a sensible authorization mechanism

Step 3 Connect:

This is an important step if you are going to use JavaScript API or facebook connect inside your application.

Connect URL: this is the URL of your application wherever is hosted since there you will have a file named xd_receiver.htm (this file is the one receiving all the calls from the facebook JavaScript API to enable the cross domain for the Ajax calls)

The other fields can be left in blank or filled with the necessary information according to whatever you want to do with your facebook application.

After this 4 steps facebook is ready to load your application.

How to provide custom JSON exceptions from a WCF service

In my last post I described a simple way to handle exceptions in WCF services (It might be helpful to read it before this one). Now I’d like to go a step further writing a solution to provide JSON exceptions. This approach is helpful for applications using pure JavaScript to connect to a WCF service. For me it makes a lot of sense to have a service that transparently provides JSON responses with exception information instead of regular HTML or XML responses, which are very difficult to deal with using JavaScript.

First we need to create our Error class. This error class will contain all the attributes we define for our JSON Exception. This class will be serialized as JSON before sending it as response when an exception occurs.

[DataContract]
public class AjaxError
{
    [DataMember]
    public int Code { get; set; }
    [DataMember]
    public String Message { get; set; }
}

Then we need to write our ErrorHandler class implementing IErrorHandler interface. In the ProvideFault method we will take care of the object serializing the response object and setting the response content type and status. You may notice that we are always setting the response status as BadRequest, this is just a personal decision, you can set it as InternalServerError o any other status you decide.

public class ErrorHandlerEx : IErrorHandler
{
    public bool HandleError(Exception error)
    {
        return true;
    }

    public void ProvideFault(Exception exception, MessageVersion version, ref Message message)
    {
        AjaxError error = new AjaxError();
        error.Code = 1;
        error.Message = exception.Message;
        message = Message.CreateMessage(version, "", error, new DataContractJsonSerializer(error.GetType()));
        var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
        message.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
        WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
        WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
    }
}

After that we create a behavior inheriting from WebHttpBehavior and in the AddServerErrorHandlers class we remove the existing error handlers and add ours.

public class WebHttpBehaviorEx : WebHttpBehavior
{
    protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        endpointDispatcher.ChannelDispatcher.ErrorHandlers.Clear();
        endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new ErrorHandlerEx());
    }
}

Now we need to write our own service factory inheriting from WebServiceHostFactory and in the CreateServiceHost method we add our custom behavior to the endpoint.

public class ServiceHostFactory : WebServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        ServiceHost host = new ServiceHost(typeof(Services), baseAddresses);
        ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IServices), new WebHttpBinding(), "");
        endpoint.Behaviors.Add(new WebHttpBehaviorEx());
        return host;
    }
}

Finally we need to set our Service factory in the Factory attribute of the ServiceHost tag for our Service Markup.

<%@ ServiceHost
        Language="C#"
        Debug="true"
        Service="Services"
        CodeBehind="Services.svc.cs"
        Factory="ServiceHostFactory"
%>

How to take care of unhandled exceptions in WCF Services

When developing web services using WCF it’s considered a good practice to take care of unhandled exceptions. In this post I’ll explain an easy way to log your WCF unhandled errors and create a custom message.

First you will need to create a class that inherits from Attribute and implements IServiceBehavior and IErrorHandler interfaces. Inheritance from Attribute will allow us to use our new class as metadata for our service. IServiceBehavior interface makes our new class a custom extension for a service and IErrorHandler will give us control over service faults. As you can think we will be creating a new service behavior that handles errors and will be assigned to our service as a metadata attribute. This is the code for our custom error handler:

public class ErrorHandlerAttribute : Attribute, IServiceBehavior, IErrorHandler
{
    public bool HandleError(Exception e)
    {
        EventLog log = new EventLog();
        log.Source = "Your Application Name";
        log.WriteEntry(e.Message + "\n" + e.StackTrace, EventLogEntryType.Error);
        return true;
    }

    public void ProvideFault(Exception error,
        MessageVersion ver,
        ref System.ServiceModel.Channels.Message msg)
    {
        FaultException fe = new FaultException("Your Custom Error");
        MessageFault fault = fe.CreateMessageFault();
        msg = System.ServiceModel.Channels.Message.CreateMessage(ver, fault, null);
    }

    public void AddBindingParameters(ServiceDescription serviceDescription,
        ServiceHostBase serviceHostBase,
        Collection<ServiceEndpoint> endpoints,
        BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription,
        ServiceHostBase serviceHostBase)
    {

    }

    public void Validate(ServiceDescription serviceDescription,
        ServiceHostBase serviceHostBase)
    {

    }
}

The AddBindingParameters, ApplyDispatchBehavior and Validate methods will need no implementation. We just need to take care of HandleError method for logging and ProvideFault method to create our custom error message.

After that all you need to do is annotate your service class with the error handler:

[ErrorHandler]
public class Service : IService
{
}

Object Oriented Programming (OOP) in JavaScript

When you are trying to develop a complex JavaScript application you will be looking for a way to organize and maintain your code in an easy way, that’s why Object Oriented Programming looks like the perfect approach. In OOP you can talk about public, private and privileged methods and members. Private methods and members have access the whole object but can’t be accessed by other objects. Public members and methods can’t access private parts but can be accessed by other objects. Finally privileged methods have full access to object and can be accessed by other objects.

The next technique can be used to write OOP in JavaScript:

1. Constructors are functions with the name of the object:

function Constructor(value) { ... };

2. Private members will be defined inside the constructor:

function Constructor(value) {
    var member = value;
};

3. Private methods will be defined inside the constructor:

function Constructor(value) {
    function Method() { ... }
    var Method = function() { ... }
};

4. Public members will be created inside the constructor and associated to this:

function Constructor(value) {
    this.member = value;
};

5. Public methods will be created outside the constructor using the prototype member of the object:

function Constructor(value) { ... };
Constructor.prototype.Method(){ ... }

6. Privileged methods will be created inside the constructor and associated to this:

function Constructor(value) {
    this.Method = function() { ... }
};

Using Forms Based Authentication (FBA) on a desktop application in C#

To use FBA on a desktop client will be necessary to make a first request to the server and create the authentication cookie. This cookie will be used on the next requests to receive permission from the server to access protected resources imitating the browser’s behavior.
First we need to write a server side method that receives the login and password information, does the authentication task and creates the authentication cookie:

public bool Authenticate(String login, String password)
{
    if (Membership.ValidateUser(login, password))
    {
        System.Web.Security.FormsAuthentication.SetAuthCookie(login, false);
        return true;
    }
    else return false;
}

On the client side we need to make a request to the authentication method and copy the authentication cookie to the future requests (Here you will find an easy way to make post requests using C#):

Cookie cookie = authenticate_response.Cookies[".ASPXAUTH"];
new_request.CookieContainer = new CookieContainer();
new_request.CookieContainer.Add(cookie);

Making a JSON service request using C#

This is an easy way to make a JSON POST request to a remote service using C#:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset:utf-8";
DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, data);
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();

Notice that in line 4 we create an instance of DataContractJsonSerializer (Assembly: System.ServiceModel.Web) and initialize it with the type of object we are serializing as JSON to send to the service. In lines 5 and 6 the serializer writes the object into a Stream. Line 7 transforms the Stream into an UTF-8 String (as the content-type) and finally in lines 8 to 10 we send the data to the service.

Return top

Idea Manglar

Idea Manglar is a private held startup located in Cali, Colombia, South America. It began as an idea lab and quickly became an intuitive and innovative software developer. 1136 and Dynamic Crystal will be the first ideas going online on 2010. http://www.manglar.com