Archive for the ‘WCF’ Category

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

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
{
}

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