Example #1
0
        private List <Guid> CreateRecords(EntityTemplate entityTemplate,
                                          List <AttributeTemplate> attributes,
                                          dynamic mockarooDataSet)
        {
            var entity = new Entity(entityTemplate.Name);
            var ids    = new List <Guid>( );

            foreach (IDictionary <string, object> mockaroodata in mockarooDataSet)
            {
                var createRecord = false;
                for (var i = 0; i < attributes.Count; i++)
                {
                    if (mockaroodata.ContainsKey(attributes[i].Name))
                    {
                        createRecord = true;
                        entity[attributes[i].Name] = CastStringToObject(attributes[i], mockaroodata[attributes[i].Name].ToString( ));
                    }
                    else if (attributes[i].AttMetadata.AttributeType.ToString( ) == "Picklist")
                    {
                        createRecord = true;
                        entity[attributes[i].Name] = CastStringToObject(attributes[i], string.Empty);
                    }
                }
                if (createRecord)
                {
                    ids.Add(CrmService.Create(entity));
                }
            }

            return(ids);
        }
Example #2
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a new recurring appointment.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create a contact
            Contact newContact = new Contact
            {
                FirstName     = "Lisa",
                LastName      = "Andrews",
                EMailAddress1 = "*****@*****.**"
            };

            _contactId = service.Create(newContact);
            Console.WriteLine("Created contact: {0}.", newContact.FirstName + " " + newContact.LastName);

            // Create ab activity party
            ActivityParty requiredAttendee = new ActivityParty
            {
                PartyId = new EntityReference(Contact.EntityLogicalName, _contactId)
            };

            // Create an appointment
            Appointment newAppointment = new Appointment
            {
                Subject           = "Test Appointment",
                Description       = "Test Appointment",
                ScheduledStart    = DateTime.Now.AddHours(1),
                ScheduledEnd      = DateTime.Now.AddHours(2),
                Location          = "Office",
                RequiredAttendees = new ActivityParty[] { requiredAttendee }
            };

            _appointmentId = service.Create(newAppointment);
            Console.WriteLine("Created {0}.", newAppointment.Subject);
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            //Define the email template to create.
            Template emailTemplate = new Template
            {
                Title            = "An example email template",
                Subject          = "This is an example email.",
                IsPersonal       = false,
                TemplateTypeCode = "lead",

                //1033 is the code for US English - you may need to change this value
                //depending on your locale.
                LanguageCode = 1033
            };

            _emailTemplateId = service.Create(emailTemplate);

            for (int i = 0; i < 3; i++)
            {
                ActivityMimeAttachment attachment = new ActivityMimeAttachment
                {
                    Subject        = String.Format("Attachment {0}", i),
                    FileName       = String.Format("ExampleAttachment{0}.txt", i),
                    Body           = "Some Text",
                    ObjectId       = new EntityReference(Template.EntityLogicalName, _emailTemplateId),
                    ObjectTypeCode = Template.EntityLogicalName
                };

                _templateAttachmentIds.Add(service.Create(attachment));
            }

            Console.WriteLine("An email template and {0} attachments were created.", _templateAttachmentIds.Count);

            return;
        }
Example #4
0
        //creates a contact entity and adds it to the crm
        public Entity CreateContactEntity(Contact contact, out Guid c_guid)
        {
            //create an entity by entity id
            Entity contactEntity = new Entity("contact");

            //add attributes to the enitity
            contactEntity.Attributes.Add("firstname", contact.firstName);
            contactEntity.Attributes.Add("lastname", contact.lastName);
            //contactEntity.Attributes.Add("birthdate", contact.birthday);
            contactEntity.Attributes.Add("new_ssn", contact.social);
            contactEntity.Attributes.Add("gendercode", new OptionSetValue(contact.gender));
            contactEntity.Attributes.Add("familystatuscode", new OptionSetValue(contact.maritalStatus));

            contactEntity.Attributes.Add("address1_country", contact.country);
            contactEntity.Attributes.Add("address1_stateorprovince", contact.state);
            contactEntity.Attributes.Add("address1_city", contact.city);
            contactEntity.Attributes.Add("address1_line1", contact.street);
            contactEntity.Attributes.Add("address1_line2", contact.apt);
            //contactEntity.Attributes.Add("address1_telephone1", contact.phone);
            //contactEntity.Attributes.Add("emailaddress1", contact.email);

            c_guid = service.Create(contactEntity);

            return(contactEntity);
        }
