Wednesday, 26 June 2013

Use CRM 2011 web service in Silverlight 5

In the silverlight application add CRM 2011 webservice as Service Reference.

The CRM 2011 organization url will be like below.

http://CRMServer/OrgName/XRMServices/2011/Organization.svc?wsdl

Include the Service reference name in the class where we create the helper methods to get the Iorganizationservice object.

Use below helper methods in the class to your project.

internal static class SilverlightUtility
{
   public static IOrganizationService GetSoapService()
   {
    Uri serviceUrl = CombineUrl(GetServerBaseUrl(),"/XRMServices/2011/Organization.svc/web");
     BasicHttpBinding binding = new BasicHttpBinding(Uri.UriSchemeHttps == serviceUrl.Scheme
     ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.TransportCredentialOnly);
            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.MaxBufferSize = int.MaxValue;
            binding.SendTimeout = TimeSpan.FromMinutes(2);

    return new CrmSdk.OrganizationServiceClient(binding, new EndpointAddress(serviceUrl));
 }

 public static Uri GetServerBaseUrl()
 {
   string serverUrl = (string)GetContext().Invoke("getServerUrl");
  //Remove the trailing forwards slash returned by CRM Online
  //So that it is always consistent with CRM On Premises
  if (serverUrl.EndsWith("/"))serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);
  return new Uri(serverUrl);
 }

 public static Uri CombineUrl(Uri baseValue, string value)
 {
    if (null == baseValue)
    {
      throw new ArgumentNullException("baseValue");
    }
    else if (string.IsNullOrEmpty(value))
    {
      return baseValue;
    }

    //Ensure that a double '/' is not being added
    string newValue = baseValue.AbsoluteUri;
    if (!newValue.EndsWith("/", StringComparison.Ordinal))
    {
      //Check if there is a character at the beginning of value
      if (!value.StartsWith("/", StringComparison.Ordinal))
      {
         newValue += "/";
      }
    }
    else if (value.StartsWith("/", StringComparison.Ordinal))
    {
      value = value.Substring(1);
    }

    //Create the combined URL
    return new Uri(newValue + value);
 }

 #region Private Methods
 private static ScriptObject GetContext()
 {
   ScriptObject xrmProperty = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
   if (null == xrmProperty)
   {
    //It may be that the global context should be used
     try
     {
       ScriptObject globalContext = (ScriptObject)HtmlPage.Window.Invoke("GetGlobalContext");
       return globalContext;
     }
     catch (System.InvalidOperationException)
     {
       throw new InvalidOperationException("Property \"Xrm\" is null and the Global Context 
       is not available.");
     }

   }

   ScriptObject pageProperty = (ScriptObject)xrmProperty.GetProperty("Page");
   if (null == pageProperty)
   {
       throw new InvalidOperationException("Property \"Xrm.Page\" is null");
   }

   ScriptObject contextProperty = (ScriptObject)pageProperty.GetProperty("context");
   if (null == contextProperty)
   {
     throw new InvalidOperationException("Property \"Xrm.Page.context\" is null");
   }

   return contextProperty;
 }
 #endregion


}

 Now you can access the GetSoapService method to get the IOrganization method.

IOrganizationService service = SilverlightUtility.GetSoapService();

Tuesday, 25 June 2013

CRM 2011 Query Expression samples

Query Expression Sample 1

// Create the ConditionExpression.
ConditionExpression condition1 = new ConditionExpression("contractid"ConditionOperator.Equal, entityId);

 // Create the FilterExpression.
 FilterExpression filter = new FilterExpression();

// Set the properties of the filter.
 filter.FilterOperator = LogicalOperator.And;
 filter.Conditions.Add(condition1);

// Create the QueryExpression object.
QueryExpression query = new QueryExpression();

// Set the properties of the QueryExpression object.
query.EntityName = "contractdetail";
query.ColumnSet = new ColumnSet(true);
query.Criteria = filter;

//Build Retrieve request
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
             
//Retrieve SLARuleTemplates
RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(retrieve);


Query Expression Sample(Link Entity) 2

//Create a query expression specifying the link entity alias and the columns of the link entity that you want to return
QueryExpression qe = new QueryExpression();
qe.EntityName = "account";
qe.ColumnSet = new ColumnSet();
qe.ColumnSet.Columns.Add("name");

qe.LinkEntities.Add(new LinkEntity("account", "contact", "primarycontactid", "contactid", JoinOperator.Inner));
qe.LinkEntities[0].Columns.AddColumns("firstname", "lastname");
qe.LinkEntities[0].EntityAlias = "primarycontact";

EntityCollection ec = _orgService.RetrieveMultiple(qe);


Query Expression Sample( One-To-Many Relationship)

// Construct query
// Condition where task attribute equals account id.
ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "regardingobjectid";
condition.Operator = ConditionOperator.Equal;
condition.Values.Add(acctId.ToString());

//Create a column set.
ColumnSet columns = new ColumnSet("subject");

