Browse by Tags

[WCF] Delegation between WCF and CRM Services

Impersonation and Delegation are important concepts around the services' world. Impersonation restricts client access to resources in the local machine where is running the service and Delegation restricts client access to resources on other machine. In my scenario, I was trying to access from a WCF service to Dynamics CRM 4.0 services using Delegation.

In WCF, Delegation is a special type of Impersonation, which can be configured easily according to the next good articles:

However, some points are not really emphasized and you shouldn’t forget them:

  • Allow impersonation in the corresponding server. This configuration must be set from the domain controller.
  • User who is running WCF service must have enough privileges to impersonate the expected users
  • Allow Delegation from the client side. You have two options to do it:
    • Client Config. file:
 <behaviors>
<endpointBehaviors>
<behavior name="NewBehavior">
<clientCredentials>
<windows allowedImpersonationLevel="Delegation" />
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
    • Programmatically:
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
  • Set the userPrincipalName properly in client configuration file according to the user who is running the WCF service:
 <client>
<endpoint address="service address with an allowed protocol to impersonate"
behaviorConfiguration="NewBehavior" binding="Allowed protocol to impersonate"
bindingConfiguration="defaultEndPoint" contract="MyAssembly.MyContract"
name="defaultEndPoint">
<identity>
<userPrincipalName value="serviceuser@mydomain.com" />
</identity>
</endpoint>
</client>
Posted 23 February 10 12:37 from Escuchoyo | 0 Comments   
Filed under
[WPF/WCF] DataGrid + DoubleClick + MVVM + Loading Splash (description & code)

Using the DataGrid WPF Toolkit, this post shows a simple client/server application to fill a DataGrid according to the information that is provided by a WCF service. When any row receives a double click, a new document (jpeg or docx for this example) is opened by an external application.

WPFDataGridExampleLoading

WPFDataGridOpenDocument

The application is designed using MVVM pattern, where View and ViewModel are placed in the client side and Model in the server side. In our example, we will show a set of “Alerts” in a DataGrid , so that we will have the next elements:

  • Model: Alert. This class provide all the information about an “Alert” entity.
  • View: Custom DataGrid with all the alerts
  • ViewModel: Intermediary element between Model and View to decouple the alert model from its view. In our case,  ViewModel provides a collection of alerts and a command to open its associated document.

About the DataGrid control, I would like to highlight the next points:

  • Double click behavior in DataGrid control using attached properties. See the new HandleDoubleClick and TheCommandToRun properties in DataGrid, which are declared in WpfApplication.TestGridView => AttachedProperties => SelectorDoubleClickCommandBehavior.cs
  • Using DataGridTemplateColumn: I got some problems trying to apply padding in the cell content, regarding the rest styles and behaviors (see Themes folder). To resolve it, I’ve used a DataGridTemplateColumn, which allows integrate any custom content in a cell. In this way, I’m using a TextBlock with a specify margin to simulate that padding.

In the server side (WCF service), I’ve implemented a request/response messages architecture, so that it would be easier and scalable to add other functionality like delete or create alerts (see the service implementation in WcfService.ServiceLibrary => AlertsService.cs, as well as the retrieve messages and handler).

Download source (VS2008)

This application is based on different sources, which can be found below. At the same time, I would like to be grateful to my workmate Wael, who is a great developer and he always gives me great advices.

Useful Links:

Posted 07 January 10 10:02 from Escuchoyo | 0 Comments   
Filed under ,
Serializar Dictionay de tipos complejos usando Framework 3.0 - WCF

Continuando con el anterior post de la serialización de diccionarios, una asignatura pendiente en el Framework 2.x, veremos ahora como conseguirlo con el Framework 3.0 también sobre tipos complejos; es decir, ahora tendremos un diccionario tal que Dictionary<MiTipo1,MiTipo2> y podremos des-serializarlo a XML sin necesidad de implementar nuestras propios diccionarios.

Pasemos directamente a ver un sencillo ejemplo sobre códigoWink  ; para ello suponemos declarada un sencilla clase "Casa", la cual será uno de los tipos contenidos en nuestro diccionario.


    [DataContract]
    public class Casa
    {
        [DataMember]
        public string nombre;

        [DataMember]
        public int habitaciones;

        public Casa() { }

        public Casa(string nombre,int habitaciones)
        {
            this.nombre = nombre;
            this.habitaciones = habitaciones;
        }
    }

Como podeis observar, los miembros de nuestra clase están marcados con ciertos atributos especiales. Estos también provienen del ensamblado System.Runtime.Serialization.dll y dan sorporte al nuevo motor de serializacion de WCF (Data Contract Serializer). Son fundamentales si queremos que una entidad o alguno de sus miembros sea serializable.

 

  • Serializando un diccionario de tipos complejos:
 
