Posts Tagged Asp.Net

LINQ to XML


LINQ to XML

LINQ(Language Integrated Query)to XML is the modern way of dealing with XML data. The Linq to Xml came with the.Net Framework 3.5. Before that we were using XMLDocument which follows the DOM architecture. But with the introduction of LINQ the task has been reduced a lot coding wise for the developers. But for type of operations the whole XML Document has to be loaded in memory.

Today we will look how we canperform certain operation on Xml data using the Linq to XML architecture.

Reading the Xml and Storing in List

Lets create a sample XML which we are going to use read using Linq to XML feature. The below XML is our sample xml lets name it as “Sample.xml”.

<Configurations>
    <Employee Id="1">
        <Info Name="aaaaa" Age="24" Sex="Male"></Info>
        <Info Name="bbbbb" Age="25" Sex="Male"></Info>
    </Employee>
    <Employee Id="2">
        <Info Name="ccccc" Age="26" Sex="Male"></Info>
        <Info Name="ddddd" Age="27" Sex="Female"></Info>
    </Employee>
</Configurations>

Lets create a class a define some

property that can hold the xml values. Lets name this class as ReadingXmlWithLinq.cs

public class ReadingXmlWithLinq
        {
            public string Name { get; set; }
            public string Age { get; set; }
            public string Sex { get; set; }
        }

Now let’s see how we can read the Sample.xml file using Linq to Xml concept.

using System;
using System.Linq;
using System.Xml.Linq;

private IList<ReadingXmlWithLinq> GetXMlList()

{	
   XDocument configparentXML = XDocument.Load(xmlPathAddress);
   string node = "Info";
   var configs = (from config in configparentXML.Descendants(node)
   select new ReadingXmlWithLinq
    {
       Name = config.Attribute("Name") != null ? config.Attribute("Name").Value : "",
       Age = config.Attribute("Age") != null ? config.Attribute("Age").Value : datatable,
       Sex = config.Attribute("Sex") != null ? config.Attribute("Sex").Value : "",
     });
   IList<ReadingXmlWithLinq> rules = configs.ToList();
   return rules;
}

Now this will return a list of four elements. Thus we will get all the four rows values. Thus rules[0].Name will give “aaaaa” and rules[3].Name will give “ddddd” Now what if I need only those info whose Id is 1. That is Node Attribute value Id. So now this looks little  difficult. But if we are using Linq it is quite simple. Lets see

private IList<ReadingXmlWithLinq> GetXMlList()
        {
            XDocument parentXML = XDocument.Load(xmlPathAddress);
            string node = Employee;
            string IdValue = "1";

            var parentconfigs = from config in parentXML.Descendants(node)
                                where (string)config.Attribute("Id") == IdValue
                                select config;
            string childnode = "Info";
            configs = (from config in parentconfigs.Descendants(childnode)
                       select new ReadingXmlWithLinq
                       {
                           Name = config.Attribute("Name") != null ? config.Attribute("Name").Value : "",
                           Age = config.Attribute("Age") != null ? config.Attribute("Age").Value : datatable,
                           Sex = config.Attribute("Sex") != null ? config.Attribute("Sex").Value : "",
                       });

            IList<ReadingXmlWithLinq> rules = configs.ToList();
            return rules;
        }

Now the above function will return only two values that is Employee ID’s value equal to 1. Thus we can get selective value based on certain criteria or condition. This is pretty simple and easy as compared to the traditional way of handling. 

, , ,

Leave a comment

CRUD Operation (Early Bound Classes) using WCF services in CRM 2011


Working with Early Bound Classes with CRM 2011 WCF Services.

Before starting the development we should see the Services involved

1. IDiscoveryService : The IDiscovery Service is a global service used to determine the Organizations that the system user is a member of, and the endpoint address URL to access the IOrganization service. This is basically used when we have multiple organizations in the same CRM Server and we need to know all the organization and their IOrganization Services URL’s at runtime or  through the code.

For eg: https://{ServerName} /XRMServices/2011/Discovery.svc

2. IOrganizationService : The IOrganization Service is Basically used for accessing the organization data and metadata with the help of the WCF implementation. This is the main service for the operation of all  Create,Update ,Delete,Retrieve  etc.

For eg: https://{ServerName} /XRMServices/2011/Organization.svc

Steps  to be done before Development

  1. Registration of Device using Device Registration Tool Provided in the SDK.

Eg:

C:\>deviceregistration.exe /operation:Register – Go to the location where the exe is there and then run with the following command.

This will register you device and give Device Username and Device Password. This Device Id Username and Password is basically used while generating  the class which is used for the development though early bound class.

The device Username and password is basically used for the Authentication of the Services (mainly for Claim Based Authentication) which we want to use. The CRM 2011 online supports only claim based authentication so the device username and the password is very important and a necessary component for generating the code{class} for using the Organization Service data and metadata.

