/*ACTIVITIES*/
    protected void activity(string username, string message, bool isUpdate)
    {
        using (OrganizationService service = new OrganizationService(OurConnect()))
        {
            Entity newActivity = new Entity(consts.activities);

            newActivity[consts.activitytime] = DateTime.Now;
            newActivity[consts.activityid]   = Guid.NewGuid();
            newActivity[consts.to]           = username;
            newActivity[consts.from]         = _ApplicationName;
            newActivity[consts.subject]      = message;

            if (message != "")
            {
                service.Create(newActivity);
            }

            if (isUpdate)
            {
                newActivity[consts.subject] = "Modified";
                service.Create(newActivity);
            }

            return;
        }
    }
예제 #2
0
        private Entity CreateAddress(AddressDetails address, Entity postCode, Entity country)
        {
            Entity city   = null;
            Entity county = null;

            if (address.City != null || address.City != "")
            {
                city = FindOrCreateCity(country.ToEntityReference(), address.City);
            }

            if (address.County != null || address.County != "")
            {
                county = FindOrCreateCounty(country.ToEntityReference(), address.County);
            }

            var addrEntity = new Entity("new_address");

            addrEntity["new_addressname"]       = address.BuildingDetails;
            addrEntity["new_addressnumbertext"] = address.Number;

            addrEntity["new_county"]  = county.ToEntityReference();
            addrEntity["new_country"] = country.ToEntityReference();
            addrEntity["new_city"]    = city.ToEntityReference();

            addrEntity["new_street1"] = address.street1;
            addrEntity["new_street2"] = address.street2;
            addrEntity["new_street3"] = address.street3;

            addrEntity["new_addressorigin"] = AddressOrigin.Manual.ToOptionSet();
            addrEntity["new_postalcode"]    = postCode.ToEntityReference();

            var createdAddress = svc.Create(addrEntity);

            return(svc.Retrieve("new_address", createdAddress, new ColumnSet(true)));
        }
        public void AddPluginAssembly(PluginAssemblyAndTypes pluginAssemblyAndTypes, Solution solution)
        {
            var id = orgService.Create(pluginAssemblyAndTypes.PluginAssembly);

            pluginAssemblyAndTypes.PluginAssembly.Id = id;
            AddComponentToSolution(solution, id, componenttype.PluginAssembly);
            UpsertAssemblyTypes(pluginAssemblyAndTypes, solution);
        }
예제 #4
0
        public void CreateEmploye(Employe employe)
        {
            Entity employeEntity = new Entity("new_employeuniversietjkwe");

            employeEntity["new_name"]    = employe.nom;
            employeEntity["new_prenom"]  = employe.prenom;
            employeEntity["new_adresse"] = employe.adresse;

            Guid id = orgService.Create(employeEntity);

            Console.WriteLine("Et voilà !! : " + id);
        }
        public OrganizationsControllerTests()
        {
            var list = new List <Organization>
            {
                new Organization {
                    Id = 1, Name = "test 1"
                },
                new Organization {
                    Id = 2, Name = "test 2"
                }
            }.AsQueryable();

            var mockContext            = Substitute.For <TtContext>();
            var organizationRepository = Substitute.For <Repository <Organization> >(mockContext);

            _service = Substitute.For <OrganizationService>(organizationRepository);
            _service.GetList().Returns(list);
            _service.GetItem(Arg.Any <int>()).Returns(new Organization {
                Id = 1, Name = "test 1"
            });
            _service.Create(Arg.Any <Organization>());
            _service.Update(Arg.Any <int>(), Arg.Any <Organization>());
            _service.Delete(Arg.Any <int>());

            var mockLogger = Substitute.For <ILoggerFactory>();

            _controller = new OrganizationsController(_service, mockLogger);
        }
예제 #6
0
        public static Entity RegisterPlugin(this OrganizationService crm, Type type, string friendlyName, string description)
        {
            var assembly = RegisterPluginAssembly(crm, type.Assembly);
            var pq       = new QueryExpression()
            {
                EntityName = "plugintype",
                Criteria   = new FilterExpression()
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions     =
                    {
                        new ConditionExpression("pluginassemblyid", ConditionOperator.Equal, assembly.Id),
                        new ConditionExpression("typename",         ConditionOperator.Equal, type.FullName),
                    }
                }
            };

            var pluginType = crm.RetrieveMultiple(pq).Entities.FirstOrDefault() ?? new Entity("plugintype");

            pluginType["pluginassemblyid"] = new EntityReference("pluginassembly", assembly.Id);
            pluginType["typename"]         = type.FullName;
            pluginType["friendlyname"]     = friendlyName;
            pluginType["description"]      = description;

            if (pluginType.Id != Guid.Empty)
            {
                crm.Update(pluginType);
            }
            else
            {
                pluginType.Id = crm.Create(pluginType);
            }
            return(pluginType);
        }
예제 #7
0
 private void LogEvent(EventLogItem eventLog, bool writeWindowsApplicationLog)
 {
     // Check to make sure the proxy is accessible
     //if (base.organizationServiceProxy == null)
     //{
     //    return;
     //}
     try
     {
         Entity logEntity = new Entity(ENTITY_EVENTLOG);
         logEntity.Attributes.Add("inf_name", "Plugin Assembly");
         logEntity.Attributes.Add("inf_type", eventLog.Type);
         logEntity.Attributes.Add("inf_user", this.PluginExecutionContext.UserId.ToString());
         logEntity.Attributes.Add("inf_host", System.Net.Dns.GetHostName());
         logEntity.Attributes.Add("inf_message", eventLog.Message);
         logEntity.Attributes.Add("inf_source", eventLog.Source);
         logEntity.Attributes.Add("inf_stacktrace", eventLog.StackTrace);
         logEntity.Attributes.Add("inf_targetsite", eventLog.TargetSite);
         logEntity.Attributes.Add("inf_innerexceptions", eventLog.InnerExceptions);
         OrganizationService.Create(logEntity);
     }
     catch (Exception handleExceptionFailure)
     {
         if (writeWindowsApplicationLog)
         {
             WriteEventLogEntry("Log failed : unable to create an event log record in MSCRM. Detailed exception:" + handleExceptionFailure.Message);
             WriteEventLogEntry(eventLog.Message + Environment.NewLine + eventLog.StackTrace);
         }
     }
 }
