public void AddEntityRecord(string documentNumber, string batch, DocumentType typeOfDocument, DateTime date) { OptionSetValue documentType = new OptionSetValue { Value = (int)typeOfDocument }; Entity entityRecord = new Entity(EntityName) { Attributes = { ["acm_documentnumber"] = documentNumber, ["acm_batch"] = batch, ["acm_documenttype"] = documentType, ["acm_invalidationdate"] = date } }; Guid id = Guid.Empty; try { id = CrmService.Create(entityRecord); } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine($"RECORD CREATED - Guid: {id}"); }
/// <summary> /// 新增或编辑 logcall /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <ValidateResult <CrmEntity> > AddOrEditEntity(LogCallRequest request) { var validateResult = new ValidateResult <CrmEntity>(); var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); try { Guid guid = string.IsNullOrEmpty(request.mcs_logcallid) ? Guid.NewGuid() : Guid.Parse(request.mcs_logcallid); CrmExecuteEntity Entity = new CrmExecuteEntity("mcs_logcall", guid); if (!string.IsNullOrEmpty(request.mcs_onlyleadid)) { Entity.Attributes.Add("mcs_onlyleadid", new CrmEntityReference("mcs_onlylead", Guid.Parse(request.mcs_onlyleadid))); } if (!string.IsNullOrEmpty(request.accountid)) { Entity.Attributes.Add("mcs_accountid", new CrmEntityReference("account", Guid.Parse(request.accountid))); } if (!string.IsNullOrEmpty(request.mcs_content)) { Entity.Attributes.Add("mcs_content", request.mcs_content); } if (!string.IsNullOrEmpty(request.mcs_fullname)) { Entity.Attributes.Add("mcs_fullname", request.mcs_fullname); } if (!string.IsNullOrEmpty(request.mcs_mobilephone)) { Entity.Attributes.Add("mcs_mobilephone", request.mcs_mobilephone); } if (!string.IsNullOrEmpty(request.mcs_results)) { Entity.Attributes.Add("mcs_results", request.mcs_results); } if (request.mcs_visittime.HasValue) { Entity.Attributes.Add("mcs_visittime", request.mcs_visittime.Value); } if (!string.IsNullOrEmpty(request.mcs_logcallid)) { await _crmService.Update(Entity, userInfo?.systemuserid); } else { guid = await _crmService.Create(Entity, userInfo?.systemuserid); } validateResult.Result = true; validateResult.Description = "操作成功"; } catch (Exception ex) { validateResult.Result = false; validateResult.Description = "操作失败,原因:" + ex.Message; throw ex; } return(validateResult); }
private void ImportRecord(DynamicEntity entity) { string statecode = ""; int statuscode = -1; if (entity.Properties.Contains("statecode")) { statecode = entity["statecode"].ToString(); entity.Properties.Remove("statecode"); } if (entity.Properties.Contains("statuscode")) { statuscode = ((Status)entity["statuscode"]).Value; entity.Properties.Remove("statuscode"); } string primaryAttribute = MetadataUtility.RetrievePrimaryAttribute(_metadataService, entity.Name); string primaryAttributeValue = entity.Properties.Contains(primaryAttribute) ? entity[primaryAttribute].ToString() : ""; Guid id = entity.Properties.OfType <KeyProperty>().First().Value.Value; Guid potentialNewId = Guid.Empty; int matchingRecordCount = GetMatchingRecordCount(entity.Name, id, primaryAttributeValue, ref potentialNewId); switch (matchingRecordCount) { case 0: _crmService.Create(entity); ReportDetail(String.Format("Created {0} with id of {1}.", entity.Name, id)); break; case 1: if (potentialNewId != Guid.Empty) { id = potentialNewId; entity.Properties.OfType <KeyProperty>().First().Value.Value = potentialNewId; } _crmService.Update(entity); ReportDetail(String.Format("Updated {0} with id of {1}.", entity.Name, id)); break; default: ReportError(String.Format("Cannot import {0} with id of {1} because it matches more than one record in the target system based on attribute {2}.", entity.Name, id, primaryAttribute)); break; } if (matchingRecordCount < 2 && !String.IsNullOrEmpty(statecode)) { DynamicEntityUtility.SetStateDynamicEntity(_crmService, entity.Name, id, statecode, statuscode); ReportDetail(String.Format("Set state on {0} with id of {1}.", entity.Name, id)); } _currentRecordCount++; _entityRecordCounts[entity.Name]++; int percent = (int)Math.Round(100.0 * _currentRecordCount / _totalRecordCount); percent = percent > 100 ? 100 : percent; OnImportProgressChanged(new ProgressChangedEventArgs(percent, null)); }
/// <summary> /// 新建附件 /// </summary> /// <param name="model"></param> /// <returns></returns> public async Task <ValidateResult> Add(List <AttachmentAddResponse> model) { var validateResult = new ValidateResult(); try { foreach (var item in model) { var entity = new CrmExecuteEntity("mcs_attachment", Guid.NewGuid()); if (item.attrname != null) { entity.Attributes.Add(item.attrname, new CrmEntityReference(item.entitylookup, Guid.Parse(item.id))); } if (item.filename != null) { entity.Attributes.Add("mcs_filename", item.filename); } if (item.filesize != null) { entity.Attributes.Add("mcs_filesize", item.filesize); } entity.Attributes.Add("mcs_filetype", item.filename.Split('.')[1]); if (item.url != null) { entity.Attributes.Add("mcs_fileurl", item.url); } if (item.mcs_partnertype != null) { entity.Attributes.Add("mcs_partnertype", item.mcs_partnertype); } if (item.mcs_filecategory != null) { entity.Attributes.Add("mcs_filecategory", item.mcs_filecategory); } await _crmService.Create(entity, null); } #region 组装数据返回 validateResult.Result = true; validateResult.Description = "操作成功"; #endregion } catch (Exception e) { validateResult.Result = false; validateResult.Description = e.Message; } return(validateResult); }
public static void AddNoteToLead(CrmService service, Guid leadID, string noteText) { try { var annotation = new annotation(); annotation.notetext = noteText; annotation.objectid = new Lookup { Value = leadID, type = EntityName.lead.ToString() }; var annotationId = service.Create(annotation); } catch (Exception ex) { throw ex; } }
/// <summary> /// Метод создает новую запись сущности "contact". /// </summary> /// <param name="contactModel">Объект модели контакта.</param> public void AddContactToCrm(ContactEntityModel contactModel) { // Получаем токен. var token = new CrmAuthenticationToken { AuthenticationType = 0, OrganizationName = "AdventureWorksCycle" }; var connectionString = System.Configuration.ConfigurationManager. ConnectionStrings["CrmConnection"].ConnectionString; // Получаем сервис организации CRM. var service = new CrmService { Url = connectionString, CrmAuthenticationTokenValue = token, Credentials = System.Net.CredentialCache.DefaultCredentials }; // Создаем новую запись. var newContact = new contact { firstname = contactModel.ContactFirstName, lastname = contactModel.ContactLastName, mobilephone = contactModel.MobilePhone, emailaddress1 = contactModel.Email, jobtitle = contactModel.JobTitle }; if (contactModel.BirthDay.HasValue) { newContact.birthdate = CrmDateTime.FromUser(contactModel.BirthDay.Value); } service.Create(newContact); }
public Guid Create(BusinessEntity entity) { return(_service.Create(entity)); }
/// <summary> /// 创建试乘试驾预约 /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <ValidateResult <CrmEntity> > CreateTestDrive(TestDriveViewModel request) { var validateResult = new ValidateResult <CrmEntity>(); var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); try { Guid mcs_driverecordid = string.IsNullOrEmpty(request.mcs_driverecordid) ? Guid.NewGuid() : Guid.Parse(request.mcs_driverecordid); CrmExecuteEntity Entity = new CrmExecuteEntity("mcs_driverecord", mcs_driverecordid); if (!string.IsNullOrEmpty(request.mcs_fullname)) { Entity.Attributes.Add("mcs_fullname", request.mcs_fullname); } if (!string.IsNullOrEmpty(request.mcs_mobilephone)) { Entity.Attributes.Add("mcs_mobilephone", request.mcs_mobilephone); } if (!string.IsNullOrEmpty(request.mcs_carmodel)) { Entity.Attributes.Add("mcs_carmodel", new CrmEntityReference("mcs_carmodel", Guid.Parse(request.mcs_carmodel))); } if (!string.IsNullOrEmpty(request.mcs_businesstype)) { Entity.Attributes.Add("mcs_businesstype", request.mcs_businesstype); } if (!string.IsNullOrEmpty(request.mcs_dealerid)) { Entity.Attributes.Add("mcs_dealerid", new CrmEntityReference("mcs_dealer", Guid.Parse(request.mcs_dealerid))); } if (request.mcs_ordertime.HasValue) { Entity.Attributes.Add("mcs_ordertime", request.mcs_ordertime.Value); } if (!string.IsNullOrEmpty(request.mcs_testdrivetime)) { Entity.Attributes.Add("mcs_testdrivetime", new CrmEntityReference("mcs_reservationconfiguration", Guid.Parse(request.mcs_testdrivetime))); } if (!string.IsNullOrEmpty(request.UserId)) { Entity.Attributes.Add("mcs_userid", request.UserId); } if (!string.IsNullOrEmpty(request.mcs_driverecordid)) { await _crmService.Update(Entity, userInfo?.systemuserid); } else { mcs_driverecordid = await _crmService.Create(Entity, userInfo?.systemuserid); //预约成功后 进行留资 if (mcs_driverecordid != null) { CreateLead(request, userInfo?.systemuserid); } } validateResult.Result = true; validateResult.Description = "操作成功"; } catch (Exception ex) { validateResult.Result = false; validateResult.Description = "操作失败,原因:" + ex.Message; throw ex; } return(validateResult); }
public String CreateConfig(Guid new_config_allid, Config config) { Guid configid = new_config_allid; try { DynamicEntity conf = new DynamicEntity("new_reestr"); conf.Name = "new_reestr"; CrmConnection crmc = new CrmConnection("Crm"); CrmService crmService = crmc.CreateCrmService(); if (new_config_allid == new Guid("{00000000-0000-0000-0000-000000000000}")) { configid = crmService.Create(conf); } // Создаем экземпляр динамческого объекта и указываем его имя DynamicEntity myDEUpdate = new DynamicEntity(); myDEUpdate.Name = "new_config_allid"; // Создаем KeyProperty для хранения GUID’а обновляемой записи KeyProperty myConfigGuid = new KeyProperty(); myConfigGuid.Name = "new_config_allid"; // Указываем GUID обновляемой записи Key myConfigKey = new Key(); myConfigKey.Value = configid; myConfigGuid.Value = myConfigKey; myDEUpdate.Properties.Add(myConfigGuid); //if (conf.new_count != 0) // myDEUpdate.Properties.Add(new CrmNumberProperty("new_count", new CrmNumber(conf.new_count))); ////Кем выдан //if (conf.new_giveoutby != null) // myDEUpdate.Properties.Add(new StringProperty("new_giveoutby", contact.new_giveoutby)); ////День рождения //if (contact.birthdate != null) // myDEUpdate.Properties.Add(new CrmDateTimeProperty("birthdate", CrmDateTime.FromUser(DateTime.ParseExact(contact.birthdate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); crmService.Update(myDEUpdate); //поиск контакта для переназначения ответственного, если таковой меняется Owner ownerID = new Owner(); if (new_config_allid != new Guid("{00000000-0000-0000-0000-000000000000}")) { try { string ln = ""; //фамилия BusinessEntityCollection fcontact = searchContact(new_config_allid.ToString()); foreach (DynamicEntity cont1 in fcontact.BusinessEntities) { ln = cont1["lastname"].ToString(); if (cont1.Properties.Contains("ownerid")) { ownerID = (Owner)cont1["ownerid"]; } } logger.Info($"Нашли контакт {ln}. ownerid={ownerID.Value.ToString()}"); } catch (Exception ex) { logger.Error($"Ошибка: {ex.ToString()}"); } } return(configid.ToString()); } catch (SoapException ex) { logger.Error($"Ошибка: {ex.Detail.InnerText}"); return(ex.Detail.InnerText); } }
public string Pay(Reestr r) { logger.Info("_______pay______"); logger.Info(r.txn_id); logger.Info(r.txn_date); logger.Info(r.opportunityID); logger.Info(r.sum); logger.Info("_______pay______"); String errormsg = ""; BusinessEntityCollection opportunity; BusinessEntityCollection existing_reestr; try { existing_reestr = searchnew_reestr(r.txn_id); foreach (Microsoft.Crm.Sdk.DynamicEntity reestr in existing_reestr.BusinessEntities) { errormsg = $"Реестра оплат с именем {r.txn_id} уже существует. new_reestrid: {((Microsoft.Crm.Sdk.Key)((reestr).Properties["new_reestrid"])).Value.ToString()}"; logger.Error(errormsg); return(errormsg); } } catch (Exception ex) { errormsg = $"Не удалось осуществить поиск Реестра оплат с txn_id={r.txn_id}. Ошибка: {ex.Message}"; logger.Error(errormsg); return(errormsg); } try { Opp opp = new Opp(); opportunity = opp.searchOpportunity(r.opportunityID.ToString()); } catch (Exception ex) { errormsg = $"Не удалось осуществить поиск договора № {r.opportunityID.ToString()}. Ошибка: {ex.Message}"; logger.Error(errormsg); return(errormsg); } CrmConnection crmc = new CrmConnection("Crm"); CrmService crmService = crmc.CreateCrmService(); DynamicEntity new_reestr = new DynamicEntity("new_reestr"); new_reestr.Name = "new_reestr"; foreach (Microsoft.Crm.Sdk.DynamicEntity opp in opportunity.BusinessEntities) { try { // new_reestr.Properties.Add(new CrmDateTimeProperty("new_data", CrmTypes.CreateCrmDateTimeFromUser(DateTime.ParseExact(txn_date, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); new_reestr.Properties.Add(new CrmDateTimeProperty("new_data", CrmDateTime.FromUser(DateTime.ParseExact(r.txn_date, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); } catch (Exception ex) { errormsg = $"Не удалось конвертировать входное значение txn_date=[{r.txn_date}] в дату. Ошибка: {ex.Message}"; logger.Error(errormsg); return(errormsg); } try { new_reestr.Properties.Add(new CrmMoneyProperty("new_summ", new CrmMoney(decimal.Parse(r.sum, CultureInfo.InvariantCulture)))); } catch (Exception ex) { errormsg = $"Не удалось конвертировать входное значение sum=[{r.sum}] в decimal. Ошибка: {ex.Message}"; logger.Error(errormsg); return(errormsg); } new_reestr.Properties.Add(new PicklistProperty("new_source", new Picklist(10)));//Интернет - эквайринг new_reestr.Properties.Add(new StringProperty("new_name", r.txn_id.ToString())); new_reestr.Properties.Add(new StringProperty("new_txn_id", r.txn_id.ToString())); new_reestr.Properties.Add(new LookupProperty("new_dogovor", new Lookup("opportunity", ((Microsoft.Crm.Sdk.Key)(((Microsoft.Crm.Sdk.DynamicEntity)opportunity.BusinessEntities[0]).Properties["opportunityid"])).Value))); if (opp.Properties.Contains("new_signdate")) { new_reestr.Properties.Add(new CrmDateTimeProperty("new_data_dogovor", (CrmDateTime)opp["new_signdate"])); } if (opp.Properties.Contains("customerid")) { Customer customer = (Customer)opp["customerid"]; new_reestr.Properties.Add(new LookupProperty("new_customerid", new Lookup(customer.type, customer.Value))); } if (opp.Properties.Contains("new_programsidcost")) { Lookup lu = (Lookup)opp["new_programsidcost"]; new_reestr.Properties.Add(new LookupProperty("new_programsid", new Lookup(lu.type, lu.Value))); } if (opp.Properties.Contains("new_studyplaceid")) { Lookup lu = (Lookup)opp["new_studyplaceid"]; new_reestr.Properties.Add(new LookupProperty("new_studyplaceid", new Lookup(lu.type, lu.Value))); } if (opp.Properties.Contains("new_placeofwriteid")) { Lookup lu = (Lookup)opp["new_placeofwriteid"]; new_reestr.Properties.Add(new LookupProperty("new_placeofwriteid", new Lookup(lu.type, lu.Value))); } if (opp.Properties.Contains("ownerid")) { Owner lu = (Owner)opp["ownerid"]; new_reestr.Properties.Add(new LookupProperty("new_ownerid", new Lookup(lu.type, lu.Value))); } DateTime new_month_income = DateTime.ParseExact(r.txn_date, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); new_month_income = new_month_income.AddDays((new_month_income.Day * -1) + 1); new_month_income = new_month_income.AddHours((new_month_income.Hour * -1) + 12); new_reestr.Properties.Add(new CrmDateTimeProperty("new_month_income", CrmDateTime.FromUser(new_month_income))); } Guid new_reestrID = Guid.Empty; try { new_reestrID = crmService.Create(new_reestr); } catch (Exception ex) { errormsg = $"Не удалось Создать запись реестра оплат для договора № {r.opportunityID.ToString()}. Ошибка: {ex.Message}"; logger.Error(errormsg); return(errormsg); } return(new_reestrID.ToString()); }
/// <summary> /// 勘测单新增或编辑 /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <ValidateResult <CrmEntity> > AddOrEditSurveyorder(SurveyorderMetadataModel request) { var validateResult = new ValidateResult <CrmEntity>(); var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); try { Guid guid = string.IsNullOrEmpty(request.mcs_surveyorderid) ? Guid.NewGuid() : Guid.Parse(request.mcs_surveyorderid); CrmExecuteEntity Entity = new CrmExecuteEntity("mcs_surveyorder", guid); if (!string.IsNullOrEmpty(request.mcs_surveyordertype.ToString())) { int surveyordertype = Convert.ToInt32(request.mcs_surveyordertype); Entity.Attributes.Add("mcs_surveyordertype", surveyordertype); } if (!string.IsNullOrEmpty(request.mcs_accountid)) { Entity.Attributes.Add("mcs_accountid", new CrmEntityReference("account", Guid.Parse(request.mcs_accountid))); } if (!string.IsNullOrEmpty(request.mcs_username)) { Entity.Attributes.Add("mcs_username", request.mcs_username); } if (!string.IsNullOrEmpty(request.mcs_userphone)) { Entity.Attributes.Add("mcs_userphone", request.mcs_userphone); } if (!string.IsNullOrEmpty(request.mcs_idcard)) { Entity.Attributes.Add("mcs_idcard", request.mcs_idcard); } if (!string.IsNullOrEmpty(request.mcs_email)) { Entity.Attributes.Add("mcs_email", request.mcs_email); } if (!string.IsNullOrEmpty(request.mcs_carmodelid)) { Entity.Attributes.Add("mcs_carmodelid", new CrmEntityReference("mcs_carmodel", Guid.Parse(request.mcs_carmodelid))); } if (!string.IsNullOrEmpty(request.mcs_dealer)) { Entity.Attributes.Add("mcs_dealer", new CrmEntityReference("mcs_dealer", Guid.Parse(request.mcs_dealer))); } if (!string.IsNullOrEmpty(request.mcs_salesconsultant)) { Entity.Attributes.Add("mcs_salesconsultant", new CrmEntityReference("systemuser", Guid.Parse(request.mcs_salesconsultant))); } if (!string.IsNullOrEmpty(request.mcs_contactname)) { Entity.Attributes.Add("mcs_contactname", request.mcs_contactname); } if (!string.IsNullOrEmpty(request.mcs_contactphone)) { Entity.Attributes.Add("mcs_contactphone", request.mcs_contactphone); } if (!string.IsNullOrEmpty(request.mcs_contactemail)) { Entity.Attributes.Add("mcs_contactemail", request.mcs_contactemail); } if (!string.IsNullOrEmpty(request.mcs_province)) { Entity.Attributes.Add("mcs_province", new CrmEntityReference("mcs_sysarea", Guid.Parse(request.mcs_province))); } if (!string.IsNullOrEmpty(request.mcs_city)) { Entity.Attributes.Add("mcs_city", new CrmEntityReference("mcs_sysarea", Guid.Parse(request.mcs_city))); } if (!string.IsNullOrEmpty(request.mcs_area)) { Entity.Attributes.Add("mcs_area", new CrmEntityReference("mcs_sysarea", Guid.Parse(request.mcs_area))); } if (!string.IsNullOrEmpty(request.mcs_installationaddress)) { Entity.Attributes.Add("mcs_installationaddress", request.mcs_installationaddress); } if (!string.IsNullOrEmpty(request.mcs_detailaddress)) { Entity.Attributes.Add("mcs_detailaddress", request.mcs_detailaddress); } if (!string.IsNullOrEmpty(request.mcs_chargingpilemodel)) { Entity.Attributes.Add("mcs_chargingpilemodel", new CrmEntityReference("mcs_mc_chargingpilemodel", Guid.Parse(request.mcs_chargingpilemodel))); } if (!string.IsNullOrEmpty(request.mcs_communityname)) { Entity.Attributes.Add("mcs_communityname", request.mcs_communityname); } if (!string.IsNullOrEmpty(request.mcs_residentialnature.ToString())) { int residentialnature = Convert.ToInt32(request.mcs_residentialnature); Entity.Attributes.Add("mcs_residentialnature", residentialnature); } if (!string.IsNullOrEmpty(request.mcs_price)) { Entity.Attributes.Add("mcs_price", Convert.ToDecimal(request.mcs_price)); } if (!string.IsNullOrEmpty(request.mcs_parkingspace.ToString())) { int parkingspace = Convert.ToInt32(request.mcs_parkingspace); Entity.Attributes.Add("mcs_parkingspace", parkingspace); } if (!string.IsNullOrEmpty(request.mcs_residentialtype.ToString())) { int residentialtype = Convert.ToInt32(request.mcs_residentialtype); Entity.Attributes.Add("mcs_residentialtype", residentialtype); } if (!string.IsNullOrEmpty(request.mcs_remark)) { Entity.Attributes.Add("mcs_remark", request.mcs_remark); } if (!string.IsNullOrEmpty(request.mcs_surveyorderid)) { await _crmService.Update(Entity, userInfo?.systemuserid); } else { guid = await _crmService.Create(Entity, userInfo?.systemuserid); } validateResult.Result = true; validateResult.Description = "操作成功"; } catch (Exception ex) { validateResult.Result = false; validateResult.Description = "操作失败,原因:" + ex.Message; throw ex; } return(validateResult); }
/// <summary> /// 创建或编辑实体 /// </summary> /// <param name="crmEntity"></param> /// <returns></returns> public async Task <Guid> AddOrEditEntity(AccountRequest request) { Guid guid = Guid.Empty; try { guid = string.IsNullOrEmpty(request.Id) ? Guid.NewGuid() : Guid.Parse(request.Id); CrmExecuteEntity createorUpdateEntity = new CrmExecuteEntity(EntityName, guid); if (!string.IsNullOrEmpty(request.name)) { createorUpdateEntity.Attributes.Add("name", request.name); } if (!string.IsNullOrEmpty(request.mcs_onlyleadid)) { createorUpdateEntity.Attributes.Add("mcs_onlyleadid", new CrmEntityReference("mcs_onlylead", Guid.Parse(request.mcs_onlyleadid))); } if (!string.IsNullOrEmpty(request.mcs_vehcolorid)) { createorUpdateEntity.Attributes.Add("mcs_vehcolorid", new CrmEntityReference("mcs_vehiclecolor", Guid.Parse(request.mcs_vehcolorid))); } if (!string.IsNullOrEmpty(request.mcs_vehtypeid)) { createorUpdateEntity.Attributes.Add("mcs_vehtypeid", new CrmEntityReference("mcs_vehicletype", Guid.Parse(request.mcs_vehtypeid))); } if (!string.IsNullOrEmpty(request.mcs_carattention)) { createorUpdateEntity.Attributes.Add("mcs_carattention", request.mcs_carattention); } if (!string.IsNullOrEmpty(request.mcs_competingtype)) { createorUpdateEntity.Attributes.Add("mcs_competingtype", request.mcs_competingtype); } if (!string.IsNullOrEmpty(request.mcs_introducecarowner)) { createorUpdateEntity.Attributes.Add("mcs_introducecarowner", request.mcs_introducecarowner); } if (!string.IsNullOrEmpty(request.mcs_mobilephone)) { createorUpdateEntity.Attributes.Add("mcs_mobilephone", request.mcs_mobilephone); } if (!string.IsNullOrEmpty(request.mcs_estimatedtransactiondate)) { createorUpdateEntity.Attributes.Add("mcs_estimatedtransactiondate", DateTime.Parse(request.mcs_estimatedtransactiondate)); } if (request.mcs_carereason.HasValue) { createorUpdateEntity.Attributes.Add("mcs_carereason", request.mcs_carereason.Value); } if (request.mcs_gender.HasValue) { createorUpdateEntity.Attributes.Add("mcs_gender", request.mcs_gender.Value); } if (request.mcs_generation.HasValue) { createorUpdateEntity.Attributes.Add("mcs_generation", request.mcs_generation.Value); } if (request.mcs_idtype.HasValue) { createorUpdateEntity.Attributes.Add("mcs_idtype", request.mcs_idtype.Value); } if (request.mcs_level.HasValue) { createorUpdateEntity.Attributes.Add("mcs_level", request.mcs_level.Value); } if (request.mcs_purchasepurpose.HasValue) { createorUpdateEntity.Attributes.Add("mcs_purchasepurpose", request.mcs_purchasepurpose.Value); } if (request.mcs_purchaseway.HasValue) { createorUpdateEntity.Attributes.Add("mcs_purchaseway", request.mcs_purchaseway.Value); } if (request.mcs_vehicleusers.HasValue) { createorUpdateEntity.Attributes.Add("mcs_vehicleusers", request.mcs_vehicleusers.Value); } if (request.mcs_familymembernum.HasValue) { createorUpdateEntity.Attributes.Add("mcs_familymembernum", request.mcs_familymembernum.Value); } if (!string.IsNullOrEmpty(request.description)) { createorUpdateEntity.Attributes.Add("description", request.description); } if (request.mcs_customerstatus.HasValue) { createorUpdateEntity.Attributes.Add("mcs_customerstatus", request.mcs_customerstatus.Value); } //if (request.ownerid.HasValue) //{ // createorUpdateEntity.Attributes.Add("ownerid", new CrmEntityReference("systemuser", request.ownerid.Value)); //} var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); if (userInfo != null && userInfo.systemuserid.HasValue) { createorUpdateEntity.Attributes.Add("ownerid", new CrmEntityReference("systemuser", userInfo.systemuserid.Value)); } if (!string.IsNullOrEmpty(request.Id)) { await _crmService.Update(createorUpdateEntity); } else { guid = await _crmService.Create(createorUpdateEntity); } } catch (Exception ex) { throw ex; } return(guid); }
public String CreateContact(Guid contact_ID, Contact contact) { Guid contactid = contact_ID; try { contact cont = new contact(); CrmConnection crmc = new CrmConnection("Crm"); CrmService crmService = crmc.CreateCrmService(); if (contact_ID == new Guid("{00000000-0000-0000-0000-000000000000}")) { contactid = crmService.Create(cont); } // Создаем экземпляр динамческого объекта и указываем его имя DynamicEntity myDEUpdate = new DynamicEntity(); myDEUpdate.Name = "contact"; // Создаем KeyProperty для хранения GUID’а обновляемой записи KeyProperty myContactGuid = new KeyProperty(); myContactGuid.Name = "contactid"; // Указываем GUID обновляемой записи Key myContactKey = new Key(); myContactKey.Value = contactid; myContactGuid.Value = myContactKey; myDEUpdate.Properties.Add(myContactGuid); if (contact.address1_city != null) { myDEUpdate.Properties.Add(new StringProperty("address1_city", contact.address1_city)); } if (contact.address1_country != null) { myDEUpdate.Properties.Add(new StringProperty("address1_country", contact.address1_country)); } if (contact.address1_line1 != null) { myDEUpdate.Properties.Add(new StringProperty("address1_line1", contact.address1_line1)); } if (contact.address1_name != null) { myDEUpdate.Properties.Add(new StringProperty("address1_name", contact.address1_name)); } if (contact.address1_postalcode != null) { myDEUpdate.Properties.Add(new StringProperty("address1_postalcode", contact.address1_postalcode)); } if (contact.emailaddress1 != null) { myDEUpdate.Properties.Add(new StringProperty("emailaddress1", contact.emailaddress1)); } if (contact.firstname != null) { myDEUpdate.Properties.Add(new StringProperty("firstname", contact.firstname)); } if (contact.lastname != null) { myDEUpdate.Properties.Add(new StringProperty("lastname", contact.lastname)); } if (contact.middlename != null) { myDEUpdate.Properties.Add(new StringProperty("middlename", contact.middlename)); } if (contact.mobilephone != null) { myDEUpdate.Properties.Add(new StringProperty("mobilephone", contact.mobilephone)); } if (contact.salutation != null) { myDEUpdate.Properties.Add(new StringProperty("salutation", contact.salutation)); } //Кем выдан if (contact.new_giveoutby != null) { myDEUpdate.Properties.Add(new StringProperty("new_giveoutby", contact.new_giveoutby)); } //Номер if (contact.new_nomer != null) { myDEUpdate.Properties.Add(new StringProperty("new_nomer", contact.new_nomer)); } //Серия if (contact.new_seria != null) { myDEUpdate.Properties.Add(new StringProperty("new_seria", contact.new_seria)); } //Пол if (contact.gendercode != 0) { myDEUpdate.Properties.Add(new PicklistProperty("gendercode", new Picklist(contact.gendercode))); } //Гражданство if (contact.new_nationality != 0) { myDEUpdate.Properties.Add(new PicklistProperty("new_nationality", new Picklist(contact.new_nationality))); } //Тип ФЛ if (contact.new_type != 0) { myDEUpdate.Properties.Add(new PicklistProperty("new_type", new Picklist(contact.new_type))); } //Семейное положение if (contact.familystatuscode != 0) { myDEUpdate.Properties.Add(new PicklistProperty("familystatuscode", new Picklist(contact.familystatuscode))); } //День рождения if (contact.birthdate != null) { myDEUpdate.Properties.Add(new CrmDateTimeProperty("birthdate", CrmDateTime.FromUser(DateTime.ParseExact(contact.birthdate, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); } //Посетил открытый урок if (contact.new_openles != null) { myDEUpdate.Properties.Add(new CrmDateTimeProperty("new_openles", CrmDateTime.FromUser(DateTime.ParseExact(contact.new_openles, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); } //Дата выдачи if (contact.new_dategiveout != null) { myDEUpdate.Properties.Add(new CrmDateTimeProperty("new_dategiveout", CrmDateTime.FromUser(DateTime.ParseExact(contact.new_dategiveout, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)))); } crmService.Update(myDEUpdate); //поиск контакта для переназначения ответственного, если таковой меняется Owner ownerID = new Owner(); if (contact_ID != new Guid("{00000000-0000-0000-0000-000000000000}")) { try { string ln = ""; //фамилия BusinessEntityCollection fcontact = searchContact(contact_ID.ToString()); foreach (DynamicEntity cont1 in fcontact.BusinessEntities) { ln = cont1["lastname"].ToString(); if (cont1.Properties.Contains("ownerid")) { ownerID = (Owner)cont1["ownerid"]; } } logger.Info($"Нашли контакт {ln}. ownerid={ownerID.Value.ToString()}"); } catch (Exception ex) { logger.Error($"Ошибка: {ex.ToString()}"); } } if (contact.ownerid != new Guid("{00000000-0000-0000-0000-000000000000}")) { if (ownerID.Value != contact.ownerid) { TargetOwnedContact target = new TargetOwnedContact(); SecurityPrincipal assignee = new SecurityPrincipal(); assignee.Type = SecurityPrincipalType.User; assignee.PrincipalId = contact.ownerid; target.EntityId = contactid; AssignRequest assign = new AssignRequest(); assign.Assignee = assignee; assign.Target = target; AssignResponse res = (AssignResponse)crmService.Execute(assign); } } return(contactid.ToString()); } catch (SoapException ex) { logger.Error($"Ошибка: {ex.Detail.InnerText}"); return(ex.Detail.InnerText); } }
/// <summary> /// 试乘试驾新增修改 /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <ValidateResult <CrmEntity> > AddOrEdit(DriveRecordAddOrEditRequest request) { var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); if (userInfo != null && !string.IsNullOrWhiteSpace(userInfo.mcs_dealerid)) { request.driveRecord.mcs_dealerid = Guid.Parse(userInfo.mcs_dealerid); } if (userInfo != null && userInfo.systemuserid != null) { request.driveRecord.mcs_consultantid = userInfo.systemuserid; } var validateResult = new ValidateResult <CrmEntity>(); var reusetCrmEntity = new CrmEntity("mcs_driverecord", new Guid()); //新增预约单 if (request.driveRecord.mcs_driverecordid == null) { var createEntity = new CrmExecuteEntity("mcs_driverecord", Guid.NewGuid()); //预约状态 创建默认是已提交 createEntity.Attributes.Add("mcs_drivestatus", 10); BasicAssignment(createEntity, request); await _crmService.Create(createEntity, userInfo?.systemuserid); reusetCrmEntity.Id = createEntity.Id; } //编辑预约单 if (request.driveRecord.mcs_driverecordid != null) { var updateEntity = new CrmExecuteEntity("mcs_driverecord", (Guid)request.driveRecord.mcs_driverecordid); //预约状态 if (request.driveRecord.mcs_drivestatus != null) { updateEntity.Attributes.Add("mcs_drivestatus", request.driveRecord.mcs_drivestatus); #region 判断如果试驾结束,为用户推送试驾反馈站内信 if (request.driveRecord.mcs_drivestatus.Value == 15) { //获取试驾结束站内信发送配置json var fetchString = _driveRecordRepository.GetConfigFetchXml(DCEM_APP_DriveOverMsgJson); var fetchRequest = new CrmRetrieveMultipleFetchRequestMessage() { EntityName = "mcs_cepconfig", FetchXml = fetchString //ProxyUserId = userInfo?.systemuserid }; fetchRequest.Headers.Add(dicHeadKey, dicHead[dicHeadKey]); var fetchResponse = await _crmService.Execute(fetchRequest); var fetchResponseResult = fetchResponse as CrmRetrieveMultipleFetchResponseMessage; if (fetchResponseResult.Value.Results.Count > 0) { //获取试驾明细 var detail = GetDetail((Guid)request.driveRecord.mcs_driverecordid); if (detail != null && detail.Result.Detail.Attributes.ContainsKey("mcs_userid")) { //用户获取 fetchString = _driveRecordRepository.GetUser(detail.Result.Detail.Attributes["mcs_userid"].ToString()); fetchRequest = new CrmRetrieveMultipleFetchRequestMessage() { EntityName = "mcs_user", FetchXml = fetchString //ProxyUserId = userInfo?.systemuserid }; fetchRequest.Headers.Add(dicHeadKey, dicHead[dicHeadKey]); fetchResponse = await _crmService.Execute(fetchRequest); var responseUser = fetchResponse as CrmRetrieveMultipleFetchResponseMessage; if (responseUser.Value.Results.Count > 0)//判断试驾用户信息是否存在 { var obj = JsonConvert.DeserializeObject <DriveRecordEndSendMsg>(fetchResponseResult.Value.Results[0].Attributes["mcs_val"].ToString()); var createUsermsgEntity = new CrmExecuteEntity("mcs_user_msg", Guid.NewGuid()); createUsermsgEntity.Attributes.Add("mcs_name", obj.mcs_name); createUsermsgEntity.Attributes.Add("mcs_content", obj.mcs_content); createUsermsgEntity.Attributes.Add("mcs_type", 2); createUsermsgEntity.Attributes.Add("mcs_readstatus", 0); var mcs_url = string.Format(obj.mcs_url, responseUser.Value.Results[0].Attributes["mcs_code"], detail.Result.Detail.Attributes["mcs_name"]); createUsermsgEntity.Attributes.Add("mcs_url", mcs_url); var UserEntityEF = new CrmEntityReference("mcs_user", responseUser.Value.Results[0].Id); createUsermsgEntity.Attributes.Add("mcs_user", UserEntityEF); await _crmService.Create(createUsermsgEntity); } } } } #endregion } BasicAssignment(updateEntity, request); await _crmService.Update(updateEntity, userInfo?.systemuserid); reusetCrmEntity.Id = (Guid)request.driveRecord.mcs_driverecordid; } validateResult.Data = reusetCrmEntity; validateResult.Result = true; validateResult.Description = "操作成功"; return(validateResult); }