Example #5
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            Console.WriteLine("Creating contacts records...");

            var emailContact1 = new Contact()
            {
                FirstName     = "Adam",
                LastName      = "Carter",
                EMailAddress1 = "*****@*****.**"
            };

            // Create the contact1.
            _contactsIds.Add(service.Create(emailContact1));
            Console.WriteLine("Contact1 created.");

            var emailContact2 = new Contact()
            {
                FirstName     = "Adina",
                LastName      = "Hagege",
                EMailAddress1 = "*****@*****.**"
            };

            // Create the contact2.
            _contactsIds.Add(service.Create(emailContact2));
            Console.WriteLine("Contact2 created.");
        }
Example #6
0
        public void CheckPhoneCallHistory()
        {
            string crmCon = ConfigurationManager.ConnectionStrings["crm"].ConnectionString;

            using (CrmServiceClient svc = new CrmServiceClient(crmCon))
            {
                Contact c = new Contact();
                c.FirstName   = "Wael";
                c.LastName    = Guid.NewGuid().ToString();
                c.MobilePhone = new Random().Next(100000000, 200000000).ToString();

                c.Id = svc.Create(c);

                PhoneCall p = new PhoneCall();
                p.RegardingObjectId = c.ToEntityReference();
                p.PhoneNumber       = c.MobilePhone;

                p.Id = svc.Create(p);

                using (var ctx = new XrmServiceContext(svc))
                {
                    var exists = (from ph in ctx.CreateQuery <ultra_phonecallhistory>()
                                  where ph.ultra_contactid.Id == c.Id
                                  where ph.ultra_phonenumber == c.MobilePhone
                                  select ph).FirstOrDefault() != null;

                    Assert.IsTrue(exists);
                }
            }
        }
