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