// Create query expression.
QueryExpression query1 = new QueryExpression();
query1.ColumnSet = columns;
query1.EntityName = "task";
query1.Criteria.AddCondition(condition);

EntityCollection result1 = _serviceProxy.RetrieveMultiple(query1);

Page Large Result Sets with Query Expression

//  Query using the paging cookie.
// Define the paging attributes.
// The number of records per page to retrieve.
int fetchCount = 3;
// Initialize the page number.
int pageNumber = 1;
// Initialize the number of records.
int recordCount = 0;

// Define the condition expression for retrieving records.
ConditionExpression pagecondition = new ConditionExpression();
pagecondition.AttributeName = "address1_stateorprovince";
pagecondition.Operator = ConditionOperator.Equal;
pagecondition.Values.Add("WA");

// Define the order expression to retrieve the records.
OrderExpression order = new OrderExpression();
order.AttributeName = "name";
order.OrderType = OrderType.Ascending;

// Create the query expression and add condition.
QueryExpression pagequery = new QueryExpression();
pagequery.EntityName = "account";
pagequery.Criteria.AddCondition(pagecondition);
pagequery.Orders.Add(order);
pagequery.ColumnSet.AddColumns("name", "address1_stateorprovince", "emailaddress1", "accountid");

// Assign the pageinfo properties to the query expression.
pagequery.PageInfo = new PagingInfo();
pagequery.PageInfo.Count = fetchCount;
pagequery.PageInfo.PageNumber = pageNumber;
// The current paging cookie. When retrieving the first page,
// pagingCookie should be null.
pagequery.PageInfo.PagingCookie = null;

Console.WriteLine("#\tAccount Name\t\t\tEmail Address");

  while (true)
  {
    // Retrieve the page.
     EntityCollection results = _serviceProxy.RetrieveMultiple(pagequery);

     if (results.Entities != null)
     {
        // Retrieve all records from the result set.
         foreach (Account acct in results.Entities)
         {
           Console.WriteLine("{0}.\t{1}\t\t{2}",++recordCount,acct.EMailAddress1,                       
           acct.Name);
         }
    }

    // Check for more records, if it returns true.
    if (results.MoreRecords)
    {
       // Increment the page number to retrieve the next page.
       pagequery.PageInfo.PageNumber++;
       // Set the paging cookie to the paging cookie returned from current results.
       pagequery.PageInfo.PagingCookie = results.PagingCookie;
    }
    else
    {
       // If no more records are in the result nodes, exit the loop.
       break;
    }
 }

Multiple condition with Query Expression.


// Create the ConditionExpression.
ConditionExpression condition1 = new ConditionExpression("new_contractserviceid", ConditionOperator.Equal, contractserviceid);
ConditionExpression condition2 = new ConditionExpression("new_componenttemplateid", ConditionOperator.Equal, componentTemplate.Get(executionContext).Id);

// Create the FilterExpression.
FilterExpression filter = new FilterExpression();

// Set the properties of the filter.
filter.FilterOperator = LogicalOperator.And;
filter.Conditions.Add(condition1);
filter.Conditions.Add(condition2);

// Create the QueryExpression object.
QueryExpression query = new QueryExpression();

// Set the properties of the QueryExpression object.
query.EntityName = "new_component";
query.ColumnSet = new ColumnSet(true);
query.Criteria = filter;

//Build Retrieve request
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
          
//Retrieve SLARuleTemplates
RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(retrieve);






CRM 2011 Custom Workflow sample

 public class TestCodeActivity {
 
#region Input Properties

[Input("Task Subject")]
[Default("Empty Subject")]
public InArgument<string> TaskSubject { getset; }

[Input("Contract Lookup")]
[ReferenceTarget("contract")]
public InArgument<EntityReference>startContract { get; set;}
[Input("Contract Service Type Lookup")]
[ReferenceTarget("new_contractservicetype")]
public InArgument<EntityReference>contractServiceType { get; set; }
[Input("Component Template Lookup")]
[ReferenceTarget("new_componenttemplate")]
public InArgument<EntityReference>componentTemplate { get; set; }
[Output("Target Component")]
[ReferenceTarget("new_component")]
public OutArgument<EntityReference>targetComponent { get; set;}
[Output("Is Component Found Flag")]
public OutArgument<Boolean>IsFoundFlag { get; set;}

[Input("Activity Type")]
[AttributeTarget("appointment", "new_type")]
public InArgument<OptionSetValue>ActvType { get; set;}

[Input("End Date Time")]
public InArgument<DateTime>endDate { get; set;}
#endregion
 protected override void Execute(CodeActivityContext context) 
 {
 
      //Create the IWorkflowContext and the
     //IOrganizationService for communication with CRM
    IWorkflowContext workflowContext =context.GetExtension<IWorkflowContext>();
    IOrganizationServiceFactory Factory =context.GetExtension<IOrganizationServiceFactory>();
    IOrganizationService service =Factory .CreateOrganizationService(workflowContext.UserId);
   //Retrieve data from InputParameter 
    string newSubject = TaskSubject.Get<string>(context);
 
   //Create the new task object (in memory)
   Entity newTask = new Entity("task");
   newTask["subject"] = newSubject;
   newTask["regardingobjectid"] =new EntityReference("account", workflowContext.PrimaryEntity   Id);
 
   //Create task in CRM
   Guid taskId = service.Create(newTask);
  }
}