Note: The Device Username and the password is not necessary in the other form of Authentication like On- Premise, IFD  etc.

  1. Creating the Class using the CrmSvcUtil.exe Tool  which is again the part of the SDK and can be used for generating the Early bound Class. The syntax for using this tool is given below.

For Eg:

CrmSvcUtil.exe /url:https://{servername}/XRMServices/2011/Organization.svc /out:E:\GeneratedCode.cs /username:USERNAME /password:”********” / deviceid:”11yjcvqjo4ynpdoi5dfyo19yth” /devicepassword:”^Va/oCyeCy~Fbbko0fZ~m;lf”

Note: Please replace the USERNAME with the username with which you logs the CRM for the given URL.

After using this tool a class file will be generated which we need to include in our Project for accessing all the entities and data of the Organization.

Sample Code

  1. First create a class that will contain the configuration details which we can use in our code for creating the proxy class. This class will contain all the details about the Authentication ,the Organization URL information ,Device Credentials, user credentials etc.

So let us create a class called ServerConnection  which also contains a class called Configuration which holds the different  variables like Server Address, Organization Name, Discovery URL, Organization URL , Device Credentials, Credentials etc.

public class ServerConnection
        {
            public class Configuration
            {
                //Declare the variables like Discoveryurl,
            }
        }

Now we will create a method called GetServerConfiguration() for defining the variables.

public virtual Configuration GetServerConfiguration()
        {
            config.ServerAddress = "{ServerAddress}";
            config.DiscoveryUri = new Uri(String.Format("https://{0}/XRMServices/2011/Discovery.svc", config.ServerAddress));
            config.DeviceCredentials = GetDeviceCredentials();// only for CRM Online not required for On-Premise and IFD
            config.Credentials = GetUserLogonCredentials();
            string baseurl ="https://{ServerAddress}/XRMServices/2011/Organization.svc";
            Uri uri = new Uri(baseurl);
            config.OrganizationUri = uri;
            if (configurations == null) configurations = new List<Configuration>();
            configurations.Add(config);
            return config;
        }

Here we can find that we are using certain methods like GetDeviceCredentials(),GetUserLogonCredentials(), so we are going to define all those methods now.

protected virtual ClientCredentials GetDeviceCredentials()
        {
            ClientCredentials credential = new ClientCredentials();
            credential.UserName.UserName = "11yjcvqjo4ynpdoi5dfyo19yth";//Give the username that you get after registering the device.
            credential.UserName.Password = "^Va/oCyeCy~Fbbko0fZ~m;lf";// Give the Device Password .
            return credential;
        }

Now we will define the GetUserLogonCredential() for getting the User Credentials

protected virtual ClientCredentials GetUserLogonCredentials()
        {
            ClientCredentials credentials = new ClientCredentials(); ;
            String userName;
            String password;
            userName = "{Windows Live ID Username for logging into CRM.}";
            if (string.IsNullOrWhiteSpace(userName))
            {
            return null;
            }
            password = "Windows Live ID Password.";
            credentials.UserName.UserName = userName;
            credentials.UserName.Password = password;
            return credentials;
        }

After our ServerConnection Class is ready tharn we can Proceed for the Application part where we can use this class for creating a proxy class for talking  to the IOrganization Service through code.

Now we will create a class where we can consume this. Lets create a class called ConsumeIorganization.cs

Now first create a Proxy class for establishing a connection to the IOrganization Service and call this method in the page load or any constructor so that before using the classes of the Organization the proxy is properly created.

public void Run(ServerConnection.Configuration serverConfig)
        {
            try
            {
               using (serviceproxy = new OrganizationServiceProxy(serverConfig.OrganizationUr, serverConfig.HomeRealmUri,
               serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    serviceproxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                    service = (IOrganizationService)serviceproxy;
                }
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
               throw;
            }

         }


Now the next step is to use the class in our project which we have got by the tool [SvcUtil.exe ]. Include the class in our Project and start using to get all the classes of the CRM Organization. By adding this class you can use all the data and metadata in your Project.

So Let’s start using this to consume in our code. In the Below code I have written a method which Creates an Account Record.

public void CreateAccount()
        {
            Account account =new Account();
            account.Name="Sample Account Record Without Service Reference(WCF).";
            account.AccountNumber="10000000000000";
            accountid = service.Create(account);
        }

Note: Here service is the object which we have defined while creating a Proxy Class. So not forget to Declare in the beginning  of the class. You can declare as follows

IOrganizationService service;

OrganizationServiceProxy serviceproxy;

Both are part of the DLL [using Microsoft.Xrm.Sdk,using Microsoft.Xrm.Sdk.Client]   which is provided in the CRM Sdk .

So Now we are all set to run the. After running the Application you will find that a Account Record will be created in the CRM server.

So Its Easy …………………………..Enjoy………………………..!!!!!!!!!!


, , ,

11 Comments