There is a method named ExecuteWorkflowRequest using which we can execute our workflow programmatically. We had a requirement to find all the opportunities which haven’t been modified for past 30 days and to decrease their probability attribute value by 10.
Now the thing over here was that there wasn’t any specific event against which we could have fired the above workflow. So we thought of writing an application which than we could scheduled, which will periodically run the above workflow
This is how we implemeneted it within a windows application
private void Form1_Load(object sender, EventArgs e){
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.OrganizationName = “organizationName”;
//0 – AD
//1 – Passport
//2 – Form Authentication
token.AuthenticationType = 0;
CrmService crmService = new CrmService();
crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
crmService.CrmAuthenticationTokenValue = token;
crmService.Url = “http://servername:port/mscrmservices/2007/crmservice.asmx”;
try{
// Create an ExecuteWorkflow request.
ExecuteWorkflowRequest request = new ExecuteWorkflowRequest();
//Assign the ID of the workflow you want to execute to the request.
// use this query to get the id select parentworkflowid,name,* from dbo.Workflow
// id is the parentworkflowid
request.WorkflowId = new Guid(“21B9528D-D13D-4B93-9F91-FA7468D3C82C”);
// We want to run it against all the opportunity which are in open state
ArrayList OpportunityGuids = GetOpportunityGuids(crmService);
foreach (String oppGuid in OpportunityGuids){
//Assign the ID of the entity to execute the workflow on to the request.
request.EntityId = new Guid(oppGuid);
ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)crmService.Execute(request);}
// Execute the workflow. }
catch (SoapException ex){
// write in log}
catch (Exception ex){
// write in log} }
private ArrayList GetOpportunityGuids(CrmService crmService){
// using QueryByAttribute to retrieve all the opportunity having statuscode as 1 i.e. Open
QueryByAttribute myOppQuery = new QueryByAttribute();
myOppQuery.Attributes = new String[] { “statuscode” };
myOppQuery.Values = new String[] {“1”};
ColumnSet myCols = new ColumnSet();
myOppQuery.ColumnSet = myCols;
myOppQuery.EntityName = EntityName.opportunity.ToString();
WindowsFormsApplication2.CrmSdk.BusinessEntityCollection myOppCollection= crmService.RetrieveMultiple(myOppQuery);
ArrayList opportunityGuids = new ArrayList();
foreach (WindowsFormsApplication2.CrmSdk.BusinessEntity opp in myOppCollection.BusinessEntities ){
opportunity myOpp = (opportunity)opp;
opportunityGuids.Add(myOpp.opportunityid.Value.ToString()); }
return opportunityGuids;
}
Bye ..
