Wednesday, October 02, 2013

Create task in CRM 2011

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Xrm.Sdk.Client;
using System.Windows.Forms;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using System.IO;
using SSB.Xrm;
using Microsoft.Xrm.Sdk.Deployment;


namespace DynamicsTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string dest = "prod";
            string prod = "http://crm/prod/XRMServices/2011/Organization.svc";
            string test = "http://crm/Test/XRMServices/2011/Organization.svc";
            string test2 = "http://crm/Testt/XRMServices/2011/Organization.svc";
            string dev = "http://crm/Dev/XRMServices/2011/Organization.svc";
            string server = "";
            switch (dest)
            {
                case "prod":
                    server = prod;
                    break;
                case "test2":
                    server = test2;
                    break;
                case "test":
                    server = test;
                    break;
                default:
                    server = dev;
                    break;
            }
            Uri organizationUri = new Uri(server);
            Uri homeRealmUri = null;
            ClientCredentials credentials = new ClientCredentials();
            credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
            OrganizationServiceProxy _serviceProxy  = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
            _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
            IOrganizationService _service = (IOrganizationService)_serviceProxy;

            if (!Directory.Exists("Logs"))
            {
                Directory.CreateDirectory("Logs");
            }
            StreamWriter w = new StreamWriter(".\\Logs\\DynamicsTest" + DateTime.Now.ToString("_yyyyMMdd") + ".log", true);

            try
            {
                string[] customers = { "000000XXXXX~C260XXX~Kongekonto - gjsnitt utnyttelse over 95 % siste året"
 };
                foreach (string cust in customers)
                {
                    string[] entry = cust.Split('~');
                    string kundenr = entry[0];
                    string ownerLogin = entry[1];
                    string subject = entry[2];
                    Helper.Log("Processing for customer " + kundenr + " with owner as " + ownerLogin + " ........", w);

                    ConditionExpression con_ce1 = new ConditionExpression("efs_sourcecustomernumber", ConditionOperator.Equal, kundenr);
                    FilterExpression con_fe = new FilterExpression(LogicalOperator.And);
                    con_fe.AddCondition(con_ce1);
                    QueryExpression con_qe = new QueryExpression();
                    con_qe.EntityName = "contact";
                    con_qe.Criteria = con_fe;
                    con_qe.ColumnSet = new ColumnSet("contactid", "efs_sourcecustomernumber");
                    con_qe.PageInfo.ReturnTotalRecordCount = true;
                    EntityCollection con_coll = _service.RetrieveMultiple(con_qe);
                    ConditionExpression own_ce1 = new ConditionExpression("domainname", ConditionOperator.Like, "%" + ownerLogin + "%");
                    FilterExpression own_fe = new FilterExpression(LogicalOperator.And);
                    own_fe.AddCondition(own_ce1);
                    QueryExpression own_qe = new QueryExpression();
                    own_qe.EntityName = "systemuser";
                    own_qe.Criteria = own_fe;
                    own_qe.ColumnSet = new ColumnSet("systemuserid", "domainname");
                    own_qe.PageInfo.ReturnTotalRecordCount = true;
                    EntityCollection own_coll = _service.RetrieveMultiple(own_qe);
                    DateTime today = DateTime.Today.AddMonths(1);
                    DateTime endOfMonth = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));
                    if (con_coll.Entities.Count > 0)
                    {
                        Entity ent = con_coll.Entities[0];
                        Entity task = new Entity();
                        task.LogicalName = "task";
                        OptionSetValue type = new OptionSetValue();
                        type.Value = 867700004; //Incoming
                        EntityReference regarding = new EntityReference();
                        regarding.LogicalName = "contact";
                        regarding.Id = ent.Id;
                        task["ssb_type"] = type;
                        task["description"] = subject;
                        task["scheduledstart"] = DateTime.Now;
                        task["scheduledend"] = endOfMonth;
                        task["owneridtype"] = 8;
                        task["regardingobjectid"] = regarding;
                        task["subject"] = subject;
                        Guid _createdId = _service.Create(task);
                        Helper.Log("Task Created  with Id: " + _createdId.ToString(), w);

                        try
                        {
                            if (own_coll.Entities.Count > 0)
                            {
                                Entity owner = own_coll.Entities[0];
                                Guid _userId = owner.Id;
                                AssignRequest request = new AssignRequest();
                                //request.RequestName
                                request.Assignee = new EntityReference("systemuser", _userId);
                                request.Target = new EntityReference("task", _createdId);
                                _service.Execute(request);
                                Helper.Log("Task successfully assigned to " + ownerLogin, w);
                            }
                            else
                            {
                                Helper.Log("Owner not found with Login: " + ownerLogin, w);
                            }
                        }
                        catch
                        {
                            //Do nothing
                            Helper.Log("Unable to assign task to " + ownerLogin, w, true);
                        }
                    }
                    else
                    {
                        if (con_coll.Entities.Count == 0)
                            Helper.Log("Customer not found with customer number: " + kundenr, w);
                    }
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Helper.Log(ex.Message, w, true);
            }
            finally
            {
                if (w != null)
                    w.Close();
            }
        }

        

    }
}

No comments: