Author Archive

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.

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.

Como eliminar la extensión .svc de un servicio WCF en IIS7

Cuando se está desarrollando un servicio con WCF + REST probablemente se quiera eliminar la extensión .svc de la ruta. Por ejemplo, puede ser preferible que nuestro servicio http://manglar.com/service.svc/gmedina/ se pueda acceder desde la ruta http://manglar.com/service/gmedina/ . Para hacer esto es necesario instalar el URL Rewrite Module para IIS7, y crear una regla de reescritura en el web.config de la siguiente manera:

<system.webServer>
  <rewrite>
      <rules>
          <rule name="Remove .svc" enabled="true">
            <match url="Service/(.*)$" />
              <action type="Rewrite" url="Service.svc/{R:1}" />
          </rule>
      </rules>
    </rewrite>
</system.webServer>

Lo que logramos con esto es que todas las direcciones que lleguen a nuestro servicio con la ruta http://manglar.com/service/* sean reescritas como http://manglar.com/service.svc/*

Como hacer Backup para SQL Server 2008 en dispositivos de red

Aunque la idea es hacer de este un blog menos técnico y más amigable, empezaré usándolo como lo que es, una bitácora. Hoy tuvimos que configurar nuestros servidores de bases de datos (SQL Server 2008 / Windows 2008) para hacer backups todas las madrugadas en un network drive sobre una máquina Linux. Aunque probablemente esta sea una tarea bastante obvia para un administrador de bases de datos experimentado, debo confesar que dimos varias vueltas antes de lograr el resultado esperado.

Al principio la tarea parecía sencilla, pensamos que solamente debíamos usar las herramientas de administración de SQL Server 2008 para crear el backup (como siempre lo hemos hecho), pero resultó que no es posible usar una dirección de red para este fin, solamente el dispositivo que tiene asociado por defecto. Luego pensamos que lo que debíamos hacer era algún tipo de script que tomara los archivos y los moviera de la ruta configurada a la ruta deseada, pero tampoco fue así de fácil.

Finalmente, y después de una búsqueda acertada encontramos la manera más fácil de hacer todo el proceso y terminamos obteniendo mejores resultados de lo que esperábamos. Esto fue lo que hicimos:

Ejecutamos el siguiente script para asociar la dirección de red a un dispositivo que el servidor aceptara:

EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
EXEC xp_cmdshell 'net use H: \\DRIVE PASSWORD /user:USUARIO'

Configuramos el correo electronico (Management/Database Mail)
Creamos un operador (SQL Server Agent/Operators)
Creamos un plan de mantenimiento (Management/Maintenance Plans) que nos permitió verificar la integridad de la base de datos, reorganizar los índices, actualizar las estadísticas, hacer backups incrementales y enviar un correo electrónico con el reporte todas las madrugadas.

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