Example #7
0
        private Guid RegisterPluginType(Entity pluginEntity, TypeInfo plugin)
        {
            var fetchData = new
            {
                typename = plugin.FullName
            };
            var fetchXml = $@"
<fetch>
  <entity name='plugintype'>
    <attribute name='plugintypeid' />
    <filter type='and'>
      <condition attribute='typename' operator='eq' value='{fetchData.typename}'/>
    </filter>
  </entity>
</fetch>";
            var rows     = crmServiceClient.RetrieveMultiple(new FetchExpression(fetchXml));

            if (rows.Entities.Count == 0)
            {
                var pluginType = new Entity("plugintype")
                {
                    ["name"]             = plugin.FullName,
                    ["pluginassemblyid"] = new EntityReference("pluginassembly", Guid.Parse(pluginEntity["pluginassemblyid"].ToString())),
                    ["typename"]         = plugin.FullName,
                    ["friendlyname"]     = plugin.FullName
                };
                CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorRed, " Registering", CliLog.ColorGreen, " Type: ", CliLog.ColorCyan, $"{plugin.FullName}");
                return(crmServiceClient.Create(pluginType));
            }
            else
            {
                return(rows.Entities[0].Id);
            }
        }
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create an account record named Fourth Coffee.
            var account = new Account
            {
                Name          = "Fourth Coffee",
                AccountNumber = "ACC005"
            };

            accountId = service.Create(account);
            Console.Write("Account {0} {1} created, ", account.Name, account.AccountNumber);

            // Create a duplicate detection rule
            var accountDuplicateRule = new DuplicateRule
            {
                Name               = "DuplicateRule: Accounts with the same Account Number",
                BaseEntityName     = "account",
                MatchingEntityName = "account"
            };

            ruleId = service.Create(accountDuplicateRule);

            // Create a duplicate detection rule condition
            DuplicateRuleCondition accountDupCondition = new DuplicateRuleCondition
            {
                BaseAttributeName     = "accountnumber",
                MatchingAttributeName = "accountnumber",
                OperatorCode          = new OptionSetValue(0), // Exact Match.
                RegardingObjectId     = new EntityReference(DuplicateRule.EntityLogicalName, ruleId)
            };
            Guid conditionId = service.Create(accountDupCondition);

            Console.Write("'{0}' created, ", accountDuplicateRule.Name);

            // Execute the publish request.
            var response =
                (PublishDuplicateRuleResponse)service.Execute(new PublishDuplicateRuleRequest()
            {
                DuplicateRuleId = ruleId
            });

            // When the publishDuplicateRule request returns, the state of the rule will still be "Publishing" (StatusCode = 1).
            // we need to wait for the publishing operation to complete, so we keep polling the state of the
            // rule until it becomes "Published" (StatusCode = 2).
            int i             = 0;
            var retrievedRule =
                (DuplicateRule)service.Retrieve(DuplicateRule.EntityLogicalName, ruleId, new ColumnSet(new String[] { "statuscode" }));

            while (retrievedRule.StatusCode.Value == 1 && i < 20)
            {
                i++;
                System.Threading.Thread.Sleep(1000);
                retrievedRule =
                    (DuplicateRule)service.Retrieve(DuplicateRule.EntityLogicalName, ruleId, new ColumnSet(new String[] { "statuscode" }));
            }

            Console.Write("published.\n");
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create source queue and destination queue.
        /// Create a letter  entity.
        /// Add letter  entity to source queue.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            var QueueViewType = new
            {
                Public  = 0,
                Private = 1
            };
            //Create new queues and store their returned GUIDs in variables for later use.
            Queue sourceQueue = new Queue
            {
                Name          = "Source Queue",
                Description   = "This is an example queue.",
                QueueViewType = new OptionSetValue(QueueViewType.Private)
            };

            _sourceQueueId = service.Create(sourceQueue);
            Console.WriteLine("Created {0}", sourceQueue.Name);

            Queue destinationQueue = new Queue
            {
                Name          = "Destination Queue",
                Description   = "This is an example queue.",
                QueueViewType = new OptionSetValue(QueueViewType.Private)
            };

            _destinationQueueId = service.Create(destinationQueue);
            Console.WriteLine("Created {0}", destinationQueue.Name);


            // Create a letter  entity.
            Letter newLetter = new Letter
            {
                Description = "Example Letter"
            };

            _letterId = service.Create(newLetter);
            Console.WriteLine("Created {0}", newLetter.Description);

            // Use AddToQueue message to add an  entity into a queue, which will associate
            // the letter with the first queue.
            AddToQueueRequest addToSourceQueue = new AddToQueueRequest
            {
                DestinationQueueId = _sourceQueueId,
                Target             = new EntityReference(Letter.EntityLogicalName, _letterId)
            };

            service.Execute(addToSourceQueue);
            Console.WriteLine("Added letter record to {0}", sourceQueue.Name);

            // Retrieve/create a user record for assigning the queue item to the user's
            // queue.
            _userId = SystemUserProvider.RetrieveSalesManager(service);



            return;
        }
        /// <summary>
        /// Create some account records to retrieve duplicates
        /// </summary>
        private static void CreateAccountRecords(CrmServiceClient service)
        {
            var crmAccount = new Account {
                Name = "Microsoft"
            };

            accountId1 = service.Create(crmAccount);
            accountId2 = service.Create(crmAccount);
            Console.WriteLine(String.Concat("Creating duplicate records:\n\taccount 1 - ",
                                            accountId1.Value, "\n\taccount 2 - ", accountId2.Value));
        }
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create an account.
            Account account = new Account
            {
                Name = "Fourth Coffee",
            };

            _accountId = service.Create(account);
            Console.WriteLine("Created a sample account: {0}.", account.Name);

            // Define the body and subject of the email template in XML format.
            string bodyXml =
                "<?xml version=\"1.0\" ?>"
                + "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">"
                + "<xsl:output method=\"text\" indent=\"no\"/><xsl:template match=\"/data\">"
                + "<![CDATA["
                + "This message is to notify you that a new account has been created."
                + "]]></xsl:template></xsl:stylesheet>";

            string subjectXml =
                "<?xml version=\"1.0\" ?>"
                + "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">"
                + "<xsl:output method=\"text\" indent=\"no\"/><xsl:template match=\"/data\">"
                + "<![CDATA[New account notification]]></xsl:template></xsl:stylesheet>";

            string presentationXml =
                "<template><text><![CDATA["
                + "This message is to notify you that a new account has been created."
                + "]]></text></template>";

            string subjectPresentationXml =
                "<template><text><![CDATA[New account notification]]></text></template>";

            // Create an e-mail template.
            Template template = new Template
            {
                Title                  = "Sample E-mail Template for Account",
                Body                   = bodyXml,
                Subject                = subjectXml,
                PresentationXml        = presentationXml,
                SubjectPresentationXml = subjectPresentationXml,
                TemplateTypeCode       = Account.EntityLogicalName,
                LanguageCode           = 1033, // For US English.
                IsPersonal             = false
            };

            _templateId = service.Create(template);
            Console.WriteLine("Created {0}.", template.Title);
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a queue instance.
        /// Create a phone call activity instance.
        /// Add phone call entity instance in to queue.
        /// Mark phone call entity instance status as completed.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create a queue instance and set its property values.
            var newQueue = new Queue()
            {
                Name          = "Example Queue",
                Description   = "This is an example queue.",
                QueueViewType = new OptionSetValue((int)QueueQueueViewType.Private)
            };

            _queueId = service.Create(newQueue);
            Console.WriteLine("Created {0}.", newQueue.Name);

            // Create a phone call activity instance.
            var newPhoneCall = new PhoneCall
            {
                Description = "Example Phone Call"
            };

            _phoneCallId = service.Create(newPhoneCall);
            Console.WriteLine("Created {0}.", newPhoneCall.Description);

            // Create a new instance of a queueitem and initialize its
            // properties.
            var item = new QueueItem
            {
                QueueId  = new EntityReference(Queue.EntityLogicalName, _queueId),
                ObjectId = new EntityReference(PhoneCall.EntityLogicalName, _phoneCallId)
            };

            // Create the queueitem on the server, which will associate
            // the phone call activity with the queue.
            _queueItemId = service.Create(item);

            Console.WriteLine("Added phone call entity instance to {0}", newQueue.Name);

            // Mark the phone call as completed.
            var setStatePhoneCall = new SetStateRequest
            {
                EntityMoniker = new EntityReference(PhoneCall.EntityLogicalName,
                                                    _phoneCallId),
                State  = new OptionSetValue((int)PhoneCallState.Completed),
                Status = new OptionSetValue(-1)
            };

            service.Execute(setStatePhoneCall);
            Console.WriteLine("PhoneCall entity instance has been marked as completed.");

            return;
        }
 public void WhenICreateANewAccount()
 {
     account = new Entity("account");
     account.Attributes["name"] = new RandomGenerator().GetString(8);
     account["telephone1"]      = "123456789";
     account.Id = service.Create(account);
 }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a new queue instance.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            var whoRequest = new WhoAmIRequest();

            _currentUser = ((WhoAmIResponse)service.Execute(whoRequest)).UserId;

            //Create an activity objects which will act like a template during QC distrbution.
            //The activities created by QC will create activities with content that this activity has
            _templateEmailActivity = new Email()
            {
                Subject = "qcCreatedEmailActivity"
            };

            _templateLetterActivity = new Letter()
            {
                Subject = "qcCreatedLetterActivity"
            };

            // Create accounts on which we want to run QC
            _accountIdArray = new Guid[5];
            for (int i = 0; i < 5; i++)
            {
                var acct = new Account()
                {
                    Name = "Account For Quick Campaign " + i.ToString()
                };
                _accountIdArray[i] = service.Create(acct);
                Console.WriteLine("Created {0}.", acct.Name);
            }
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Define some anonymous types to define the range
            // of possible connection property values.
            var Categories = new
            {
                Business = 1,
                Family   = 2,
                Social   = 3,
                Sales    = 4,
                Other    = 5
            };

            // Create a Connection Role
            ConnectionRole setupConnectionRole = new ConnectionRole
            {
                Name        = "Example Connection Role",
                Description = "This is an example one sided connection role.",
                Category    = new OptionSetValue(Categories.Business),
            };

            _connectionRoleId = service.Create(setupConnectionRole);
            Console.WriteLine("Created {0}.", setupConnectionRole.Name);

            return;
        }
