How to use SSL in a WCF service

1. Enable SSL configuration on your site
2. Set your binding security mode to Transport.
3. Set you service behavior serviceAuthorization PrincipalPermissionMode to None.

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

How to publish WCF services using IIS6

1. C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis –i
2. C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe –i
3. Do all the things you normally do on IIS7, you are all set.

How to go beyond PUT and DELETE limitations on RESTful Scenarios

One of the biggest problems you will have while implementing RESTful services is that most of today’s browsers and firewalls will not allow PUT and DELETE requests. An easy way to fix this is to add a custom HTTP header to your post requests and send the real method in there. Since Google is using “X-HTTP-Method-Override” it looks like a smart choice to follow that pattern and use it too.

This simple jquery code shows how to do it in the client side:

$.ajax({
    type: "POST",
    url: serviceURL,
    data: "data",
    success: function(data, textStatus) { alert("success"); },
    error: function(xhr, status, error) { alert("error"); },
    beforeSend: function(xhr) { xhr.setRequestHeader("X-HTTP-Method-Override", "DELETE"); }
});

This C# code shows how to use the custom header in a WCF server:

public String PostProxy(String data)
{
    switch (HttpContext.Current.Request.Headers["X-HTTP-Method-Override"])
    {
        case "PUT": return Add(data);
        case "DELETE": return Delete(data);
        default: return Update(data);
    }
}

Big files transfer using WCF services

If you need to receive files bigger than 4MB using WCF services you have to change the default configuration in your web.config file to allow the size required.

<system.web>
    <httpRuntime maxRequestLength="131072" />
</system.web>

Note: this should work for any ASP application.

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.

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