HTML Dropdown

Thursday, 16 June 2016

Close open activities in CRM 2013


1. Generate early bound types


Run the CrmSvcUtil.exe tool, with the “Microsoft.Xrm.Client.CodeGeneration” extension, to generate your entity classes and service contexts. The following is an example command to create a file called Xrm.cs that points at an instance of Microsoft Dynamics CRM. Note that the Microsoft.Xrm.Client.CodeGeneration.dll file must be in the same directory as the CrmSvcUtil.exe file, or in the system global assembly cache, when you run this command. The first command shown is for an on-premises organization. The second command is for a CRM Online organization. Both commands should be executed as a single command line with no line breaks.

CrmSvcUtil.exe

/codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration"

/out:Xrm.cs /url:https://<mydomain>.api.crm.dynamics.com/XRMServices/2011/Organization.svc

/username:<myusername>@<mydomain>.onmicrosoft.com /password:<mypassword> /namespace:Xrm /serviceContextName:XrmServiceContext





2. Create a Console Application project in Visual studio 2012.





3. Add the following references from the SDK\bin folder. You can skip this step and the next by simply installing the Microsoft.CrmSdk.Extensions NuGet package.

  • AntiXSSLibrary.dll
  • Microsoft.Crm.Sdk.Proxy.dll
  • Microsoft.Xrm.Client.dll
  • Microsoft.Xrm.Portal.dll
  • Microsoft.Xrm.Portal.Files.dll
  • Microsoft.Xrm.Sdk.dll



    4.Add the following references from .NET.

    • System.IdentityModel.dll
    • Microsoft.ServiceBus.dll
    • System.Data.Services.dll
    • System.Data.Services.Client.dll
    • System.Runtime.Serialization.dll
Note: - To install Microsoft.ServiceBus.dll add following: Project -> Manage nugget package Manager or Tools -> Library Package Manager Console
Install-Package WindowsAzure.ServiceBus
 
5.Make sure the console project specifies .NET Framework 4.5.2 as the target framework and not .NET Framework 4.5.2 Client Profile. Check the properties of the project by selecting the ConsoleApplication1 project in Solution Explorer and clicking Alt-Enter.
Right Click ConsoleApplication1  -> Properties

6.Right-click the project in Visual Studio, click Add, and then click Existing Item.
7.Select the “Xrm.cs” file that you created when you generated the early bound types.
8.Right-click your project again, click Add, and then click New Item.
9.Select Application Configuration File from the options and then click Add.
10.Edit the App.config configuration file with your specific connection string.
                                   
XML
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="microsoft.xrm.client" type="Microsoft.Xrm.Client.Configuration.CrmSection, Microsoft.Xrm.Client"/>
  </configSections>
  <connectionStrings>   <add name="Xrm" connectionString="Server=http://crmserver/contoso; Domain=CONTOSO; Username=Administrator;Password=pass@word1"/></connectionStrings>
  <microsoft.xrm.client>
    <contexts default="Xrm">
      <add name="Xrm" type="Xrm.XrmServiceContext, Xrm" connectionStringName="Xrm"/>
    </contexts>
  </microsoft.xrm.client>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
  </startup>
</configuration>

11. Add a using statement to the namespace that you used in Step 1 when you created the project (for this example “Xrm”).
using System;
using System.Linq;
using System.Threading.Tasks;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml;
using System.IO;
using System.Linq;
 
 
//earlybound types
using Xrm;
 
 
// These namespaces are found in the Microsoft.Xrm.Sdk.dll assembly
// found in the SDK\bin folder.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
 
// These namespaces are found in the Microsoft.Sharepoint.Client.dll assembly
// found in the SDK\bin folder.
 
using Microsoft.Win32;
using Microsoft.SharePoint.Client;
 
 
 
// This namespace is found in Microsoft.Crm.Sdk.Proxy.dll and Microsoft.Crm.Sdk.Workflow.dll assembly
// found in the SDK\bin folder.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Crm.Sdk.Messages;
 
 
// These namespaces are found in the System.Data assembly
// found in the .NET
using System.Data;
using System.Data.Services;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Net;

 
12.Declare the Run Method as below:-
  1.  
