Skip to main content

WCF - How to add custom information to a message header

De obicei intr-o aplicatie client-server folosim WCF pentru a putea comunica intre client si server. WCF este un framework destul de complex si desi este usor de integrat intr-o aplicatie, cand dorim sa facem ceva mai complex putem sa ne trezim pierduti intre tot felul de documentatii si carti despre WCF.
In acest post o sa prezint cum putem adauga in header-ul mesajului care se trimite la client un continut custom( date suplimentare).
O sa pornim de la urmatarea cerinta: fiecare mesaj care vine de la server trebuie sa vina insotit de un token unic a serverului.
O solutie la aceasta problema ar putea fi ca fiecare mesaj( contract) pe care il primim de la server sa fie incapsulat intr-o clasa de tip Response care contina tokenul nostru. Aceasta solutie este destul de buna, dar ce ne facem daca avem nevoie sa adaugam alte date pe langa token? O sa fie nevoie sa facem update imediat la clienti, servicile pe care le expunem prin WCF trebuie versionate si alte probleme de acest gen. Plus ca raspunsul pe care il primim de la server ar trebui sa contina doar datele pentru operatiea( actiunea) care vrem sa se execute. Altfel o sa fim nevoiti de fiecare data sa verificam daca raspunsul contine token-ul sau sa facem un wrapper peste apel. Toate aceste lucruri duc la o crestere a complexitati plus apare si un smel.
Toate aceste date, care contin statusul la server, tokenul de identificare si orice alte date pot sa fie adaugate in headerul mesajului. Trebuie avut doar grija ce fel de date punem. Informatile care se adauga in header trebuie sa fie informatii comune tuturor mesajelor si nu specifice unei singure operatii.
Acest comportament se obtine destul de simplu daca implementam interfata IDispatchMessageInspector. Prin intermediul acestei interfete putem sa modificam continutul unui mesaj inainte sa fie trimis la client. Avem doua metode pe care trebuie sa le implementam:
  • AfterReceiveRequest - metoda care este apelata automat dupa ce o cerere a ajuns pe client, dar inante ca ea sa fie executata
  • BeforeSendReply - metoda care este apelata chiar inainte ca raspunsul sa fie trimis la client
In cazul in care pe una din actiuni nu vrem sa facem nimic, putem returna null, sau lasam metoda goala. Primul parametru este de tip Message si ne permite sa accesam si/sau modificam mesajul primit sau trimis de la client in orice fel. Prin intermediul la Message avem access atat la header cat si la proprietatea message.Properties. Aceasta colectie de propietati de format (cheie,valoare) ajunge in header-ul mesajului. Valorea poate sa fie orice obiect serializabil, iar cheia este de tip string. Clientul ca sa poata accesa aceste propietati trebuie explicit sa acceseze aceasta colectie( este nevoie ca si clientul sa implementeze un comportament asemanator). Comunicarea intre cei doi o sa functioneze chiar daca clientul nu stie( verifica) aceste propietati. Doar ca nu le v-a putea accesa.
internal class TokenDispatchMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
request.Properties["ServerToken"] = "SomeValue";

return null;
}

public void BeforeSendReply(ref Message reply, object correlationState)
{

}
}
Odata ce am facut acest lucru este nevoie sa ne definim un OperationBehavior sub forma unui atribut, pe care o sa il putem folosi la contractele sau operatiile pentru care avem nevoie de acest comportament. Prin intermediul interfetei IOperationBehavior, putem sa facem si alte actiuni precum validarea unei operatii. Noi avem nevoie doar sa ne inregistram inspectorul de mesaje definit mai sus( de fapt sa il adaugam in lista de message inspectors).
    public class TokenHeadersOperationBehaviorAttribute : Attribute, IOperationBehavior
{
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
}

public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
}

public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
TokenDispatchMessageInspector inspector = new TokenDispatchMessageInspector();
dispatchOperation.Parent.MessageInspectors.Add(inspector);
}

public void Validate(OperationDescription operationDescription)
{
}
}

Pentru operatiile la care avem nevoie de acest comportament, ajunge sa le decoram cu atributul nostru.
    "[ServiceContract]"
internal class MyService:IMyService
{
"[OperationContract]"
[TokenHeadersOperationBehaviorAttribute]
public Response OperationOne()
{
...
}
}
Urmatorul pas este sa ne declaram behaviorul nostru. Acest lucru se face din fisierul de configurare( dar se poate face si din cod):
<system.ServiceModel>
<extensions>
<behaviorExtensions>
<add
name="endpointTokenMessageInspector"
type="Example.TokenDispatchMessageInspector, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
/>
</behaviorExtensions>
</extensions>
...
<behaviors>
<endpointBehaviors>
<behavior name="tokenBehaviorMessageInspector">
<endpointMessageInspector />
</behavior>
</endpointBehaviors>
</behaviors>
...
<service name="Test" ...>
<endpoint
address="/Test"
binding="wsHttpBinding"
behaviorConfiguration="tokenBehaviorMessageInspector"
contract="Test.IMyService"
/>
</service>
</system.ServiceModel>

In acest moment avem configurat serverul. In cazul in care dupa ce faceti configurarile in fisierul de configurare, vedeti ca servicul nu pornteste, va recomand sa adaugati pe rand fiecare linie de configurare. In cazul in care configurarea la serviciu o faceti din cod, va puteti definii propiul endpointBehavior implementand interfata IEndpointBehavior.
Am terminat cu serverul, aproape acelasi lucru trebuie sa il facem pe server, tot ce difera este ca in loc sa implementam interfata IDispatchMessageInspector o sa fie nevoie sa ne folosim de interfata IClientMessageInspector. Aceasta contine doua metode asemanatoare:
  • BeforeSendReply - metoda apelata inainte ca un mesaj sa fie trimis la server
  • AfterReceiveReply - metoda apelata dupa ce se primeste un raspuns de la server
Pe client avantajul folosirii acestei interfete este ca o putem folosii si intr-o aplicatie Silverlight. Pe client, in assembly-urile care formeaza core-ul de la Silverlight oricat am cauta nu o gasim niciodata IDispatchMessageInspector.
    internal class TokenDispatchMessageInspector : IClientMessageInspector
{
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
return null;
}

public void AfterReceiveReply(ref Message reply, object correlationState)
{
string serverToken = reply.Properties["ServerToken"] as string;
}
}
Pentru inregistrarea acestui comportament pe client trebuie sa face aceiasi pasi ca si pe server( definirea unui endpoint custom in care sa specificam behaviorul nostru).
Enjoy!

Comments

Popular posts from this blog

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Run native .NET application in Docker (.NET Framework 4.6.2)

Scope
The main scope of this post is to see how we can run a legacy application written in .NET Framework in Docker.

Context
First of all, let’s define what is a legacy application in our context. By a legacy application we understand an application that runs .NET Framework 3.5 or higher in a production environment where we don’t have any more the people or documentation that would help us to understand what is happening behind the scene.
In this scenarios, you might want to migrate the current solution from a standard environment to Docker. There are many advantages for such a migration, like:

Continuous DeploymentTestingIsolationSecurity at container levelVersioning ControlEnvironment Standardization
Until now, we didn’t had the possibility to run a .NET application in Docker. With .NET Core, there was support for .NET Core in Docker, but migration from a full .NET framework to .NET Core can be costly and even impossible. Not only because of lack of features, but also because once you…