Example #16
0
        public void CreateContactUsingProxyCallerId()
        {
            CrmServiceClient crmServiceClient = new CrmServiceClient(dynamicsConnectionString);

            crmServiceClient.OrganizationServiceProxy.CallerId = UserID1;
            Entity newContact = InitialiseContact();

            newContact.Id = crmServiceClient.Create(newContact);

            crmServiceClient.OrganizationServiceProxy.CallerId = UserID2;
            newContact["emailaddress1"] = string.Format("test.{0}@example.com", DateTime.Now.ToString("yyyyMMddHHmmss"));
            crmServiceClient.Update(newContact);

            Entity createdContact = crmServiceClient.Retrieve("contact", newContact.Id, new ColumnSet(new string[] { "createdby", "createdonbehalfby", "modifiedby", "modifiedonbehalfby" }));

            Guid actualCreatedBy    = ((EntityReference)createdContact["createdby"]).Id;
            Guid createdOnBehalfBy  = ((EntityReference)createdContact["createdonbehalfby"]).Id;
            Guid actualModifiedBy   = ((EntityReference)createdContact["modifiedby"]).Id;
            Guid modifiedOnBehalfBy = ((EntityReference)createdContact["modifiedonbehalfby"]).Id;

            Assert.AreEqual(UserID1, actualCreatedBy);
            Assert.AreEqual(ServiceUser, createdOnBehalfBy);
            Assert.AreEqual(UserID2, actualModifiedBy);
            Assert.AreEqual(ServiceUser, modifiedOnBehalfBy);
        }
        public void CreatePublisher()
        {
            using (var svc = new CrmServiceClient(connection))
            {
                Publisher _crmSdkPublisher = new Publisher
                {
                    UniqueName           = "sdksamples",
                    FriendlyName         = "Microsoft CRM SDK Samples",
                    SupportingWebsiteUrl = "https://msdn.microsoft.com/dynamics/crm/default.aspx",
                    CustomizationPrefix  = "sample",
                    EMailAddress         = "*****@*****.**",
                    Description          = "This publisher was created with samples from the Microsoft Dynamics CRM SDK"
                };

                Publisher publisher = RetrievePublisher("sdksamples");

                if (publisher != null)
                {
                    Console.WriteLine(string.Format("Publisher already exist: {0}.", _crmSdkPublisher.FriendlyName));
                }
                else
                {
                    svc.Create(_crmSdkPublisher);
                    Console.WriteLine(string.Format("Created publisher: {0}.", _crmSdkPublisher.FriendlyName));
                }
            }
        }
Example #18
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Define an anonymous type to define the possible values for
            // report type
            var ReportTypeCode = new
            {
                ReportingServicesReport = 1,
                OtherReport             = 2,
                LinkedReport            = 3
            };

            // Create a report
            var newReport = new Report
            {
                Name           = "Sample Report",
                Description    = "Report created by the SDK code sample.",
                ReportTypeCode = new OptionSetValue((int)ReportTypeCode.OtherReport),

                //Base64-encoded "Hello, I am a text file."
                BodyBinary = "SGVsbG8sIEkgYW0gYSB0ZXh0IGZpbGUu",
                FileName   = "textfile.txt",
                IsPersonal = true
            };

            _reportId = service.Create(newReport);
            Console.WriteLine("Created {0}.", newReport.Name);
        }
Example #19
0
        public void CreateContactUsingCustomOverridden()
        {
            CrmServiceClient crmServiceClient = new CrmServiceClient(dynamicsConnectionString);

            DateTime        newCreatedOn  = DateTime.Now.AddDays(-2);
            EntityReference newCreatedBy  = new EntityReference("systemuser", UserID1);
            DateTime        newModifiedOn = DateTime.Now.AddHours(-5);
            EntityReference newModifiedBy = new EntityReference("systemuser", UserID2);

            Entity newContact = InitialiseContact();

            newContact["overriddencreatedon"]      = newCreatedOn;
            newContact["rtb_overriddencreatedby"]  = newCreatedBy;
            newContact["rtb_overriddenmodifiedon"] = newModifiedOn;
            newContact["rtb_overriddenmodifiedby"] = newModifiedBy;
            newContact.Id = crmServiceClient.Create(newContact);

            Entity createdContact = crmServiceClient.Retrieve("contact", newContact.Id, new ColumnSet(new string[] { "createdon", "createdby", "modifiedby", "modifiedon" }));

            Guid     actualCreatedBy  = ((EntityReference)createdContact["createdby"]).Id;
            DateTime actualCreatedOn  = (DateTime)createdContact["createdon"];
            Guid     actualModifiedBy = ((EntityReference)createdContact["modifiedby"]).Id;
            DateTime actualModifiedOn = (DateTime)createdContact["modifiedon"];

            Assert.AreEqual(UserID1, actualCreatedBy);
            Assert.AreEqual(newCreatedOn.ToString("yyyyMMddHHmmss"), actualCreatedOn.ToString("yyyyMMddHHmmss"));
            Assert.AreEqual(UserID2, actualModifiedBy);
            Assert.AreEqual(newModifiedOn.ToString("yyyyMMddHHmmss"), actualModifiedOn.ToString("yyyyMMddHHmmss"));
        }
Example #20
0
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Get the current user.
            WhoAmIRequest  userRequest  = new WhoAmIRequest();
            WhoAmIResponse userResponse = (WhoAmIResponse)service.Execute(userRequest);

            _userId = userResponse.UserId;

            // Create the activity party for sending and receiving the fax.
            ActivityParty party = new ActivityParty
            {
                PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId)
            };

            // Create the fax object.
            Fax fax = new Fax
            {
                Subject = "Sample Fax",
                From    = new ActivityParty[] { party },
                To      = new ActivityParty[] { party }
            };

            _faxId = service.Create(fax);
            Console.WriteLine("Created a fax: '{0}'.", fax.Subject);
        }
        private Entity RegisterPluginType(Entity pluginEntity, TypeInfo plugin)
        {
            var fetchData = new
            {
                typename = plugin.FullName
            };
            var fetchXml = $@"
<fetch>
  <entity name='plugintype'>
    <attribute name='plugintypeid' />
    <filter type='and'>
      <condition attribute='typename' operator='eq' value='{fetchData.typename}'/>
    </filter>
  </entity>
</fetch>";
            var rows     = CrmServiceClient.RetrieveMultiple(new FetchExpression(fetchXml));

            if (rows.Entities.Count == 0)
            {
                var pluginType = new Entity("plugintype");
                pluginType["name"]             = plugin.FullName;
                pluginType["pluginassemblyid"] = new EntityReference("pluginassembly", Guid.Parse(pluginEntity["pluginassemblyid"].ToString()));
                pluginType["typename"]         = plugin.FullName;
                pluginType["friendlyname"]     = plugin.FullName;
                CliLog.WriteLine(CliLog.COLOR_GREEN, $"\tRegistering Type: ", CliLog.COLOR_CYAN, $"{plugin.FullName}");
                var pluginTypeId = CrmServiceClient.Create(pluginType);
                pluginType["plugintypeid"] = pluginTypeId;
                return(pluginType);
            }
            else
            {
                return(rows.Entities[0]);
            }
        }
Example #22
0
        public static void Main(string[] args)
        {
            try
            {
                using (_client = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString))
                {
                    //Do stuff
                    WhoAmIResponse res = (WhoAmIResponse)_client.Execute(new WhoAmIRequest());
                    Console.WriteLine($"Login User ID : {res.UserId}");
                    Console.WriteLine($"Organization Unique Name : {_client.ConnectedOrgUniqueName}");
                    Console.WriteLine($"Organization Display Name : {_client.ConnectedOrgFriendlyName}");
                    //Entity test = RetrieveProjectTemplateTask(new EntityReference("msdyn_project", new Guid("23A38E60-C0D0-E811-A96E-000D3A16ACEE")), "1");

                    Entity ProjectEntity = new Entity("msdyn_project");
                    ProjectEntity["fkh_unitid"]            = new EntityReference("po_unit", new Guid("6068F309-8A9D-E811-A857-000D3A14019B"));
                    ProjectEntity["msdyn_projecttemplate"] = new EntityReference("msdyn_project", new Guid("23A38E60-C0D0-E811-A96E-000D3A16ACEE"));
                    ProjectEntity["msdyn_subject"]         = "Malhar Test Project 2";

                    ProjectEntity.Id = _client.Create(ProjectEntity);


                    Console.WriteLine($"Press any key to exit.");
                    Console.Read();
                }
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                string message = ex.Message;
                throw;
            }
        }
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            Console.Write("Creating an account, ");

            // Account entity category codes.
            var Categories = new { PreferredCustomer = 1, Standard = 2 };

            // Create a new account entity.
            var newAccount = new Account {
                Name = "Example Account"
            };

            _newAccountId = service.Create(newAccount);

            Console.WriteLine("then updating the account.");

            var accountToUpdate = new Account
            {
                AccountId           = _newAccountId,
                AccountNumber       = "1-A",
                AccountCategoryCode = new OptionSetValue(Categories.PreferredCustomer),
                Telephone1          = "555-555-5555"
            };

            service.Update(accountToUpdate);
        }