13.Add the following code in Run method.
  CreateLog("Execution Started");
                //Get CRM service context from app.config
                var xrm = new XrmServiceContext("Xrm");
             //   var xrm = new XrmServiceContext("Xrm");
 
                // CONFIGURE INPUT PARAMETERS HERE.
                //***********************************************************************//
                //***********************************************************************//
                int fetchCount = 5;
                int desiredStateCode = 1;
                int desiredStatusCode = 5;
                String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='task'>
                                    <attribute name='activityid' />
                                    <order attribute='subject' descending='false' />
                                    <filter type='and'>
                                      <condition attribute='subject' operator='eq' value='Account number is missing' />
                                    </filter>
                                  </entity>
                                </fetch>";
                //***********************************************************************//
                //***********************************************************************//
                // Initialize the page number.
                int pageNumber = 1;
                // Initialize the number of records.
                //int recordCount = 0;
                // Specify the current paging cookie. For retrieving the first page,
                // pagingCookie should be null.
                string pagingCookie = null;
 
                while (true)
                    {
                    // Build fetchXml string with the placeholders.
                    string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);
 
                    // Excute the fetch query and get the xml result.
                    RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
                    {
                        Query = new FetchExpression(xml)
                    };
 
                    EntityCollection activityResults = ((RetrieveMultipleResponse)xrm.Execute(fetchRequest1)).EntityCollection;
                    if (activityResults != null)
                        {
                        if (activityResults.Entities.Count > 0)
                            {
 
                            foreach (Entity activity in activityResults.Entities)
                                {
                                Guid activityId = activity.Id;
                                try
                                    {
                                    SetStateRequest setStateRequest = new SetStateRequest();
 
                                    // In my case i'm Cancelling Task Activity
                                    setStateRequest.EntityMoniker = new EntityReference(activity.LogicalName, activityId);
 
                                    // Set the State and Status OptionSet Values to Cancelled.
                                    setStateRequest.State = new OptionSetValue(desiredStateCode);
                                    setStateRequest.Status = new OptionSetValue(desiredStatusCode);
 
                                    // Execute the Response
                                    SetStateResponse setStateResponse = (SetStateResponse)xrm.Execute(setStateRequest);
                                    Console.WriteLine(activityId + ", Completed Sucessfully");
                                    CreateLog(activityId + ", Completed Sucessfully");
                                    }
                                catch (Exception ex)
                                    {
                                    Console.WriteLine(activityId + ", Error " + ex.Message.ToString());
                                    CreateLog(activityResults.Entities.Count + "," + activityId + ", Error ," + ex.Message.ToString());
                                    }
 
                                }
                            }
                        }
                    // Check for morerecords, if it returns 1.
                    if (activityResults.MoreRecords)
                        {
                            Console.WriteLine(pageNumber * fetchCount + " records Processed");
                            CreateLog(pageNumber * fetchCount + ", records Processed");
                            // Increment the page number to retrieve the next page.
                            pageNumber++;
                        }
                    else
                        {
                            // If no more records in the result nodes, exit the loop.
                            break;
                        }
                    }
                CreateLog("Execution Ended Successfully");
               Console.ReadLine();
 
 
 
14. Add the following Code in the class file.
 
            public string CreateXml(string xml, string cookie, int page, int count)
                {
                StringReader stringReader = new StringReader(xml);
                XmlTextReader reader = new XmlTextReader(stringReader);
 
                // Load document
                XmlDocument doc = new XmlDocument();
                doc.Load(reader);
 
                return CreateXml(doc, cookie, page, count);
                }
 
            public string CreateXml(XmlDocument doc, string cookie, int page, int count)
                {
                XmlAttributeCollection attrs = doc.DocumentElement.Attributes;
 
                if (cookie != null)
                    {
                    XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
                    pagingAttr.Value = cookie;
                    attrs.Append(pagingAttr);
                    }
 
                XmlAttribute pageAttr = doc.CreateAttribute("page");
                pageAttr.Value = System.Convert.ToString(page);
                attrs.Append(pageAttr);
 
                XmlAttribute countAttr = doc.CreateAttribute("count");
                countAttr.Value = System.Convert.ToString(count);
                attrs.Append(countAttr);
 
                StringBuilder sb = new StringBuilder(1024);
                StringWriter stringWriter = new StringWriter(sb);
 
                XmlTextWriter writer = new XmlTextWriter(stringWriter);
                doc.WriteTo(writer);
                writer.Close();
 
                return sb.ToString();
                }
 
            public static void CreateLog(string logText)
                {
                StreamWriter log;
                string date1 = DateTime.Now.ToShortDateString();
                string today = date1.Replace("/", "-") + ".txt";
                if (!System.IO.File.Exists(@"C:\Temp\" + today))
                    {
                    log = new StreamWriter(@"C:\Temp\" + today);
                    }
                else
                    {
                    log = System.IO.File.AppendText(@"C:\Temp\" + today);
                    }
                log.WriteLine(DateTime.Now + "," + logText);
                log.Close();
                }

 
15. Testing: Now go to advance find search like below query and click on result
16. Testing:




No comments:

Post a Comment