예제 #8
0
        private bool UpsertDocumentTemplate(Entity curEntity, Entity targetEntity,
                                            Dictionary <string, EntityMetadata> entitiesMetaData, ref string debugInfo)
        {
            if (!curEntity.LogicalName.Equals(Constant.DocumentTemplate.EntityLogicalName, StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            // DocumentTemplate has objectTypeCode (EntityTypeCode) that can be
            // different in target environment. So fix it here.
            debugInfo = "Replacing Document Type code";
            ReplaceDocumentTypeCodes(curEntity, entitiesMetaData);

            if (targetEntity != null)
            {
                debugInfo = "Updating Document Template";
                OrganizationService.Update(curEntity);
            }
            else
            {
                debugInfo = "Inserting Document Template";
                OrganizationService.Create(curEntity);
            }

            return(true);
        }
    private Guid GetUniqueID(string username, bool isAuthenticated, bool ignoreAuthenticationType)
    {
        if (username == null)
        {
            throw new ArgumentNullException("User name cannot be null.");
        }
        using (OrganizationService service = new OrganizationService(OurConnect()))
        {
            ConditionExpression usernameCondition = new ConditionExpression();
            ConditionExpression appCondition      = new ConditionExpression();

            usernameCondition.AttributeName = consts.username;
            usernameCondition.Operator      = ConditionOperator.Equal;
            usernameCondition.Values.Add(username);

            appCondition.AttributeName = consts.appname;
            appCondition.Operator      = ConditionOperator.Equal;
            appCondition.Values.Add(_ApplicationName);

            FilterExpression filter = new FilterExpression();
            filter.Conditions.Add(usernameCondition);
            filter.Conditions.Add(appCondition);

            if (!ignoreAuthenticationType)
            {
                ConditionExpression isanonymousCondition = new ConditionExpression();

                isanonymousCondition.AttributeName = consts.isanonymous;
                isanonymousCondition.Operator      = ConditionOperator.Equal;
                isanonymousCondition.Values.Add(!isAuthenticated);

                filter.Conditions.Add(isanonymousCondition);
            }

            QueryExpression query = new QueryExpression(consts.userprofile);
            query.ColumnSet.AddColumn(consts.profileid);
            query.Criteria.AddFilter(filter);
            EntityCollection collection = service.RetrieveMultiple(query);

            Guid uniqueID;
            if (collection.Entities.Count != 0)
            {
                uniqueID = (Guid)collection.Entities[0][consts.profileid];
            }
            else
            {
                Entity newProfile = new Entity(consts.userprofile);

                newProfile[consts.username]    = username;
                newProfile[consts.appname]     = _ApplicationName;
                newProfile[consts.isanonymous] = !isAuthenticated;

                uniqueID = (Guid)service.Create(newProfile);

                activity(username, "Profile Created", true);
            }

            return(uniqueID);
        }
    }
예제 #10
0
        private Entity CreatePayment(Entity contact)
        {
            Entity newParentRecord = new Entity("dxtools_payment");

            newParentRecord["dxtools_paymentreference"] = "DXT-" + DateTime.Now.Ticks;
            newParentRecord["dxtools_subject"]          = "Integration Test - CreateCustomEmailTest_NotSend at " + DateTime.Now;
            newParentRecord["dxtools_amount"]           = new Microsoft.Xrm.Sdk.Money(new Decimal(50.3));
            newParentRecord["dxtools_paymentdirection"] = new OptionSetValue(503530000);
            newParentRecord["dxtools_contactid"]        = contact.ToEntityReference();

            newParentRecord.Id = OrganizationService.Create(newParentRecord);

            Entity newRecord = new Entity("dxtools_payment");

            newRecord["dxtools_paymentreference"] = "DXT-" + DateTime.Now.Ticks;
            newRecord["dxtools_subject"]          = "Integration Test - CreateCustomEmailTest_NotSend at " + DateTime.Now;
            newRecord["dxtools_amount"]           = new Microsoft.Xrm.Sdk.Money(new Decimal(101.5));
            newRecord["dxtools_paymentdirection"] = new OptionSetValue(503530000);
            newRecord["dxtools_contactid"]        = contact.ToEntityReference();
            newRecord["dxtools_parentpaymentid"]  = newParentRecord.ToEntityReference();

            newRecord.Id = OrganizationService.Create(newRecord);

            return(newRecord);
        }
        /// <summary>
        /// Uploads the created from processing the data files (company + contact)
        /// to the CRM organization
        /// </summary>
        public void CommitRecords(List <Record> records)
        {
            var counter = 0;

            foreach (var record in records)
            {
                _sw.Start();
                var guidCompany = _orgService.Create(record.Company);
                record.BindContactToCompany(guidCompany);
                _orgService.Create(record.Contact);
                _sw.Stop();
                var time = _sw.ElapsedMilliseconds;
                _sw.Reset();
                Console.WriteLine($"\t{counter++}:\t{guidCompany}\t{time}ms");
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            base.WriteVerbose(string.Format("Importing access team templates from: {0}", InputPath));
            ExportedTeamTemplates templates = new ExportedTeamTemplates();
            var serializer = new XmlSerializer(templates.GetType());

            using (TextReader reader = new StreamReader(InputPath))
            {
                templates = (ExportedTeamTemplates)serializer.Deserialize(reader);
            }

            foreach (ExportEntity exportedEntity in templates.TeamTemplates)
            {
                Entity entity = new Entity(exportedEntity.LogicalName);
                entity.Id = exportedEntity.Id;
                foreach (var attribute in exportedEntity.Attributes)
                {
                    entity[attribute.Key] = attribute.Value;
                }
                try
                {
                    //first try an update
                    OrganizationService.Update(entity);
                }
                catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
                {
                    //if update fails, try a create
                    OrganizationService.Create(entity);
                }
            }

            base.WriteObject("Import complete");
        }
예제 #13
0
        public void Test_CaseImport()
        {
            CrmConnection        crmConnection = (CrmConnection)connection.GetConnection();
            IOrganizationService service       = new OrganizationService(crmConnection);

            string accountName1 = Guid.NewGuid().ToString();
            Entity account      = new Entity("account");

            account.Attributes.Add("name", accountName1);
            Guid account1 = service.Create(account);

            IntegrationTool.Module.WriteToDynamicsCrm.WriteToDynamicsCrmConfiguration writeToCrmConfig = new IntegrationTool.Module.WriteToDynamicsCrm.WriteToDynamicsCrmConfiguration();
            writeToCrmConfig.EntityName = "incident";
            writeToCrmConfig.PrimaryKeyAttributes.Add("ticketnumber");
            writeToCrmConfig.ImportMode        = Module.WriteToDynamicsCrm.SDK.Enums.ImportMode.All;
            writeToCrmConfig.MultipleFoundMode = Module.WriteToDynamicsCrm.SDK.Enums.MultipleFoundMode.All;
            writeToCrmConfig.Mapping.Add(new IntegrationTool.DataMappingControl.DataMapping()
            {
                Source = "CaseID", Target = "ticketnumber"
            });
            writeToCrmConfig.Mapping.Add(new IntegrationTool.DataMappingControl.DataMapping()
            {
                Source = "CaseTitle", Target = "title"
            });

            writeToCrmConfig.RelationMapping.Add(new Module.WriteToDynamicsCrm.SDK.RelationMapping()
            {
                EntityName  = "account",
                LogicalName = "customerid",
                Mapping     = new List <DataMappingControl.DataMapping>()
                {
                    new DataMappingControl.DataMapping()
                    {
                        Source = "CompanyName",
                        Target = "name"
                    }
                }
            });
            writeToCrmConfig.ConfigurationId = Guid.NewGuid();
            writeToCrmConfig.SelectedConnectionConfigurationId = Test_Helpers.CRMCONNECTIONID;

            IDatastore dataObject = DataStoreFactory.GetDatastore();

            dataObject.AddColumn(new ColumnMetadata("CaseID"));
            dataObject.AddColumn(new ColumnMetadata("CaseTitle"));
            dataObject.AddColumn(new ColumnMetadata("CompanyName"));


            dataObject.AddData(new object[] { "CA-100", "101 Title", accountName1 });
            dataObject.AddData(new object[] { "CA-101", "Anöther Title", null });
            dataObject.AddData(new object[] { "CA-102", "A'Title\"chen", accountName1 });

            IModule module = Activator.CreateInstance(typeof(WriteToDynamicsCrm)) as IModule;

            module.SetConfiguration(writeToCrmConfig);

            ((IDataTarget)module).WriteData(connection, new DummyDatabaseInterface(), dataObject, Test_Helpers.ReportProgressMethod);

            service.Delete("account", account1);
        }
        public void Test_AccountDeletion()
        {
            CrmConnection        crmConnection = (CrmConnection)connection.GetConnection();
            IOrganizationService service       = new OrganizationService(crmConnection);

            // Create dummy account, which shall be deleted
            string accountName1 = Guid.NewGuid().ToString();
            Entity account      = new Entity("account");

            account.Attributes.Add("name", accountName1);
            Guid account1 = service.Create(account);

            DeleteInDynamicsCrmConfiguration deleteInCrmConfig = new DeleteInDynamicsCrmConfiguration();

            deleteInCrmConfig.EntityName        = "account";
            deleteInCrmConfig.MultipleFoundMode = DeleteInCrmMultipleFoundMode.DeleteAll;
            deleteInCrmConfig.DeleteMapping.Add(new DataMapping()
            {
                Source = "CompanyName", Target = "name"
            });

            IDatastore dataObject = DataStoreFactory.GetDatastore();

            dataObject.AddColumn(new ColumnMetadata("CompanyName"));

            dataObject.AddData(new object[] { accountName1 });

            IModule module = Activator.CreateInstance(typeof(DeleteInDynamicsCrm)) as IModule;

            module.SetConfiguration(deleteInCrmConfig);

            ((IDataTarget)module).WriteData(connection, new DummyDatabaseInterface(), dataObject, ReportProgressMethod);
        }
예제 #15
0
        private static void СозданиеЗадач() //  < ----- )))))))))))))))))))))))))
        {
            var service      = new OrganizationService(connection);
            var dataFromXmlx = new Program().ExcelOpenSpreadsheets(@"C:\Users\savchinvv\Desktop\Задачи.xlsx");

            for (int i = 2; i < dataFromXmlx.Tables[0].Rows.Count; i++)
            {
                var newTask = new SoftLine.Models.Task()
                {
                    Subject               = dataFromXmlx.Tables[0].Rows[i][0].ToString(),
                    RegardingObjectId     = ToSpravaEntity(dataFromXmlx.Tables[0].Rows[i][1].ToString()),
                    PriorityCode          = ToOptionSetValue(dataFromXmlx.Tables[0].Rows[i][2].ToString()),
                    ScheduledEnd          = FindDate(dataFromXmlx.Tables[0].Rows[i][3].ToString()),
                    ScheduledStart        = FindDate(dataFromXmlx.Tables[0].Rows[i][4].ToString()),
                    ActualDurationMinutes = ToInt32(dataFromXmlx.Tables[0].Rows[i][5].ToString()),
                    Description           = dataFromXmlx.Tables[0].Rows[i][6].ToString(),
                    PercentComplete       = ToInt32(dataFromXmlx.Tables[0].Rows[i][7].ToString()),
                    ActualStart           = FindDate(dataFromXmlx.Tables[0].Rows[i][9].ToString()),
                    ActualEnd             = FindDate(dataFromXmlx.Tables[0].Rows[i][10].ToString())
                };
                var id = service.Create(newTask);
                Console.WriteLine("{0} - созданая Задача", dataFromXmlx.Tables[0].Rows[i][0].ToString());
                bool?status = false;
                if (dataFromXmlx.Tables[0].Rows[i][8].ToString() == "Завершено")
                {
                    status = ChangeStateCode(id);
                }
                Console.WriteLine("Задача = StatusChange->{0}", status ?? null);
            }
        }
예제 #16
0
        private static void LoadSprava()
        {
            var service = new OrganizationService(connection);
            var context = new CrmOrganizationServiceContext(connection);

            var dataFromXmlx = new Program().ExcelOpenSpreadsheets(@"C:\Users\savchinvv\Desktop\Дела_юр.xlsx");

            for (int i = 37; i < dataFromXmlx.Tables[0].Rows.Count; i++)
            {
                var newSprava = new new_spravastr()
                {
                    new_businessnumber   = dataFromXmlx.Tables[0].Rows[i][0].ToString(),
                    new_nameid           = FindClient(dataFromXmlx.Tables[0].Rows[i][1].ToString()),
                    new_partnercustomer  = FindAccount(dataFromXmlx.Tables[0].Rows[i][2].ToString()),
                    new_typeofbusiness   = EntityForm(dataFromXmlx.Tables[0].Rows[i][3].ToString()),
                    new_type_of_business = CheckType(dataFromXmlx.Tables[0].Rows[i][4].ToString()),
                    new_priority         = ToInt32(dataFromXmlx.Tables[0].Rows[i][5].ToString()),
                    new_state            = FindState(dataFromXmlx.Tables[0].Rows[i][6].ToString()),
                    new_creationdate     = FindDate(dataFromXmlx.Tables[0].Rows[i][7].ToString()),
                    new_liquidated       = FindBit(dataFromXmlx.Tables[0].Rows[i][8].ToString()),
                    new_gai                    = FindGos(dataFromXmlx.Tables[0].Rows[i][9].ToString()),
                    new_datedtp                = FindDate(dataFromXmlx.Tables[0].Rows[i][10].ToString()),
                    new_Dateagreement          = FindDate(dataFromXmlx.Tables[0].Rows[i][11].ToString()),
                    new_date_of_birth          = FindDate(dataFromXmlx.Tables[0].Rows[i][12].ToString()),
                    new_date_death             = FindDate(dataFromXmlx.Tables[0].Rows[i][13].ToString()),
                    new_pledge                 = dataFromXmlx.Tables[0].Rows[i][14].ToString(),
                    new_property1              = dataFromXmlx.Tables[0].Rows[i][15].ToString(),
                    new_property2              = dataFromXmlx.Tables[0].Rows[i][16].ToString(),
                    new_taxnumber              = dataFromXmlx.Tables[0].Rows[i][17].ToString(),
                    new_code                   = dataFromXmlx.Tables[0].Rows[i][18].ToString(),
                    new_placedtp               = dataFromXmlx.Tables[0].Rows[i][19].ToString(),
                    new_locality               = dataFromXmlx.Tables[0].Rows[i][20].ToString(),
                    new_home                   = dataFromXmlx.Tables[0].Rows[i][21].ToString(),
                    new_Place_of_work_1        = dataFromXmlx.Tables[0].Rows[i][22].ToString(),
                    new_Place_of_work_2        = dataFromXmlx.Tables[0].Rows[i][23].ToString(),
                    new_Companyname            = dataFromXmlx.Tables[0].Rows[i][24].ToString(),
                    new_insurancecompany       = dataFromXmlx.Tables[0].Rows[i][25].ToString(),
                    new_taxaddress             = dataFromXmlx.Tables[0].Rows[i][26].ToString(),
                    new_heir1                  = FindClient(dataFromXmlx.Tables[0].Rows[i][27].ToString()),
                    new_heir2                  = FindClient(dataFromXmlx.Tables[0].Rows[i][28].ToString()),
                    new_heir3                  = FindClient(dataFromXmlx.Tables[0].Rows[i][29].ToString()),
                    new_Credit_agreement       = dataFromXmlx.Tables[0].Rows[i][30].ToString(),
                    new_Social_security_number = dataFromXmlx.Tables[0].Rows[i][31].ToString(),
                    new_litigationnumber       = dataFromXmlx.Tables[0].Rows[i][32].ToString(),
                    new_guarantor1             = FindClient(dataFromXmlx.Tables[0].Rows[i][33].ToString()),
                    new_guarantor2             = FindClient(dataFromXmlx.Tables[0].Rows[i][34].ToString()),
                    new_guarantor3             = FindClient(dataFromXmlx.Tables[0].Rows[i][35].ToString()),
                    new_amount_loan            = ToDouble(dataFromXmlx.Tables[0].Rows[i][36].ToString()),
                    new_spouse                 = FindClient(dataFromXmlx.Tables[0].Rows[i][37].ToString()),
                    new_accident1              = FindClient(dataFromXmlx.Tables[0].Rows[i][38].ToString()),
                    new_accident2              = FindClient(dataFromXmlx.Tables[0].Rows[i][39].ToString()),
                    new_accident3              = FindClient(dataFromXmlx.Tables[0].Rows[i][40].ToString()),
                    new_accident4              = FindClient(dataFromXmlx.Tables[0].Rows[i][41].ToString()),
                    new_institution            = FindGos(dataFromXmlx.Tables[0].Rows[i][42].ToString()),
                    new_amount                 = ToDouble(dataFromXmlx.Tables[0].Rows[i][43].ToString())
                };
                service.Create(newSprava);
                Console.WriteLine("{0} Обработан и создан: {1}", i, dataFromXmlx.Tables[0].Rows[i][0].ToString());
            }
        }
예제 #17
0
        private static Entity RegisterPluginAssembly(this OrganizationService crm, Assembly assembly)
        {
            var assemblyName = assembly.GetName();

            var query = new QueryByAttribute("pluginassembly");

            query.Attributes.Add("name");
            query.Values.Add(assemblyName.Name);
            var results = crm.RetrieveMultiple(query);

            var pluginAssembly = results.Entities.FirstOrDefault() ?? new Entity("pluginassembly");

            pluginAssembly["name"]           = assemblyName.Name;
            pluginAssembly["culture"]        = assemblyName.CultureName;
            pluginAssembly["version"]        = assemblyName.Version.ToString();
            pluginAssembly["publickeytoken"] = String.Concat(Array.ConvertAll(assemblyName.GetPublicKeyToken(), b => b.ToString("x2")));

            pluginAssembly["sourcetype"]    = new OptionSetValue((int)CrmAssemblySourceType.Database);
            pluginAssembly["isolationmode"] = new OptionSetValue((int)CrmAssemblyIsolationMode.Sandbox);
            pluginAssembly["content"]       = Convert.ToBase64String(File.ReadAllBytes(assembly.Location));

            if (pluginAssembly.Id != Guid.Empty)
            {
                crm.Update(pluginAssembly);
            }
            else
            {
                pluginAssembly.Id = crm.Create(pluginAssembly);
            }
            return(pluginAssembly);
        }
예제 #18
0
        private static int CreateOrganization(OrganizationService service, string name)
        {
            var org          = new Organization(0, name);
            var createResult = service.Create(org);

            Assert.IsTrue(createResult.IsSuccessful);
            return(createResult.Data);
        }
        public void PerformTestSetup()
        {
            MessageName = "Update";

            EntityToUpdate = new Entity("contact");
            EntityToUpdate.Attributes.Add("firstname", "DummyFirstName");

            EntityToUpdate.Id = OrganizationService.Create(EntityToUpdate);
        }
예제 #20
0
        public void PublishInCRM(ServiceRequest serviceRequest)
        {
            //Connects to the database and Logs the User In
            var connection = ConnectToDatabase();
            var service = new OrganizationService(connection);
            var context = new CrmOrganizationServiceContext(connection);

            //const int hour = 60;

            EventLog.saveMessage("PublishIssue SRID:" + serviceRequest.SRID);

            //Creating the new Case
            Entity incident = new Entity("incident");

            try
            {
                //Filling the Data for the new case
                incident["createdon"] = serviceRequest.RegistrationDate;
                incident["description"] = serviceRequest.LongDescription;
                incident["statuscode"] = ReturnStatusCode(serviceRequest.ServiceRequestStatus);
                incident["subjectid"] = ReturnRequestType(serviceRequest.ServiceRequestType);
                incident["new_moduleoptionset"] = ReturnModuleCode("TS");
                //incident["ownerid"] = new EntityReference("systemuser", findConsultantID(serviceRequest.AssignedPerson, service));
                incident["new_caseasignedto"] = serviceRequest.AssignedPerson;
                incident["new_statushistory"] = serviceRequest.CommentsMatricia;
                incident["casetypecode"] = returnRequestKind(serviceRequest.ServiceRequestKind);
                incident["followupby"] = serviceRequest.DueDate;
                incident["new_supportrequestid"] = serviceRequest.SRID;
                incident["title"] = serviceRequest.AssignedToClient + " " + serviceRequest.SRID + " " + serviceRequest.companyName;
                //incident["customerid"] = new EntityReference("account", findCustomer((string)serviceRequest.companyName, service));
                incident["customerid"] = new EntityReference("account", findCustomerID(serviceRequest.companyName));
                incident["new_statushistory"] = serviceRequest.ShortDescription;
                incident["new_assignedfrom"] = serviceRequest.CreatedBy;

                Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service);

                
                //Adding the created case to CRM;
                var incidentGuid = service.Create(incident);

                //Assign a case!
                EventLog.saveMessage("Start of Assignment! to :" + consultantID);
                AssignRequest assignRequest = new AssignRequest();
                assignRequest.Assignee = new EntityReference("systemuser", consultantID);
                assignRequest.Target = new EntityReference(incident.LogicalName, incidentGuid);

                service.Execute(assignRequest);
            }
            catch (Exception)
            {
                EventLog.saveMessage("This case was not created in CRM " + serviceRequest.CreatedBy + "'" + serviceRequest.SRID); ;
            }



        }
        private Entity CreateAccount()
        {
            Entity newRecord = new Entity("account");

            newRecord["name"] = "Test LTD";

            newRecord.Id = OrganizationService.Create(newRecord);

            return(newRecord);
        }
예제 #22
0
        public static Guid CreateRecord(string entityName, OrganizationService service)
        {
            Entity icl_Case = new Entity(entityName);

            icl_Case["icl_communicationchannel"] = new OptionSetValue(2);
            icl_Case["icl_casetype"]             = new OptionSetValue(1);
            icl_Case["icl_casetheme"]            = new OptionSetValue(1);
            icl_Case["icl_incomingdate"]         = DateTime.Now;
            return(service.Create(icl_Case));
        }
        private EntityReference CreateQueue()
        {
            Entity newRecord = new Entity("queue");

            newRecord["name"]         = "Dx Tools Test Queue " + DateTime.Now;
            newRecord["emailaddress"] = "*****@*****.**";

            newRecord.Id = OrganizationService.Create(newRecord);

            return(newRecord.ToEntityReference());
        }
        private Entity CreateTemplates(string attachmentName)
        {
            //Template 1
            string title1    = rowEmailSubject1 + DateTime.Now;
            string body1     = rowEmailBody1 + DateTime.Now;
            Entity template1 = new Entity("template");

            template1["title"]   = title1;
            template1["subject"] = TemplatesHelper.GetSubjectXML(title1);
            template1["subjectpresentationxml"] = TemplatesHelper.GetSubjectPresentationXML(title1);
            template1["body"]             = TemplatesHelper.GetBodyXML(body1);
            template1["presentationxml"]  = TemplatesHelper.GetBodyPresentationXML(body1);
            template1["templatetypecode"] = 8;//Global template
            template1["ispersonal"]       = false;
            template1["languagecode"]     = 1033;
            template1.Id = OrganizationService.Create(template1);

            //Template 2
            string title2    = rowEmailSubject2 + DateTime.Now;
            string body2     = rowEmailBody2 + DateTime.Now;
            Entity template2 = new Entity("template");

            template2["title"]   = title2;
            template2["subject"] = TemplatesHelper.GetSubjectXML(title2);
            template2["subjectpresentationxml"] = TemplatesHelper.GetSubjectPresentationXML(title2);
            template2["body"]             = TemplatesHelper.GetBodyXML(body2);
            template2["presentationxml"]  = TemplatesHelper.GetBodyPresentationXML(body2);
            template2["templatetypecode"] = 8;//Global template
            template2["ispersonal"]       = false;
            template2["languagecode"]     = 1033;
            template2.Id = OrganizationService.Create(template2);

            //Add attachment to template 1
            Entity activityMimeAttachment1 = new Entity("activitymimeattachment");

            activityMimeAttachment1["objectid"]       = template1.ToEntityReference();
            activityMimeAttachment1["objecttypecode"] = "template";
            activityMimeAttachment1["filename"]       = attachmentName;
            activityMimeAttachment1["body"]           = Convert.ToBase64String(new UnicodeEncoding().GetBytes("Sample Annotation Text 1"));
            activityMimeAttachment1["mimetype"]       = "text/plain";
            OrganizationService.Create(activityMimeAttachment1);

            //Add attachment to template 2
            Entity activityMimeAttachment2 = new Entity("activitymimeattachment");

            activityMimeAttachment2["objectid"]       = template2.ToEntityReference();
            activityMimeAttachment2["objecttypecode"] = "template";
            activityMimeAttachment2["filename"]       = attachmentName;
            activityMimeAttachment2["body"]           = Convert.ToBase64String(new UnicodeEncoding().GetBytes("Sample Annotation Text 2"));
            activityMimeAttachment2["mimetype"]       = "text/plain";
            OrganizationService.Create(activityMimeAttachment2);

            return(template1);
        }
예제 #25
0
        public void PublishInCRM(ServiceRequest serviceRequest)
        {
            //Connects to the database and Logs the User In
            var connection = ConnectToDatabase();
            var service    = new OrganizationService(connection);
            var context    = new CrmOrganizationServiceContext(connection);

            //const int hour = 60;

            EventLog.saveMessage("PublishIssue SRID:" + serviceRequest.SRID);

            //Creating the new Case
            Entity incident = new Entity("incident");

            try
            {
                //Filling the Data for the new case
                incident["createdon"]           = serviceRequest.RegistrationDate;
                incident["description"]         = serviceRequest.LongDescription;
                incident["statuscode"]          = ReturnStatusCode(serviceRequest.ServiceRequestStatus);
                incident["subjectid"]           = ReturnRequestType(serviceRequest.ServiceRequestType);
                incident["new_moduleoptionset"] = ReturnModuleCode("TS");
                //incident["ownerid"] = new EntityReference("systemuser", findConsultantID(serviceRequest.AssignedPerson, service));
                incident["new_caseasignedto"]    = serviceRequest.AssignedPerson;
                incident["new_statushistory"]    = serviceRequest.CommentsMatricia;
                incident["casetypecode"]         = returnRequestKind(serviceRequest.ServiceRequestKind);
                incident["followupby"]           = serviceRequest.DueDate;
                incident["new_supportrequestid"] = serviceRequest.SRID;
                incident["title"] = serviceRequest.AssignedToClient + " " + serviceRequest.SRID + " " + serviceRequest.companyName;
                //incident["customerid"] = new EntityReference("account", findCustomer((string)serviceRequest.companyName, service));
                incident["customerid"]        = new EntityReference("account", findCustomerID(serviceRequest.companyName));
                incident["new_statushistory"] = serviceRequest.ShortDescription;
                incident["new_assignedfrom"]  = serviceRequest.CreatedBy;

                Guid consultantID = findConsultantID(serviceRequest.AssignedPerson, service);


                //Adding the created case to CRM;
                var incidentGuid = service.Create(incident);

                //Assign a case!
                EventLog.saveMessage("Start of Assignment! to :" + consultantID);
                AssignRequest assignRequest = new AssignRequest();
                assignRequest.Assignee = new EntityReference("systemuser", consultantID);
                assignRequest.Target   = new EntityReference(incident.LogicalName, incidentGuid);

                service.Execute(assignRequest);
            }
            catch (Exception)
            {
                EventLog.saveMessage("This case was not created in CRM " + serviceRequest.CreatedBy + "'" + serviceRequest.SRID);;
            }
        }
예제 #26
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            WriteVerbose(string.Format("Creating Entity: {0}", EntityObject));

            Guid id = OrganizationService.Create(EntityObject);

            WriteObject(id);

            WriteVerbose(string.Format("Entity Created: {0}", EntityObject));
        }
예제 #27
0
        private bool CreateReport(Guid solutionId, string uniqueName, string name, string filePath, string relativePath, int viewableIndex)
        {
            try
            {
                CrmConnection connection = CrmConnection.Parse(_connection.ConnectionString);

                using (_orgService = new OrganizationService(connection))
                {
                    Entity report = new Entity("report");
                    report["name"]           = name;
                    report["bodytext"]       = File.ReadAllText(filePath);
                    report["reporttypecode"] = new OptionSetValue(1); //ReportingServicesReport
                    report["filename"]       = Path.GetFileName(filePath);
                    report["languagecode"]   = 1033;                  //TODO: handle multiple
                    report["ispersonal"]     = (viewableIndex == 0);

                    Guid id = _orgService.Create(report);

                    _logger.WriteToOutputWindow("Report Created: " + id, Logger.MessageType.Info);

                    //Add to the choosen solution (not default)
                    if (solutionId != new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238"))
                    {
                        AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest
                        {
                            ComponentType      = 31,
                            SolutionUniqueName = uniqueName,
                            ComponentId        = id
                        };
                        AddSolutionComponentResponse response =
                            (AddSolutionComponentResponse)_orgService.Execute(scRequest);

                        _logger.WriteToOutputWindow("New Report Added To Solution: " + response.id, Logger.MessageType.Info);
                    }

                    NewId         = id;
                    NewName       = name;
                    NewBoudndFile = relativePath;

                    return(true);
                }
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Creating Report: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return(false);
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Creating Report: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return(false);
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();


            var newTheme = new Entity("theme");

            newTheme.Id                            = Theme.Id;
            newTheme["name"]                       = Theme.Name;
            newTheme["headercolor"]                = Theme.HeaderColor;
            newTheme["hoverlinkeffect"]            = Theme.HoverLinkEffect;
            newTheme["logoid"]                     = new EntityReference("webresource", Theme.LogoId);
            newTheme["logotooltip"]                = Theme.LogoToolTip;
            newTheme["maincolor"]                  = Theme.MainColor;
            newTheme["navbarbackgroundcolor"]      = Theme.NavBarBackgroundColor;
            newTheme["navbarshelfcolor"]           = Theme.NavBarShelfColor;
            newTheme["pageheaderbackgroundcolor"]  = Theme.PageHeaderBackgroundColor;
            newTheme["panelheaderbackgroundcolor"] = Theme.PanelHeaderBackgroundColor;
            newTheme["processcontrolcolor"]        = Theme.ProcessControlColor;
            newTheme["selectedlinkeffect"]         = Theme.SelectedLinkEffect;
            newTheme["accentcolor"]                = Theme.AccentColor;
            newTheme["backgroundcolor"]            = Theme.BackgroundColor;
            newTheme["controlborder"]              = Theme.ControlBorder;
            newTheme["controlshade"]               = Theme.ControlShade;
            newTheme["defaultcustomentitycolor"]   = Theme.DefaultCustomEntityColor;
            newTheme["defaultentitycolor"]         = Theme.DefaultEntityColor;
            newTheme["globallinkcolor"]            = Theme.GlobalLinkColor;

            bool exists = false;

            try
            {
                var existsTheme = OrganizationService.Retrieve("theme", Theme.Id, new ColumnSet(true));
                exists = true;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Does Not Exist"))
                {
                    base.WriteVerbose(string.Format("Creating new Theme"));
                    OrganizationService.Create(newTheme);
                }
            }

            if (exists)
            {
                base.WriteVerbose(string.Format("Updating existing Theme"));
                OrganizationService.Update(newTheme);
            }


            base.WriteVerbose(string.Format("Theme Imported"));
        }
        public void PerformTestSetup()
        {
            MessageName = "Delete";

            var entityToCreate = new Entity("contact");

            entityToCreate.Attributes.Add("firstname", "DummyFirstName");
            entityToCreate.Attributes.Add("lastname", "DeleteRequest");

            entityToCreate.Id = OrganizationService.Create(entityToCreate);

            EntityReferenceToDelete = new EntityReference(entityToCreate.LogicalName, entityToCreate.Id);
        }
        private Entity CreateContact()
        {
            Entity newRecord = new Entity("contact");

            newRecord["firstname"]        = "Mr Test";
            newRecord["lastname"]         = "Emails";
            newRecord["emailaddress1"]    = "*****@*****.**";
            newRecord["parentcustomerid"] = CreateAccount().ToEntityReference();

            newRecord.Id = OrganizationService.Create(newRecord);

            return(newRecord);
        }
예제 #31
0
        //public static ListItem GetQuestion(int QuestionID)
        //{

        //    using (ClientContext ctx = new ClientContext(_serverURL))
        //    {
        //        SecureString passWord = new SecureString();
        //        foreach (char c in _userPasswordAdmin) passWord.AppendChar(c);
        //        ctx.Credentials = new SharePointOnlineCredentials(_userNameAdmin, passWord);


        //        List oList = ctx.Web.Lists.GetByTitle("Question Flow");

        //       ListItem collListItem = oList.GetItemById(QuestionID);
        //        ctx.Load(collListItem);

        //        ctx.ExecuteQuery();

        //            return collListItem;
        //    }

        //}

        public static void SaveNewAnswer(string selectedFlowType, string InputTit, string Desc, bool Usertype, string SubmittedBy, string filename)
        {
            try
            {
                var connection = CrmConnection.Parse("Url=https://kbschatbot.crm4.dynamics.com; [email protected]; Password=Demo1234;");// ; DeviceID=xxx-ws00001; DevicePassword=xxxx");
                OrganizationService _Service = new OrganizationService(connection);

                Entity account = new Entity("account");
                account["name"] = "BotName";
                Guid _AccountId = _Service.Create(account);

                //Create new Case  for the above account
                Entity case1 = new Entity("incident");
                case1["title"]           = InputTit;
                case1["description"]     = Desc;
                case1["caseorigincode"]  = new OptionSetValue(100000001); // "Chatbot";
                case1["new_casetype"]    = new OptionSetValue(100000000); //selectedFlowType;
                case1["new_submittedby"] = SubmittedBy;
                case1["new_anonymous"]   = Usertype;
                if (Usertype == true)
                {
                    case1["new_an"] = new OptionSetValue(100000001);
                }
                else
                {
                    case1["new_an"] = new OptionSetValue(100000000);
                }


                EntityReference primaryContactId = new EntityReference("account", _AccountId);
                case1["customerid"] = primaryContactId;
                Guid _CaseId = _Service.Create(case1);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #32
0
        public void AddRemarksForEntry(Guid entryID,  Annotation data, string Username, string Password)
        {
            Entity note = new Entity("annotation");

            note["objectid"] = new EntityReference("gsc_timeentry", entryID);
            note["subject"] = data.Subject;
            note["notetext"] = data.NoteText;

            string Url = ConfigurationManager.AppSettings["Url"].ToString();
            string CrmConnectionString = string.Format("Url={0}; Username={1}; Password={2}",
                                                        Url, Username, Password);
            CrmConnection crmConnection = null;
            crmConnection = CrmConnection.Parse(CrmConnectionString);
            OrganizationService service = new OrganizationService(crmConnection);

            service.Create(note);
        }
        public string Post([FromBody] FormDataCollection formValues)
        {
            string domain = HttpContext.Current.Request.Headers["Origin"].ToLower();
            string host = HttpContext.Current.Request.Url.Host.ToLower();
            //if (!domain.Contains("jlleadform.azurewebsites.net") && !domain.Contains(host))
            //    return "fail!";

            CrmConnection connection = CrmConnection.Parse(
                ConfigurationManager.ConnectionStrings["CRMOnlineO365"].ConnectionString);

            using (_orgService = new OrganizationService(connection))
            {
                Entity lead = new Entity("lead");
                lead["firstname"] = formValues.Get("FirstName");
                lead["lastname"] = formValues.Get("LastName");

                _orgService.Create(lead);
            }
            return "success";
        }
        private WebResource CreateWebResource(string fileName, OrganizationService orgService, string filePath)
        {
            var createWebresoruce = new CreateWebResourceWindow(fileName);
            createWebresoruce.ShowDialog();

            if (createWebresoruce.CreatedWebResource == null)
                return null;

            var createdWebresource = createWebresoruce.CreatedWebResource;
            createdWebresource.Content = GetEncodedFileContents(filePath);
            createdWebresource.Id = orgService.Create(createdWebresource);
            return createdWebresource;
        }
    //Takes as input a username, password, email, password question and answer of type string; a boolean value for approval, a provider user key object, and a status variable of type Membership Create Status
    //Returns a Membership user after creating a new user account in CRM with the specified input (userame, password, email, password question and answer)
    public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
    {
        using (OrganizationService service = new OrganizationService(OurConnect()))
        {

            ConditionExpression usernameCondition = new ConditionExpression();
            ConditionExpression appCondition = new ConditionExpression();

            usernameCondition.AttributeName = consts.username;
            usernameCondition.Operator = ConditionOperator.Equal;
            usernameCondition.Values.Add(username);

            appCondition.AttributeName = consts.appname;
            appCondition.Operator = ConditionOperator.Equal;
            appCondition.Values.Add(_ApplicationName);

            FilterExpression filter = new FilterExpression();
            filter.Conditions.Add(usernameCondition);

            QueryExpression query = new QueryExpression(consts.useraccount);
            query.Criteria.AddFilter(filter); //query CRM with the new filter for username
            EntityCollection collection = service.RetrieveMultiple(query); //retrieve all records with same username

            if (collection.Entities.Count != 0)
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return null;
            }
            else
            {
                if (_RequiresQuestionAndAnswer)
                {
                    if (passwordAnswer == null)
                    {
                        status = MembershipCreateStatus.InvalidAnswer;
                        return null;
                    }
                    if (passwordQuestion == null)
                    {
                        status = MembershipCreateStatus.InvalidQuestion;
                        return null;
                    }
                }

                if (_RequireUniqueEmail && GetUserNameByEmail(email) != null)
                {
                    status = MembershipCreateStatus.DuplicateEmail;
                    return null;
                }

                else
                {
                    if (providerUserKey == null)
                    {
                        providerUserKey = Guid.NewGuid();
                    }
                    else
                    {
                        if (!(providerUserKey is Guid))
                        {
                            status = MembershipCreateStatus.InvalidProviderUserKey;
                            return null;
                        }
                    }
                    Entity newMember = new Entity(consts.useraccount);

                    newMember[consts.accountid] = providerUserKey;
                    newMember[consts.name] = "";
                    newMember[consts.username] = username;
                    newMember[consts.password] = password;
                    newMember[consts.email] = email;
                    newMember[consts.securityquestion] = passwordQuestion;
                    newMember[consts.securityanswer] = passwordAnswer;
                    newMember[consts.appname] = _ApplicationName;
                    newMember[consts.deleteduser] = false;
                    newMember[consts.lockn] = false;
                    newMember[consts.online] = true;
                    newMember[consts.loginattempts] = 0;

                    Guid _accountID = service.Create(newMember);
                    status = MembershipCreateStatus.Success;
                    activity(username, "Created On", false);

                    return GetUser(username);
                }
            }
        }
    }
    /*ACTIVITIES*/
    protected void activity(string username, string message, bool isUpdate)
    {
        using (OrganizationService service = new OrganizationService(OurConnect()))
        {
            Entity newActivity = new Entity(consts.activities);

            newActivity[consts.activitytime] = DateTime.Now;
            newActivity[consts.activityid] = Guid.NewGuid();
            newActivity[consts.to] = username;
            newActivity[consts.from] = _ApplicationName;
            newActivity[consts.subject] = message;

            if (message != "")
                service.Create(newActivity);

            if (isUpdate)
            {
                newActivity[consts.subject] = "Modified";
                service.Create(newActivity);
            }

            return;
        }
    }
    private Guid GetUniqueID(string username, bool isAuthenticated, bool ignoreAuthenticationType)
    {
        if (username == null)
            throw new ArgumentNullException("User name cannot be null.");
        using (OrganizationService service = new OrganizationService(OurConnect()))
        {
            ConditionExpression usernameCondition = new ConditionExpression();
            ConditionExpression appCondition = new ConditionExpression();

            usernameCondition.AttributeName = consts.username;
            usernameCondition.Operator = ConditionOperator.Equal;
            usernameCondition.Values.Add(username);

            appCondition.AttributeName = consts.appname;
            appCondition.Operator = ConditionOperator.Equal;
            appCondition.Values.Add(_ApplicationName);

            FilterExpression filter = new FilterExpression();
            filter.Conditions.Add(usernameCondition);
            filter.Conditions.Add(appCondition);

            if (!ignoreAuthenticationType)
            {
                ConditionExpression isanonymousCondition = new ConditionExpression();

                isanonymousCondition.AttributeName = consts.isanonymous;
                isanonymousCondition.Operator = ConditionOperator.Equal;
                isanonymousCondition.Values.Add(!isAuthenticated);

                filter.Conditions.Add(isanonymousCondition);

            }

            QueryExpression query = new QueryExpression(consts.userprofile);
            query.ColumnSet.AddColumn(consts.profileid);
            query.Criteria.AddFilter(filter);
            EntityCollection collection = service.RetrieveMultiple(query);

            Guid uniqueID;
            if (collection.Entities.Count != 0)
                uniqueID = (Guid)collection.Entities[0][consts.profileid];
            else
            {
                Entity newProfile = new Entity(consts.userprofile);

                newProfile[consts.username] = username;
                newProfile[consts.appname] = _ApplicationName;
                newProfile[consts.isanonymous] = !isAuthenticated;

                uniqueID = (Guid)service.Create(newProfile);

                activity(username, "Profile Created", true);
            }

            return uniqueID;
        }
    }
예제 #38
0
        public static void Main()
        {
            //get the config data
            GetConfig();

            //connect to rabbitmq
            Console.WriteLine("Connecting . . .");
            var factory = new ConnectionFactory();
            factory.HostName = _brokerEndpoint;
            factory.UserName = _brokerUser;
            factory.Password = _brokerPassword;
            factory.VirtualHost = "/"; //assumes we use the default vhost
            factory.Protocol = Protocols.DefaultProtocol; //assumes we use the default protocol
            factory.Port = AmqpTcpEndpoint.UseDefaultPort; //assumes we use the default port
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //wait for some messages
                    var consumer = new QueueingBasicConsumer(channel);
                    channel.BasicConsume(_queue, false, consumer);

                    Console.WriteLine(" [*] Waiting for messages. To exit press CTRL+C");
                    
                    //instantiate crm org service
                    using (OrganizationService service = new OrganizationService(_targetConn))
                    {
                        while (true)
                        {
                            //get the message from the queue
                            var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                            var body = ea.Body;
                            var message = Encoding.UTF8.GetString(body);

                            try
                            {
                                //deserialize message json to object
                                LeadType lead = JsonConvert.DeserializeObject<LeadType>(message);

                                try
                                {
                                    //create record in crm
                                    Entity entity = new Entity("lead");
                                    entity["firstname"] = lead.FirstName;
                                    entity["lastname"] = lead.LastName;
                                    entity["subject"] = lead.Topic;
                                    entity["companyname"] = lead.Company;
                                    service.Create(entity);

                                    //write success message to cli
                                    Console.WriteLine("Created lead: {0} {1}", lead.FirstName, lead.LastName);

                                    //IMPORTANT - tell the queue the message was processed successfully so it doesn't get requeued
                                    channel.BasicAck(ea.DeliveryTag, false);
                                }
                                catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                                {
                                    //return error - note no confirmation is sent to the queue, so the message will be requeued
                                    Console.WriteLine("Could not create lead: {0} {1}", lead.FirstName, lead.LastName);
                                    Console.WriteLine("Error: {0}", ex.Message);
                                }
                            }
                            catch(Exception ex)
                            {
                                //return error - note no confirmation is sent to the queue, so the message will be requeued
                                Console.WriteLine("Could not process message from queue");
                                Console.WriteLine("Error: {0}", ex.Message);
                            }
                        }
                    }
                }
            }
        }
        private bool CreateReport(Guid solutionId, string uniqueName, string name, string filePath, string relativePath, int viewableIndex)
        {
            try
            {
                CrmConnection connection = CrmConnection.Parse(_connection.ConnectionString);

                using (_orgService = new OrganizationService(connection))
                {
                    Entity report = new Entity("report");
                    report["name"] = name;
                    report["bodytext"] = File.ReadAllText(filePath);
                    report["reporttypecode"] = new OptionSetValue(1); //ReportingServicesReport
                    report["filename"] = Path.GetFileName(filePath);
                    report["languagecode"] = 1033; //TODO: handle multiple 
                    report["ispersonal"] = (viewableIndex == 0);

                    Guid id = _orgService.Create(report);

                    _logger.WriteToOutputWindow("Report Created: " + id, Logger.MessageType.Info);

                    //Add to the choosen solution (not default)
                    if (solutionId != new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238"))
                    {
                        AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest
                        {
                            ComponentType = 31,
                            SolutionUniqueName = uniqueName,
                            ComponentId = id
                        };
                        AddSolutionComponentResponse response =
                            (AddSolutionComponentResponse)_orgService.Execute(scRequest);

                        _logger.WriteToOutputWindow("New Report Added To Solution: " + response.id, Logger.MessageType.Info);
                    }

                    NewId = id;
                    NewName = name;
                    NewBoudndFile = relativePath;

                    return true;
                }
            }
            catch (FaultException<OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Creating Report: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return false;
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Creating Report: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return false;
            }
        }
예제 #40
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the source connection string: ");
            sourceOrg = Console.ReadLine();
            try
            {
                sourceConn = CrmConnection.Parse(sourceOrg);
            }
            catch(Exception ex)
            {
                Console.WriteLine("Could not parse source connection string: {0}", ex.Message);
                return;
            }

            Console.WriteLine("Enter the destination connection string: ");
            targetOrg = Console.ReadLine();
            try
            {
                targetConn = CrmConnection.Parse(targetOrg);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not parse destination connection string: {0}", ex.Message);
                return;
            }

            //export teamtemplates
            using (OrganizationService service = new OrganizationService(sourceConn))
            {
                try
                {
                    //attributes to exclude from the query
                    List<string> IgnoredAttributes = new List<string> { "issystem" };

                    Console.WriteLine("Retrieving entity metadata . . .");
                    RetrieveEntityRequest entityreq = new RetrieveEntityRequest
                    {
                        LogicalName = "teamtemplate",
                        EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes
                    };
                    RetrieveEntityResponse entityres = (RetrieveEntityResponse)service.Execute(entityreq);
                    string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
                    fetchXml += "<entity name='teamtemplate'>";

                    foreach (AttributeMetadata amd in entityres.EntityMetadata.Attributes)
                    {
                        if (!IgnoredAttributes.Contains(amd.LogicalName))
                        {
                            fetchXml += "<attribute name='" + amd.LogicalName + "' />";
                            //Console.WriteLine(amd.LogicalName);
                        }
                    }
                    fetchXml += "</entity></fetch>";

                    Console.WriteLine("");
                    Console.WriteLine("Exporting data . . .");
                    exported = service.RetrieveMultiple(new FetchExpression(fetchXml));
                }
                catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                {
                    Console.WriteLine("Could not export data: {0}", ex.Message);
                    return;
                }
            }

            //import teamtemplates
            Console.WriteLine("Importing data . . .");
            using (OrganizationService service = new OrganizationService(targetConn))
            {
                if (exported.Entities.Count > 0)
                {
                    foreach (Entity entity in exported.Entities)
                    {
                        try
                        {
                            //Console.WriteLine("Id - {0}", entity.Id.ToString());

                            //try to update first
                            try
                            {
                                service.Update(entity);
                            }
                            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
                            {
                                //if update fails, then create
                                service.Create(entity);
                            }
                        }
                        catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                        {
                            //if everything fails, return error
                            Console.WriteLine("Error: {0} - {1}", entity.Id, entity["teamtemplatename"]);
                        }
                    }
                }
            }
            Console.WriteLine("Import complete");
            Console.WriteLine("");
            Console.WriteLine("Press the enter key to exit");
            Console.ReadLine();
        }
예제 #41
0
        private static void SetAnnotationToSprava()
        {
            var service = new OrganizationService(connection);
            var dataFromXmlx = new Program().ExcelOpenSpreadsheets(@"C:\Users\savchinvv\Desktop\Примечания.xlsx");

            for (int i = 2; i < dataFromXmlx.Tables[0].Rows.Count; i++)
            {
                if (!string.IsNullOrWhiteSpace(dataFromXmlx.Tables[0].Rows[i][0].ToString()))
                {
                    var sprava = ToSpravaEntity(dataFromXmlx.Tables[0].Rows[i][1].ToString());
                    if (sprava != null)
                    {
                        var createAnn = new Annotation()
                        {
                            NoteText = dataFromXmlx.Tables[0].Rows[i][0].ToString(),
                            ObjectId = sprava,
                            ObjectTypeCode = new_spravastr.EntityLogicalName
                        };
                        service.Create(createAnn);
                        Console.WriteLine("{0} - добавлен Анотатион", dataFromXmlx.Tables[0].Rows[i][1].ToString());
                    }
                }
            }
        }
예제 #42
0
        /// <summary>
        /// runs the import process
        /// </summary>
        public void Process()
        {
            logger = LogManager.GetLogger(typeof(Importer));
            LogMessage("INFO", "starting job");
            ParseConnections();

            SetupGuidMappings();

            LogMessage("INFO","processing records");
            OrganizationService sourceService = new OrganizationService(_sourceConn);
            OrganizationService targetService = new OrganizationService(_targetConn);

            foreach (var item in JobSteps)
            {
                JobStep step = (JobStep)item;
                LogMessage("INFO",string.Format("starting step {0}", step.StepName));
                string fetchQuery = step.StepFetch;

                LogMessage("INFO","  retrieving records");

                // Set the number of records per page to retrieve.
                int fetchCount = 5000;
                
                // Initialize the page number.
                int pageNumber = 1;

                // Specify the current paging cookie. For retrieving the first page, 
                // pagingCookie should be null.
                string pagingCookie = null;

                //create a list of entities to hold retrieved entities so we can page through results
                List<Entity> ec = new List<Entity>();

                while (true)
                {
                    // Build fetchXml string with the placeholders.
                    string fetchXml = CreateXml(fetchQuery, pagingCookie, pageNumber, fetchCount);

                    EntityCollection retrieved = sourceService.RetrieveMultiple(new FetchExpression(fetchXml));
                    ec.AddRange(retrieved.Entities);

                    if (retrieved.MoreRecords)
                    {
                        // Increment the page number to retrieve the next page.
                        pageNumber++;

                        // Set the paging cookie to the paging cookie returned from current results.                            
                        pagingCookie = retrieved.PagingCookie;
                    }
                    else
                    {
                        // If no more records in the result nodes, exit the loop.
                        break;
                    }
                }

                LogMessage("INFO",string.Format("  {0} records retrieved", ec.Count));
                if (ec.Count > 0)
                {
                    foreach (Entity entity in ec)
                    {
                        //create a list to hold the replacement guids. a second pass is required because c# disallows modifying a collection while enumerating
                        List<KeyValuePair<string, object>> guidsToUpdate = new List<KeyValuePair<string, object>>();
                        LogMessage("INFO",string.Format("  processing record {0}, {1}", entity.Id, entity.LogicalName));
                        try
                        {
                            LogMessage("INFO","    processing GUID replacements");
                            foreach (KeyValuePair<string, object> attribute in entity.Attributes)
                            {
                                //LogMessage("INFO",string.Format("Attribute - {0} {1}", attribute.Key, attribute.Value.GetType().ToString()));
                                if (attribute.Value is Microsoft.Xrm.Sdk.EntityReference)
                                {
                                    //LogMessage("INFO","getting source");

                                    EntityReference source = ((EntityReference)attribute.Value);
                                    try
                                    {
                                        //LogMessage("INFO","looking for GUID replacement");
                                        Guid sourceId = source.Id;
                                        Guid targetId = _mappings.Find(t => t.sourceId == source.Id).targetId;
                                        source.Id = targetId;
                                        guidsToUpdate.Add(new KeyValuePair<string, object>(attribute.Key, source));
                                        //LogMessage("INFO",string.Format("replacement found - {0} -> {1}", sourceId, targetId));
                                    }
                                    catch (System.NullReferenceException ex)
                                    {
                                        //LogMessage("INFO", "NullReferenceException happened");
                                        //do nothing because nullreferenceexception means there's no guid mapping to use
                                    }
                                }
                            }

                            //now actually update the GUIDs with the mapped values
                            foreach (KeyValuePair<string, object> attribute in guidsToUpdate)
                            {
                                //LogMessage("INFO",string.Format("    replacing attribute GUID {0} {1}", attribute.Key, attribute.Value));
                                entity[attribute.Key] = attribute.Value;
                            }

                            //try to update first
                            try
                            {
                                LogMessage("INFO","    trying target update");
                                targetService.Update(entity);
                                LogMessage("INFO","    update ok");
                            }
                            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                            {
                                if (!step.UpdateOnly)
                                {
                                    LogMessage("INFO","    trying target create");
                                    //if update fails and step is not update-only then try to create
                                    targetService.Create(entity);
                                    LogMessage("INFO","    create ok");
                                }
                                else
                                {
                                    throw new FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>(ex.Detail);
                                }
                            }
                        }
                        catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                        {
                            //if everything fails, log error
                            //to main log
                            LogMessage("ERROR", string.Format("    record transfer failed"));

                            //to record error log
                            LogMessage("ERROR", string.Format("RECORD ERROR: {0}, {1}", entity.Id, entity.LogicalName));

                            //increment the error count
                            _errorCount++;
                        }
                    }
                }
            }
            LogMessage("INFO","job complete");
            logger.Logger.Repository.Shutdown();
        }
        private bool CreateWebResource(Guid solutionId, string uniqueName, int type, string prefix, string name, string displayName, string filePath, string relativePath)
        {
            try
            {
                CrmConnection connection = CrmConnection.Parse(_connection.ConnectionString);

                using (_orgService = new OrganizationService(connection))
                {
                    Entity webResource = new Entity("webresource");
                    webResource["name"] = prefix + name;
                    webResource["webresourcetype"] = new OptionSetValue(type);
                    if (!string.IsNullOrEmpty(displayName))
                        webResource["displayname"] = displayName;

                    if (type == 8)
                        webResource["silverlightversion"] = "4.0";

                    string extension = Path.GetExtension(filePath);

                    List<string> imageExs = new List<string>() { ".ICO", ".PNG", ".GIF", ".JPG" };
                    string content;
                    //TypeScript
                    if (extension != null && (extension.ToUpper() == ".TS"))
                    {
                        content = File.ReadAllText(Path.ChangeExtension(filePath, ".js"));
                        webResource["content"] = EncodeString(content);
                    }
                    //Images
                    else if (extension != null && imageExs.Any(s => extension.ToUpper().EndsWith(s)))
                    {
                        content = EncodedImage(filePath, extension);
                        webResource["content"] = content;
                    }
                    //Everything else
                    else
                    {
                        content = File.ReadAllText(filePath);
                        webResource["content"] = EncodeString(content);
                    }

                    Guid id = _orgService.Create(webResource);

                    _logger.WriteToOutputWindow("New Web Resource Created: " + id, Logger.MessageType.Info);

                    //Add to the choosen solution (not default)
                    if (solutionId != new Guid("FD140AAF-4DF4-11DD-BD17-0019B9312238"))
                    {
                        AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest
                        {
                            ComponentType = 61,
                            SolutionUniqueName = uniqueName,
                            ComponentId = id
                        };
                        AddSolutionComponentResponse response =
                            (AddSolutionComponentResponse)_orgService.Execute(scRequest);

                        _logger.WriteToOutputWindow("New Web Resource Added To Solution: " + response.id, Logger.MessageType.Info);
                    }

                    NewId = id;
                    NewType = type;
                    NewName = prefix + name;
                    if (!string.IsNullOrEmpty(displayName))
                        NewDisplayName = displayName;
                    NewBoundFile = relativePath;
                    NewSolutionId = solutionId;

                    return true;
                }
            }
            catch (FaultException<OrganizationServiceFault> crmEx)
            {
                _logger.WriteToOutputWindow("Error Creating Web Resource: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error);
                return false;
            }
            catch (Exception ex)
            {
                _logger.WriteToOutputWindow("Error Creating Web Resource: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error);
                return false;
            }
        }
예제 #44
0
        private void UpdateTheWebresource(string selectedFilePath, string connectionString)
        {
            try
            {
                OrganizationService orgService;
                var crmConnection = CrmConnection.Parse(connectionString);
                //to escape "another assembly" exception
                crmConnection.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
                using (orgService = new OrganizationService(crmConnection))
                {
                    var isCreateRequest = false;
                    var fileName = Path.GetFileName(selectedFilePath);
                    var choosenWebresource = GetWebresource(orgService, fileName);

                    AddLineToOutputWindow("Connected to : " + crmConnection.ServiceUri);
                    if (choosenWebresource == null)
                    {
                        AddErrorLineToOutputWindow("Error : Selected file is not exist in CRM.");
                        AddLineToOutputWindow("Creating new webresource..");

                        var createWebresoruce = new CreateWebResourceWindow(fileName);
                        createWebresoruce.ShowDialog();

                        if (createWebresoruce.CreatedWebResource == null)
                        {
                            AddLineToOutputWindow("Creating new webresource is cancelled.");
                            return;
                        }

                        isCreateRequest = true;
                        choosenWebresource = createWebresoruce.CreatedWebResource;
                    }

                    choosenWebresource.Content = GetEncodedFileContents(selectedFilePath);

                    if (isCreateRequest)
                    {
                        //create function returns, created webresource's guid.
                        choosenWebresource.Id = orgService.Create(choosenWebresource);
                        AddLineToOutputWindow("Webresource is created.");
                    }
                    else
                    {
                        AddLineToOutputWindow("Updating to Webresource..");
                        var updateRequest = new UpdateRequest
                        {
                            Target = choosenWebresource
                        };
                        orgService.Execute(updateRequest);
                        AddLineToOutputWindow("Webresource is updated.");
                    }

                    AddLineToOutputWindow("Publishing the webresource..");
                    var prequest = new PublishXmlRequest
                    {
                        ParameterXml = string.Format("<importexportxml><webresources><webresource>{0}</webresource></webresources></importexportxml>", choosenWebresource.Id)
                    };
                    orgService.Execute(prequest);
                    AddLineToOutputWindow("Webresource is published.");
                }
                _myStopwatch.Stop();
                AddLineToOutputWindow(string.Format("Time : " + _myStopwatch.Elapsed));
            }
            catch (Exception ex)
            {
                AddErrorLineToOutputWindow("Error : " + ex.Message);
            }
        }
예제 #45
0
        //  < ----- )))))))))))))))))))))))))
        private static void СозданиеЗадач()
        {
            var service = new OrganizationService(connection);
            var dataFromXmlx = new Program().ExcelOpenSpreadsheets(@"C:\Users\savchinvv\Desktop\Задачи.xlsx");

            for (int i = 2; i < dataFromXmlx.Tables[0].Rows.Count; i++)
            {
                var newTask = new SoftLine.Models.Task()
                {
                    Subject = dataFromXmlx.Tables[0].Rows[i][0].ToString(),
                    RegardingObjectId = ToSpravaEntity(dataFromXmlx.Tables[0].Rows[i][1].ToString()),
                    PriorityCode = ToOptionSetValue(dataFromXmlx.Tables[0].Rows[i][2].ToString()),
                    ScheduledEnd = FindDate(dataFromXmlx.Tables[0].Rows[i][3].ToString()),
                    ScheduledStart = FindDate(dataFromXmlx.Tables[0].Rows[i][4].ToString()),
                    ActualDurationMinutes = ToInt32(dataFromXmlx.Tables[0].Rows[i][5].ToString()),
                    Description = dataFromXmlx.Tables[0].Rows[i][6].ToString(),
                    PercentComplete = ToInt32(dataFromXmlx.Tables[0].Rows[i][7].ToString()),
                    ActualStart = FindDate(dataFromXmlx.Tables[0].Rows[i][9].ToString()),
                    ActualEnd = FindDate(dataFromXmlx.Tables[0].Rows[i][10].ToString())
                };
                var id = service.Create(newTask);
                Console.WriteLine("{0} - созданая Задача", dataFromXmlx.Tables[0].Rows[i][0].ToString());
                bool? status = false;
                if (dataFromXmlx.Tables[0].Rows[i][8].ToString() == "Завершено")
                {
                    status = ChangeStateCode(id);
                }
                Console.WriteLine("Задача = StatusChange->{0}", status ?? null);
            }
        }
        public void Create(string entityName, [FromBody] JObject objStructure)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString;
            
            CrmConnection crmConnection = CrmConnection.Parse(connectionString);
            using (OrganizationService service = new OrganizationService(crmConnection))
            {
                if (objStructure != null)
                {
                    Entity entity = new Entity(entityName);
                    Guid guidValue;

                    foreach (var attribute in objStructure)
                    {
                        if (Guid.TryParse(attribute.Value.ToString(), out guidValue))
                        {
                            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
                            {
                                EntityLogicalName = entityName,
                                LogicalName = attribute.Key.ToString(),
                                RetrieveAsIfPublished = true
                            };

                            // Execute the request
                            RetrieveAttributeResponse attributeResponse =
                                (RetrieveAttributeResponse)service.Execute(attributeRequest);

                            if (attributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.Lookup)
                            {
                                string relatedEntityName =
                                    ((LookupAttributeMetadata)(attributeResponse.AttributeMetadata)).Targets[0];

                                EntityReference eref = new EntityReference(relatedEntityName, guidValue);
                                entity[attribute.Key.ToString()] = eref;
                                continue;
                            }
                        }

                        entity[attribute.Key.ToString()] = attribute.Value.ToString();
                    }

                    service.Create(entity);
                }
            }
        }
예제 #47
0
        private static void LoadSprava()
        {
            var service = new OrganizationService(connection);
            var context = new CrmOrganizationServiceContext(connection);

            var dataFromXmlx = new Program().ExcelOpenSpreadsheets(@"C:\Users\savchinvv\Desktop\Дела_юр.xlsx");

            for (int i = 37; i < dataFromXmlx.Tables[0].Rows.Count; i++)
            {
                var newSprava = new new_spravastr()
                {
                    new_businessnumber = dataFromXmlx.Tables[0].Rows[i][0].ToString(),
                    new_nameid = FindClient(dataFromXmlx.Tables[0].Rows[i][1].ToString()),
                    new_partnercustomer = FindAccount(dataFromXmlx.Tables[0].Rows[i][2].ToString()),
                    new_typeofbusiness = EntityForm(dataFromXmlx.Tables[0].Rows[i][3].ToString()),
                    new_type_of_business = CheckType(dataFromXmlx.Tables[0].Rows[i][4].ToString()),
                    new_priority = ToInt32(dataFromXmlx.Tables[0].Rows[i][5].ToString()),
                    new_state = FindState(dataFromXmlx.Tables[0].Rows[i][6].ToString()),
                    new_creationdate = FindDate(dataFromXmlx.Tables[0].Rows[i][7].ToString()),
                    new_liquidated = FindBit(dataFromXmlx.Tables[0].Rows[i][8].ToString()),
                    new_gai = FindGos(dataFromXmlx.Tables[0].Rows[i][9].ToString()),
                    new_datedtp = FindDate(dataFromXmlx.Tables[0].Rows[i][10].ToString()),
                    new_Dateagreement = FindDate(dataFromXmlx.Tables[0].Rows[i][11].ToString()),
                    new_date_of_birth = FindDate(dataFromXmlx.Tables[0].Rows[i][12].ToString()),
                    new_date_death = FindDate(dataFromXmlx.Tables[0].Rows[i][13].ToString()),
                    new_pledge = dataFromXmlx.Tables[0].Rows[i][14].ToString(),
                    new_property1 = dataFromXmlx.Tables[0].Rows[i][15].ToString(),
                    new_property2 = dataFromXmlx.Tables[0].Rows[i][16].ToString(),
                    new_taxnumber = dataFromXmlx.Tables[0].Rows[i][17].ToString(),
                    new_code = dataFromXmlx.Tables[0].Rows[i][18].ToString(),
                    new_placedtp = dataFromXmlx.Tables[0].Rows[i][19].ToString(),
                    new_locality = dataFromXmlx.Tables[0].Rows[i][20].ToString(),
                    new_home = dataFromXmlx.Tables[0].Rows[i][21].ToString(),
                    new_Place_of_work_1 = dataFromXmlx.Tables[0].Rows[i][22].ToString(),
                    new_Place_of_work_2 = dataFromXmlx.Tables[0].Rows[i][23].ToString(),
                    new_Companyname = dataFromXmlx.Tables[0].Rows[i][24].ToString(),
                    new_insurancecompany = dataFromXmlx.Tables[0].Rows[i][25].ToString(),
                    new_taxaddress = dataFromXmlx.Tables[0].Rows[i][26].ToString(),
                    new_heir1 = FindClient(dataFromXmlx.Tables[0].Rows[i][27].ToString()),
                    new_heir2 = FindClient(dataFromXmlx.Tables[0].Rows[i][28].ToString()),
                    new_heir3 = FindClient(dataFromXmlx.Tables[0].Rows[i][29].ToString()),
                    new_Credit_agreement = dataFromXmlx.Tables[0].Rows[i][30].ToString(),
                    new_Social_security_number = dataFromXmlx.Tables[0].Rows[i][31].ToString(),
                    new_litigationnumber = dataFromXmlx.Tables[0].Rows[i][32].ToString(),
                    new_guarantor1 = FindClient(dataFromXmlx.Tables[0].Rows[i][33].ToString()),
                    new_guarantor2 = FindClient(dataFromXmlx.Tables[0].Rows[i][34].ToString()),
                    new_guarantor3 = FindClient(dataFromXmlx.Tables[0].Rows[i][35].ToString()),
                    new_amount_loan = ToDouble(dataFromXmlx.Tables[0].Rows[i][36].ToString()),
                    new_spouse = FindClient(dataFromXmlx.Tables[0].Rows[i][37].ToString()),
                    new_accident1 = FindClient(dataFromXmlx.Tables[0].Rows[i][38].ToString()),
                    new_accident2 = FindClient(dataFromXmlx.Tables[0].Rows[i][39].ToString()),
                    new_accident3 = FindClient(dataFromXmlx.Tables[0].Rows[i][40].ToString()),
                    new_accident4 = FindClient(dataFromXmlx.Tables[0].Rows[i][41].ToString()),
                    new_institution = FindGos(dataFromXmlx.Tables[0].Rows[i][42].ToString()),
                    new_amount = ToDouble(dataFromXmlx.Tables[0].Rows[i][43].ToString())
                };
                service.Create(newSprava);
                Console.WriteLine("{0} Обработан и создан: {1}", i, dataFromXmlx.Tables[0].Rows[i][0].ToString());
            }
        }
예제 #48
0
        /// <summary>
        /// The Run() method first connects to the organization service. Afterwards,
        /// basic create, retrieve, update, and delete entity operations are performed.
        /// </summary>
        /// <param name="connectionString">Provides service connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(String connectionString, bool promptforDelete)
        {
            try
            {
                // Establish a connection to the organization web service.
                Print("Connecting to the server ...");
                Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);

                // Obtain an organization service proxy.
                // The using statement assures that the service proxy will be properly disposed.
                using (_orgService = new OrganizationService(connection))
                {
                    Print("connected");
                    Print("Authenticating the user ...");

                    // Create any entity records this sample requires.
                    CreateRequiredRecords();

                    // Obtain information about the logged on user from the web service.
                    Guid userid = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId;
                    SystemUser systemUser = (SystemUser)_orgService.Retrieve("systemuser", userid,
                        new ColumnSet(new string[] { "firstname", "lastname" }));
                    Println("Logged on user is " + systemUser.FirstName + " " + systemUser.LastName + ".");

                    // Retrieve the version of Microsoft Dynamics CRM.
                    RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
                    RetrieveVersionResponse versionResponse =
                        (RetrieveVersionResponse)_orgService.Execute(versionRequest);
                    Println("Microsoft Dynamics CRM version " + versionResponse.Version + ".");

                    // Instantiate an account object. Note the use of option set enumerations defined in OptionSets.cs.
                    // Refer to the Entity Metadata topic in the SDK documentation to determine which attributes must
                    // be set for each entity.
                    Account account = new Account { Name = "Fourth Coffee" };
                    account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
                    account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

                    // Create an account record named Fourth Coffee.
                    _accountId = _orgService.Create(account);

                    Println(account.LogicalName + " " + account.Name + " created, ");

                    // Retrieve several attributes from the new account.
                    ColumnSet cols = new ColumnSet(
                        new String[] { "name", "address1_postalcode", "lastusedincampaign" });

                    Account retrievedAccount = (Account)_orgService.Retrieve("account", _accountId, cols);
                    Print("retrieved, ");

                    // Update the postal code attribute.
                    retrievedAccount.Address1_PostalCode = "98052";

                    // The address 2 postal code was set accidentally, so set it to null.
                    retrievedAccount.Address2_PostalCode = null;

                    // Shows use of a Money value.
                    retrievedAccount.Revenue = new Money(5000000);

                    // Shows use of a Boolean value.
                    retrievedAccount.CreditOnHold = false;

                    // Update the account record.
                    _orgService.Update(retrievedAccount);
                    Print("and updated.");

                    // Delete any entity records this sample created.
                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }