Declarative permissions for WCF services

When you develop WCF services you might want to have some protected and unprotected methods on the same service. To do this you will need to do as follows.
Publish your service on an unprotected area of your site; change your web.config file to do it:

<location path="services">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>

Add this line of code to your service constructor method:

public Service()
{
    Thread.CurrentPrincipal = HttpContext.Current.User;
}

Finally use declarative permissions on the service methods you want to protect:

[PrincipalPermission(SecurityAction.Demand)]
public String YourMethod()
{
    return String.Empty;
}

How to change ASP MembershipProvider ResetPassword method to provide easier passwords

First of all you don’t. You have to change the GeneratePassword method used in the ResetPassword method. To do this you need to write your own membership provider and override it like in this example:

public class MembershipProvider : System.Web.Security.SqlMembershipProvider
{
    const String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const String LOWER = "abcdefghijklmnopqrstuvwxyz";
    const String NUMBERS = "1234567890";
    const String SPECIAL = "*$-+?&=!%/";

    public override string GeneratePassword()
    {
        Random rand = new Random();
        String password = "";
        List<String> data = new List<String>();
        for (int i = 0; i < 10; i++)
        {
            if ( i < 3 ) data.Add(UPPER[rand.Next(UPPER.Length)].ToString());
            else if ( i < 6 ) data.Add(LOWER[rand.Next(LOWER.Length)].ToString());
            else if ( i < 8 ) data.Add(NUMBERS[rand.Next(NUMBERS.Length)].ToString());
            else if ( i < 10 ) data.Add(SPECIAL[rand.Next(SPECIAL.Length)].ToString());
        }
        while (data.Count > 0)
        {
            int pos = rand.Next(data.Count);
            password += data[pos];
            data.RemoveAt(pos);
        }
        return password;
    }
}

Note: After you do this you will not be able to use the IIS7 management for your users.

Calling Facebook RESTful API using C# (Without Microsoft Facebook SDK)

To continue with our previous posts about Facebook I’m going explain how to use the RESTful API from C# code. This time I’m writing a console application to read user Facebook’s statuses. This illustrates that you can really use the RESTful API from any application including desktop.
A very important thing you need to do before this code works is to ask your user for authorization to read his stream with offline access as shown in this post. After your user grants your application to have offline access you can read his session_key and use it everywhere because it will never expire.

You can download the source code for this post here.

First we need to write a Class that mimics Status FQL table.

public class Status
{
    public String status_id { get; set; }
    public String time { get; set; }
    public String source { get; set; }
    public String message { get; set; }
}

Then we create a method to generate our data signature.

public static String GetSignature(Dictionary<String, String> parameters)
{
    MD5 md5 = MD5.Create();
    String data = "";
    String[] keys = parameters.Keys.OrderBy(k => k.ToString()).ToArray();
    for (int i = 0; i < keys.Length; i++)
    {
        String key = keys[i];
        String value = parameters[key];
        data += key + "=" + value;
    }
    data += "APPLICATION_SECRET";
    byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(data));
    String signature = "";
    foreach (byte b in bytes) signature += b.ToString("x2");
    return signature;
}

After that we just build our post data, post our request, read our response and deserialize the status objects.

static void Main(string[] args)
{
    Dictionary<String, String> parameters = new Dictionary<String, String>();
    parameters.Add("format", "json");
    parameters.Add("method", "Fql.query");
    parameters.Add("query", "select status_id, time, source, message from status where uid = USER_ID");
    parameters.Add("session_key", "SESSION_KEY");
    parameters.Add("api_key", "API_KEY");
    parameters.Add("v", "1.0");
    parameters.Add("call_id", DateTime.Now.Ticks.ToString());
    parameters.Add("sig", GetSignature(parameters));
    String postData = "";
    for (int i = 0; i < parameters.Keys.Count; i++)
    {
        String key = parameters.Keys.ElementAt(i);
        String value = parameters[key];
        String param = key + "=" + HttpUtility.UrlEncode(value);
        postData += param;
        if (i < parameters.Keys.Count - 1) postData += "&";
    }
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.facebook.com/restserver.php");
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    StreamWriter writer = new StreamWriter(request.GetRequestStream());
    writer.Write(postData);
    writer.Close();
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Status[]));
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Status[] statuses = (Status[])serializer.ReadObject(response.GetResponseStream());
    foreach (Status s in statuses)
    {
        DateTime time = new DateTime(long.Parse(s.time));
        Console.WriteLine(time.ToString() + ", " + s.message);
    }
    Console.ReadLine();
}

Note that you can use this approach to call any method in the RESTful API, not to just make FQL queries.

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");
                    }
                });
            });
        });
    });
});

Los servicios Web de hoy (REST)

Hace un par de años cuando trabajaba en un proyecto sobre el lenguaje de programación Python me encontré con el reto de integrar una aplicación con otra. Como era de esperarse, la respuesta inmediata fue usar webservices. En ese momento para hacer uso de este concepto tan obvio y tan común en nuestros días necesitábamos emplear unas librerías hechas por un buen samaritano del desarrollo open source que no había tenido tiempo últimamente para actualizar su trabajo, no teníamos más opciones. El resultado, un tortuoso proceso hasta lograr una integración a medias y que estaba limitada por las posibilidades del lenguaje de programación que estábamos usando.
Varios años después, me encontraba en una conferencia de desarrolladores y escuche por primera vez el concepto REST. Sonaba como una solución maravillosa, como esas cosas que son tan simples y tan obvias que uno no entiende como nadie pensó antes en ellas, y más aun, como nos pudimos meter en algún momento en problemas como el de la integración de la aplicación en Python.
REST es otro estilo de arquitectura para desarrollo de aplicaciones a través de webservices, si, otro. Lo que hace que REST sea diferente es que es lo más neutral posible, solo hace uso de algo que ya todos hemos adoptado, la Web. Parece lógico, pero y acaso los demás webservices no usan la Web también? Si claro, pero para comunicar una aplicación con otras se han creado protocolos de comunicación nuevos (SOAP) sobre el protocolo ya existente, HTTP. REST solo usa HTTP, nada más. Pero si será posible que algo tan sencillo permita crear aplicaciones a gran escala como lo permite hoy en día SOAP? De acuerdo con Roy Fielding, uno de los creadores de la especificación de HTTP sí. REST (Representational State Transfer) predica la separación de capas, el no uso de estados (sesiones) y el aprovechamiento del cache que son características comunes en sistemas distribuidos. Los beneficios que se obtienen son interoperabilidad, evolución independiente, escalabilidad y mejoramiento del desempeño.
La Web fue construida sobre HTTP, una interface uniforme e independiente de la tecnología usada, esta interface fue diseñada para que humanos y maquinas interactúen unos con otros a través de métodos elementales como GET, POST, PUT o DELETE (las acciones básicas de cualquier sistema de información). Los servicios REST usan esta única interface para hacer de la comunicación entre aplicaciones algo natural, eficiente y fácil de implementar. Hoy en día los grandes proveedores de aplicaciones y servicios Web han adoptado a REST como la plataforma fundamental para sus negocios. Facebook, Twitter, Microsoft y Google son algunos de los ejemplos más sobresalientes.

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"
%>
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