Example #24
0
        /// <summary>
        /// Insert records to Dynamics Entity
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public string PostToCrm([FromBody] LeadModel leadModel)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            CrmServiceClient service    = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CRMConnection"].ConnectionString);
            Entity           leadRecord = new Entity("new_businesscardlead");


            leadRecord.Attributes.Add("new_name", leadModel.Name);
            leadRecord.Attributes.Add("new_company", leadModel.Company);
            leadRecord.Attributes.Add("new_title", leadModel.Title);
            leadRecord.Attributes.Add("new_citystatezip", leadModel.CityStateZip);
            leadRecord.Attributes.Add("new_email", leadModel.Email);
            leadRecord.Attributes.Add("new_website", leadModel.Website);
            leadRecord.Attributes.Add("new_facebook", leadModel.Facebook);
            leadRecord.Attributes.Add("new_twitter", leadModel.Twitter);
            leadRecord.Attributes.Add("new_phone", leadModel.Phone);
            leadRecord.Attributes.Add("new_fax", leadModel.Fax);
            leadRecord.Attributes.Add("new_cell", leadModel.Cell);

            var    guid     = service.Create(leadRecord);
            string id       = guid.ToString();
            string response = $"Lead has been created for {leadModel.Name} : lead Id : {id}.";

            return(response);
        }