CRM 2011 Sdk RetrieveRequest sample

RetrieveRequest will retrive single refence entity based on the record guid.

//Create the target
        EntityReference retrieveTarget = new EntityReference();
                retrieveTarget.Id = entityId;
                retrieveTarget.LogicalName = entityType;

                //Create a request
                RetrieveRequest retrieveRequest = new RetrieveRequest();
                retrieveRequest.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(true);
                retrieveRequest.Target = retrieveTarget;

                //Execute the request
                RetrieveResponse retrieveResponse = (RetrieveResponse)service.Execute(retrieveRequest);

                //Retrieve the Loan Application Entity
                return (Entity)retrieveResponse.Entity;

Tuesday, 18 June 2013

CRM 2011 Plugin get secure and unsecure config information

In Crm 2011 plugin when we register the plugin we can give secure and unsecure config informations.

When the plugin fires we can receive config informations automatically in the plugin constructor method which should be 2 parameters constructor.

Here you can see my PluginTest class has one constructior which will called by CRM automatically.

 public class PluginTest : IPlugin

 {

   public PluginTest(string unsecureConfig, string secureConfig)

   {
       XmlDocument doc = new XmlDocument();
       doc.LoadXml(unsecureConfig);
   }
}

Consuming a WCF from JavaScript

This is just to give simple steps to call a WCF from client side.

1) Browse the web service URL. Then you know your web service is available. You will see a page like below one.

2) Now click relevant link in the page. Search for SOAPAction tag relevant to method you wish to use, So that you know the SOAPAction value.

3) Now get the request SOAP envelops.

a) If you have the code of WCF service run the code in Visial Studio that results a pop up of WCF Test Client. Then double click the method you need and pass some values to parameters shown in Formatted tab. Then click the XML tab to grab the Request SOAP envelop. Just omit the Header Tag from the XML you get here.

b) If the web service is provided by some other party, you can simply request the soap envelops.

4) Now we got everything we need, call the relevant method of the Web Service through below code. xmlHttp.ResponseXML will return the result.
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open('POST', 'http://localhost:5555/ISV/PricingWCF/WcfIntermediateService.Service1.svc', false);
        xmlhttp.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
        xmlhttp.setRequestHeader('SOAPAction', 'http://tempuri.org/IService1/GetSalesRate');

        var data = '';
        data += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">';
        data += '<s:Body>';
        data += '<GetSalesRate xmlns="http://tempuri.org/">';
        data += '<productcode>AEC0023678</productcode>';
        data += '</GetSalesRate>';
        data += '</s:Body>';
        data += '</s:Envelope>';

        xmlhttp.send(data);


How to call External WCF Service within CRM 2011 Plugins

Step 1: Build and Publish the WCF Service

Step 2: Deploy the WCF Service


Step 3: Create WCF client


Create a WCF client using  ServiceModel Metadata Utility Tool (Svcutil.exe) by using following steps:


On the Start menu click All Programs, and then click Visual Studio 2010. Click Visual Studio Tools and then click Visual Studio 2010 Command Prompt.


Navigate to the directory where you want to place the client code.


Use the command-line tool ServiceModel Metadata Utility Tool (Svcutil.exe) with the appropriate switches to create the client code. The following example generates a code file and a configuration file for the service.


svcutil.exe /language:cs /out:TaxServiceClient.cs http://192.168.124.26:81/TaxProductionService


Step 4: Write Plugin to consume external WCF Service


Add the above generated .CS class into the plugin solution. In Visual Studio, right-click the client project in Solution Explorer and select Add and then Existing Item. Select the TaxServiceClient.cs file generated in the preceding step.

Open the plugin.cs class from the solution. And call the WCF client using channel factory.

#region Calling WCF Service


BasicHttpBinding myBinding = new BasicHttpBinding();myBinding.Name = “BasicHttpBinding_IPOCService”;myBinding.Security.Mode = BasicHttpSecurityMode.None;myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;EndpointAddress endPointAddress = new EndpointAddress(“http://192.168.124.26:81/TaxProductionService.svc“);ChannelFactory<IPOCService> factory = new ChannelFactory<IPOCService>(myBinding, endPointAddress);IPOCService channel = factory.CreateChannel();taxAmount = channel.GetCalculatedTaxValue(unitPrice);factory.Close();


#endregion


Step 5: Register the Plugin using registration tool.


You can also download a sample code from below link:

http://code.msdn.microsoft.com/How-to-call-External-WCF-42c4490d