Dictionary<string, Casa> diccionario_casas = new Dictionary<string, Casa>(2);
          diccionario_casas.Add("iberica", new Casa("iberica", 8));
          diccionario_casas.Add("jardinera", new Casa("jardinera", 15));

          XmlWriterSettings setting = new XmlWriterSettings();
          setting.Indent = true;
          XmlWriter xtw = XmlTextWriter.Create("c:/casas.xml", setting);

          XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateDictionaryWriter(xtw);

          DataContractSerializer dcs = new DataContractSerializer(typeof(Dictionary<string, Casa>));

          dcs.WriteObject(xdw, diccionario_casas);
          xtw.Close();

  • Deserializando un diccionario de tipos complejos:

 

XmlReader xr = XmlDictionaryReader.Create("c:/casas.xml");

          DataContractSerializer dcs = new DataContractSerializer(typeof(Dictionary<string, Casa>));

          Dictionary<string, Casa> mundo = (Dictionary<string, Casa>)dcs.ReadObject(xr);

          xr.Close();

 

 Para más información http://msdn2.microsoft.com/en-us/library/ms733127.aspx

Posted 09 August 07 05:00 from Escuchoyo | 0 Comments   
Filed under ,
Serializar Dictionay usando Framework 3.0 - WCF

 Para aquellos que hayan intentado serializar un diccionario con el Framework 2.x (o inferiores), se habrán encontrado con un maravilloso error de que ello no es posible por defecto. ¿Pero si puedo serializar una lista de tipos complejos, tal que List<MiTipo>, por qué no voy a poder serializar un diccionario que es 3/4 de lo mismo? Este problema digamos que se nos escapa de nuestras manos humildes y tendríamos que preguntarselo a los chichos de Redmon, ya que el problema se encuentra dentro del Framework.

Una tipo que quiera ser serializable debe implementar IXmlSerializable, lo cual no lo hace la clase Dictionary, ¿por qué? This is the question. Dicha clase se encuentra en la librería mscorlib.dll y IXmlSerializable en System.Xml.dll, no pudiendo haber dependencias de la primera a la segunda, ya que se crearía una referencia circular (System.Xml ya hace uso de mscorlib).

Para subsanar dicho problema con el Framework 2.x acudíamos al truco del almendruco: creabamos nuestra propia clase Diccionario la cual heredara de Dictionary e implementara IXmlSerializable, algo tal que así:

[XmlRoot("dictionary")]

public class SerializableDictionary<TKey, TValue>

        : Dictionary<TKey, TValue>, IXmlSerializable

{ ....

}

Podeis encontrar un ejemplo completo de ello en http://weblogs.asp.net/pwelter34/archive/2006/05/0...

------------------------------------------------

Con la llegada del Framework 3.x, este problema queda solucionado, dándonos soporte el módulo de WCF (Windows Communication Foundation).  Concretamente, la librería System.Runtime.Serialization del Framework 3.0 nos proporciona las entidades XmlDictionaryWriter y DataContractSerializer.

Si ahondamos un poco más en la cuestión, veremos como los desarrolladores del Framework 3.0 han solucionado el problema de la posible referecia circular antes comentanda, incorporando la clase XmlDictionaryWriter al ensamblado System.Runtime.Serialization.dll con en el espacio de nombre System.Xml, en lugar de incorporarla al ensamblado supuestamente correspondiente System.XML.dll

La clase DataContractSerializer es la entidad similar a XmlSerializer, encargada de serializar los diccionarios a traves de XmlDictionaryWriter.

Veamos para terminar un poco de código, donde serializaremos un Diccionario de tipos simples. En el próximo post, para no alargar más éste, serializaremos y deserializaremos un diccionario con tipos complejos.

 

Dictionary<string, string> mundo = new Dictionary<string, string>();
mundo.Add("coche", "renault");
mundo.Add("animal", "gato");
 
 
XmlWriterSettings setting = new XmlWriterSettings();
setting.Indent = true;
XmlWriter xtw = XmlTextWriter.Create("c:/mundo.xml", setting);
 
XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateDictionaryWriter(xtw);
 
System.Runtime.Serialization.DataContractSerializer dcs = new DataContractSerializer(typeof(Dictionary<string, string>));
 
dcs.WriteObject(xdw, mundo);
xtw.Close();

 

Si nos vamos a C:/ veremos el nuevo archivo mundo.xml con el siguiente contenido:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfKeyValueOfstringstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <KeyValueOfstringstring>
    <Key>coche</Key>
    <Value>renault</Value>
  </KeyValueOfstringstring>
  <KeyValueOfstringstring>
    <Key>animal</Key>
    <Value>gato</Value>
  </KeyValueOfstringstring>
</ArrayOfKeyValueOfstringstring>
Posted 08 August 07 06:02 from Escuchoyo | 0 Comments   
Filed under ,