Example #25
0
        private Entity RegisterAssembly(FileSystemInfo assemblyFilePath, Assembly assembly, IEnumerable <Type> plugins)
        {
            var assemblyProperties = assembly.GetName().FullName
                                     .Split(",= ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            var assemblyName = assembly.GetName().Name;
            var fetchData    = new
            {
                name = assemblyProperties[0]
            };
            var fetchXml         = $@"
<fetch>
  <entity name='pluginassembly'>
    <attribute name='pluginassemblyid' />
    <attribute name='content' />
    <filter type='and'>
      <condition attribute='name' operator='eq' value='{fetchData.name}'/>
    </filter>
  </entity>
</fetch>";
            var rows             = CrmServiceClient.RetrieveMultiple(new FetchExpression(fetchXml));
            var pluginAssemblyId = Guid.Empty;
            var existingContent  = string.Empty;

            if (rows.Entities.Count > 0)
            {
                var entity = rows.Entities[0];
                pluginAssemblyId = entity.Id;
                existingContent  = entity.GetAttributeValue <string>("content");
            }
            var content = Convert.ToBase64String(File.ReadAllBytes(assemblyFilePath.FullName));

            if (content == existingContent)
            {
                return(null);
            }
            var plugin = new Entity("pluginassembly")
            {
                ["content"]        = content,
                ["name"]           = assemblyProperties[0],
                ["culture"]        = assemblyProperties[4],
                ["version"]        = assemblyProperties[2],
                ["publickeytoken"] = assemblyProperties[6],
                ["sourcetype"]     = new OptionSetValue(0), /* 0 = database */
                ["isolationmode"]  = new OptionSetValue(2)  /* 2 = sandbox */
            };

            if (pluginAssemblyId == Guid.Empty)
            {
                CliLog.WriteLine(CliLog.ColorGreen, "Registering Assembly: ", CliLog.ColorCyan, $"{assemblyProperties[0]}");
                pluginAssemblyId           = CrmServiceClient.Create(plugin);
                plugin["pluginassemblyid"] = pluginAssemblyId;
            }
            else
            {
                CliLog.WriteLine(CliLog.ColorBlue, "Updating Assembly: ", CliLog.ColorCyan, $"{assemblyProperties[0]}");
                plugin["pluginassemblyid"] = pluginAssemblyId;
                CrmServiceClient.Update(plugin);
            }
            return(plugin);
        }
        public void GenerateHardCodedAccount()
        {
            using (var client = new CrmServiceClient(_connectionString))
            {
                var account = new Account()
                {
                    Name                     = "Acme Industries, Ltd",
                    EMailAddress1            = "*****@*****.**",
                    CreditOnHold             = false,
                    LastOnHoldTime           = DateTime.Now.AddYears(-1),
                    Address1_Line1           = "1234 Acme Road",
                    Address1_Line2           = "Suite 123",
                    Address1_City            = "Acme",
                    Address1_StateOrProvince = "AC",
                    Address1_PostalCode      = "01234",
                    NumberOfEmployees        = 10,
                    Revenue                  = new Money(1000000),
                    Telephone1               = "(123) 456-7890",
                    WebSiteURL               = "http://www.acmeindustries.com",
                    TickerSymbol             = "ACME"
                };

                // Create the account
                Guid accountId = client.Create(account);
                Assert.IsTrue(accountId != Guid.Empty);
            }
        }
Example #27
0
        public static void CreateApplication(string entityName, Dictionary <string, string> keyValues)
        {
            Entity eApplication = new Entity(entityName);

            foreach (KeyValuePair <string, string> record in keyValues)
            {
                if (record.Key.Equals("ss_name"))
                {
                    string typeValue = record.Value;
                    eApplication.Attributes[record.Key] = typeValue;
                }
                else if (record.Key.Equals("ss_applicationtype"))
                {
                    OptionSetValue typeValue = GetAppTypeValue(record.Value);
                    eApplication.Attributes[record.Key] = typeValue;
                }
                else if (record.Key.Equals("ss_destinationaddress"))
                {
                    Entity contact = RetrieveRecord("ss_customaddress", "ss_name", record.Value, new string[] { "ss_customaddressid" });
                    Console.WriteLine(contact.Attributes["ss_customaddressid"]);

                    Guid id = contact.Id;
                    Console.WriteLine(id);
                    EntityReference typeValue = new EntityReference("ss_customaddress", id);
                    eApplication.Attributes[record.Key] = typeValue;
                }
                else
                {
                    string typeValue = record.Value;
                    eApplication.Attributes[record.Key] = typeValue;
                }
            }

            svc.Create(eApplication);
        }
Example #28
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate

                    // Create a queue instance and set its property values.
                    var newQueue = new Queue()
                    {
                        Name        = "Example Queue.",
                        Description = "This is an example queue."
                    };

                    // Create a new queue instance.
                    _queueId = service.Create(newQueue);

                    Console.WriteLine("Created {0}.", newQueue.Name);
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Example #29
0
        static void CreateEntity()
        {
            using (var svc = new CrmServiceClient(connection))
            {
                var courier = new Entity("new_courier");

                courier["new_name"]    = "Create entity test 7";
                courier["new_vehicle"] = new OptionSetValue(100000001);

                // Associate an entity to a new contact

                //var primaryContact = new Entity("contact");
                //primaryContact["firstname"] = "John";
                //primaryContact["lastname"] = "Smith";
                //EntityCollection primaryContactCollection = new EntityCollection();
                //primaryContactCollection.Entities.Add(primaryContact);
                //courier.RelatedEntities[new Relationship("new_contact_new_courier_contact")] = primaryContactCollection;

                // Associate an entity to an existing contact

                courier["new_contact"] = new EntityReference("contact", new Guid("1218da0b-0d87-eb11-a812-000d3a4c1ce8"));

                Guid id = svc.Create(courier);

                Console.WriteLine("Entity created.");

                // Retrieve an entity

                Entity entity = svc.Retrieve("new_courier", id, new ColumnSet("new_name"));
                Console.WriteLine($"Entity name: {entity["new_name"]}");

                Console.ReadLine();
            }
        }
Example #30
0
        public void CreateNewContact()
        {
            //Setup
            string crmCon = TestCreateContact.GetConfigValue("CrmConnection");

            using (CrmServiceClient svc = new CrmServiceClient(crmCon))
            {
                // Act
                Entity c = new Entity("contact");

                c["firstname"] = "Test";
                c["lastname"]  = DateTime.Now.Date.ToShortDateString();

                c.Id = svc.Create(c);

                //Validate
                Thread.Sleep(5000);

                QueryByAttribute query = new QueryByAttribute("phonecall");
                query.Attributes.Add("regardingobjectid");
                query.Values.Add(c.Id);

                EntityCollection calls = svc.RetrieveMultiple(query);

                Assert.AreEqual(calls.Entities.Count, 1);

                //Clean up
                svc.Delete(c.LogicalName, c.Id);
            }
        }