public Execute ( OrganizationRequest request ) : OrganizationResponse | ||
request | OrganizationRequest | |
Résultat | OrganizationResponse |
/// <summary> /// 唯一线索列表查询 /// </summary> /// <param name="onlyLeadRequest"></param> /// <returns></returns> public async Task <QueryResult <CrmEntity> > QueryList(OnlyLeadRequest onlyLeadRequest) { try { var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); var fetchString = _onlyLeadRepository.QueryList(onlyLeadRequest); var fetchXdoc = XDocument.Parse(fetchString); var fetchRequest = new CrmRetrieveMultipleFetchRequestMessage() { EntityName = "mcs_onlylead", FetchXml = fetchXdoc, ProxyUserId = userInfo?.systemuserid }; fetchRequest.Headers.Add(dicHeadKey, dicHead[dicHeadKey]); var fetchResponse = await _crmService.Execute(fetchRequest); var fetchResponseResult = fetchResponse as CrmRetrieveMultipleFetchResponseMessage; var queryResult = new QueryResult <CrmEntity>(); queryResult.Results = fetchResponseResult.Value.Results; queryResult.CurrentPage = onlyLeadRequest.PageIndex; queryResult.TotalCount = 0; return(queryResult); } catch (Exception ex) { throw ex; } }
/// <summary> /// 勘测单列表查询 /// </summary> /// <param name="_request"></param> /// <returns></returns> public async Task <QueryResult <CrmEntity> > GetSurveyorderList(SurveyorderListRequest _request) { try { var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); if (userInfo != null) { _request.mcs_dealerid = userInfo.mcs_dealerid; } var fetchString = _InstallationRepository.GetSurveyorderList(_request); var fetchXdoc = XDocument.Parse(fetchString); var fetchRequest = new CrmRetrieveMultipleFetchRequestMessage() { EntityName = "mcs_surveyorder", FetchXml = fetchXdoc, ProxyUserId = userInfo != null ? userInfo.systemuserid : null }; var fetchResponse = await _crmService.Execute(fetchRequest); var fetchResponseResult = fetchResponse as CrmRetrieveMultipleFetchResponseMessage; var queryResult = new QueryResult <CrmEntity>(); queryResult.Results = fetchResponseResult.Value.Results; queryResult.CurrentPage = _request.PageIndex; queryResult.TotalCount = 0; return(queryResult); } catch (Exception ex) { throw ex; } }
/// <summary> /// 销售机会列表查询 /// </summary> /// <param name="AccountRequest"></param> /// <returns></returns> public async Task <QueryResult <CrmEntity> > QueryList(AccountSearhRequest accountRequest) { try { var fetchString = _AccountRepository.QueryList(accountRequest); var userInfo = ContextContainer.GetValue <UserInfo>(ContextExtensionTypes.CurrentUserInfo); var fetchXdoc = XDocument.Parse(fetchString); var fetchRequest = new CrmRetrieveMultipleFetchRequestMessage() { EntityName = EntityName, FetchXml = fetchXdoc, ProxyUserId = userInfo != null ? userInfo.systemuserid : null }; var fetchResponse = await _crmService.Execute(fetchRequest); var fetchResponseResult = fetchResponse as CrmRetrieveMultipleFetchResponseMessage; var queryResult = new QueryResult <CrmEntity>(); queryResult.Results = fetchResponseResult.Value.Results; queryResult.CurrentPage = accountRequest.PageIndex; queryResult.TotalCount = 0; return(queryResult); } catch (Exception ex) { throw ex; } }
// crm service /// <summary> /// Retrieve Entity from Crm service proxy /// </summary> /// <param name="cservice">Crm Service proxy</param> /// <param name="entityName">Entity Name</param> /// <param name="entityGuid">Entity Guid (String)</param> /// <returns></returns> public static DynamicEntity RetriveDynamicEntity(this CrmService cservice, String entityName, String entityGuid) { // Create/Set the Target object. TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic { EntityName = entityName, EntityId = new Guid(entityGuid) }; // Create/Set the Retrieve object. RetrieveRequest retrieve = new RetrieveRequest { Target = targetRetrieve, //ColumnSet = new AllColumns(), ReturnDynamicEntities = true // Indicate that the BusinessEntity should be retrieved as a DynamicEntity. }; // Execute the request. RetrieveResponse retrieved = (RetrieveResponse)cservice.Execute(retrieve); // Extract the DynamicEntity from the request. DynamicEntity retriveEntity = (DynamicEntity)retrieved.BusinessEntity; return(retriveEntity); }
public static DynamicEntity GetById(CrmService crmService, string entityName, Guid id, params string[] fields) { QueryExpression query = new QueryExpression(entityName) { ColumnSet = new ColumnSet(fields), }; ConditionExpression keyExpression = new ConditionExpression(entityName + "id", ConditionOperator.Equal, id); FilterExpression filterExpression = new FilterExpression(); filterExpression.Conditions.Add(keyExpression); query.Criteria.AddFilter(filterExpression); RetrieveMultipleRequest request = new RetrieveMultipleRequest() { Query = query, ReturnDynamicEntities = true }; RetrieveMultipleResponse response = (RetrieveMultipleResponse)crmService.Execute(request); if (response.BusinessEntityCollection.BusinessEntities.Count > 0) { return(response.BusinessEntityCollection.BusinessEntities[0] as DynamicEntity); } return(null); }
public static void SetStateDynamicEntity(CrmService crmService, string entityName, Guid id, string statecode, int statuscode) { DynamicEntity currentRecord = GetById(crmService, entityName, id, "statecode", "statuscode"); bool shouldUpdateState = true; if (currentRecord != null && currentRecord.Properties.Contains("statecode") && currentRecord.Properties.Contains("statuscode")) { if (statecode != currentRecord.Properties["statecode"].ToString() || statuscode != ((Status)currentRecord.Properties["statuscode"]).Value) { shouldUpdateState = true; } else { shouldUpdateState = false; } } if (shouldUpdateState) { SetStateDynamicEntityRequest request = new SetStateDynamicEntityRequest() { Entity = new Moniker(entityName, id), State = statecode, }; if (statuscode != -1) { request.Status = statuscode; } crmService.Execute(request); } }
// crm service /// <summary> /// Retrieve Entity from Crm service proxy /// </summary> /// <param name="cservice">Crm Service proxy</param> /// <param name="entityName">Entity Name</param> /// <param name="entityGuid">Entity Guid (Guid)</param> /// <returns></returns> public static DynamicEntity RetriveDynamicEntity(this CrmService cservice, String entityName, Guid entityGuid, Boolean retrieveAllColumns) { // Create/Set the Target object. TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic { EntityName = entityName, EntityId = (entityGuid) }; // Create/Set the Retrieve object. RetrieveRequest retrieve = new RetrieveRequest(); retrieve.Target = targetRetrieve; if (retrieveAllColumns == true) { retrieve.ColumnSet = new AllColumns(); } //// Indicate to retrieve all columns retrieve.ReturnDynamicEntities = true; // Indicate that the BusinessEntity should be retrieved as a DynamicEntity. // Execute the request. RetrieveResponse retrieved = (RetrieveResponse)cservice.Execute(retrieve); // Extract the DynamicEntity from the request. DynamicEntity retriveEntity = (DynamicEntity)retrieved.BusinessEntity; return(retriveEntity); }
public void DeleteAllEntityRecords() { if (Logging) { Console.WriteLine("DELETING ALL ENTITY RECORDS"); } BulkDeleteRequest request = new BulkDeleteRequest { JobName = "Delete All", ToRecipients = new Guid[] { }, CCRecipients = new Guid[] { }, RecurrencePattern = string.Empty, QuerySet = new[] { new QueryExpression { EntityName = EntityName } } }; CrmService.Execute(request); if (Logging) { Console.WriteLine("DELETE REQUEST SENT TO THE SERVER"); } }
private List <BusinessEntity> RetrieveAllRecords(string entityName) { RetrieveMultipleResponse getAllRecordsResponse = null; List <BusinessEntity> results = new List <BusinessEntity>(); int page = 1; string pagingCookie = ""; QueryExpression getAllRecordsQuery = new QueryExpression(entityName) { ColumnSet = GetColumnsForExport(entityName) }; RetrieveMultipleRequest getAllRecordsRequest = new RetrieveMultipleRequest() { ReturnDynamicEntities = true }; do { getAllRecordsQuery.PageInfo = new PagingInfo(); getAllRecordsQuery.PageInfo.Count = 5000; getAllRecordsQuery.PageInfo.PageNumber = page; getAllRecordsQuery.PageInfo.PagingCookie = pagingCookie; getAllRecordsRequest.Query = getAllRecordsQuery; getAllRecordsResponse = (RetrieveMultipleResponse)_crmService.Execute(getAllRecordsRequest); results.AddRange(getAllRecordsResponse.BusinessEntityCollection.BusinessEntities); page++; pagingCookie = getAllRecordsResponse.BusinessEntityCollection.PagingCookie; }while(getAllRecordsResponse.BusinessEntityCollection.MoreRecords); return(results); }
public void DeleteEntityRecords() { CsvReader csvrdr = new CsvReader(); csvrdr.DownloadBaseCsvFiles(); var collection = csvrdr.ReadCsv("op_vse"); var requestWithResults = new ExecuteMultipleRequest() { // Assign settings that define execution behavior: continue on error, return responses. Settings = new ExecuteMultipleSettings() { ContinueOnError = false, ReturnResponses = true }, // Create an empty organization request collection. Requests = new OrganizationRequestCollection() }; EntityCollection entityCollection = new EntityCollection() { EntityName = "acm_listinvaliddocument" }; foreach (var item in collection) { if (!string.IsNullOrEmpty(item.DocumentId)) { Entity tempEntity = new Entity("acm_listinvaliddocument") { Attributes = { ["acm_documentnumber"] = item.DocumentId, ["acm_documenttype"] = DocumentType.WithoutSeries, ["acm_invalidationdate"] = item.InvalidationDate } }; entityCollection.Entities.Add(tempEntity); } Console.WriteLine(item.DocumentId); } foreach (var entity in entityCollection.Entities) { //RetrieveMultipleRequest and then delete DeleteRequest deleteRequest = new DeleteRequest { new EntityReference() }; requestWithResults.Requests.Add(deleteRequest); } CrmService.Execute(requestWithResults); }
public override string[] GetUsersInRole(string roleName) { Assert.ArgumentNotNull(roleName, "roleName"); ConditionalLog.Info(string.Format("GetUsersInRole({0}). Started.", roleName), this, TimerAction.Start, "getUsersInRole"); string text = base.CacheService.MembersCache.Get(roleName); if (text != null) { ConditionalLog.Info(string.Format("GetUsersInRole({0}). Finished (users have been retrieved from cache).", roleName), this, TimerAction.Stop, "getUsersInRole"); return(text.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)); } // set up a query for the list to check type ColumnSet columnSet = new ColumnSet(); columnSet.Attributes = new string[] { "listname", "query", "type" }; QueryExpression query = new QueryExpression(); query.ColumnSet = columnSet; ConditionExpression listnameCondition = new ConditionExpression(); listnameCondition.AttributeName = "listname"; listnameCondition.Operator = ConditionOperator.Equal; listnameCondition.Values = new String[] { roleName }; FilterExpression filterList = new FilterExpression(); filterList.Conditions = new ConditionExpression[] { listnameCondition }; filterList.FilterOperator = LogicalOperator.And; query.EntityName = "list"; query.Criteria = filterList; // Execute the query RetrieveMultipleRequest req = new RetrieveMultipleRequest(); req.Query = query; req.ReturnDynamicEntities = true; RetrieveMultipleResponse res = (RetrieveMultipleResponse)CrmService.Execute(req); if (res.BusinessEntityCollection.BusinessEntities.GetLength(0) > 0) { DynamicEntity myList = (DynamicEntity)res.BusinessEntityCollection.BusinessEntities[0]; } return(base.GetUsersInRole(roleName)); }
private string GetLogicalCollectionName(string entity) { var request = new RetrieveEntityRequest { EntityFilters = EntityFilters.Attributes, LogicalName = entity }; var response = (RetrieveEntityResponse)CrmService.Execute(request); IsCustomEntity = response.EntityMetadata.IsCustomEntity ?? false; return(response.EntityMetadata.LogicalCollectionName); }
public async void CreateLead(TestDriveViewModel request, Guid?userid) { try { var createEntity = new CrmExecuteEntity("lead", Guid.NewGuid()); createEntity.Attributes.Add("lastname", request.mcs_fullname); createEntity.Attributes.Add("mobilephone", request.mcs_mobilephone); if (!string.IsNullOrEmpty(request.mcs_dealerid)) { createEntity.Attributes.Add("mcs_dealerid", new CrmEntityReference("mcs_dealer", Guid.Parse(request.mcs_dealerid))); } #region 用户行为赋值 var fetchString = _Repository.GetDriveBehavior("test_drive_appointment"); var fetchXdoc = XDocument.Parse(fetchString); var fetchRequest = new CrmRetrieveMultipleFetchRequestMessage() { EntityName = "mcs_behavior", FetchXml = fetchXdoc }; var fetchResponse = await _crmService.Execute(fetchRequest); var fetchResponseResult = fetchResponse as CrmRetrieveMultipleFetchResponseMessage; var queryResult = new QueryResult <CrmEntity>(); queryResult.Results = fetchResponseResult.Value.Results; var mcs_behaviorid = queryResult.Results[0].Id; createEntity.Attributes.Add("mcs_behaviorid", new CrmEntityReference("mcs_behavior", mcs_behaviorid)); #endregion var entityId = await _crmService.Create(createEntity, userid); } catch (Exception ex) { } }
private bool CanConnect(string connectionString) { try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var crmServiceClient = new CrmServiceClient(connectionString); CrmService = XrmHelper.GetIOrganizationService(crmServiceClient); CrmService.Execute(new WhoAmIRequest()); return(true); } catch { return(false); } }
public static DynamicEntity SelectLead(CrmService service, Dictionary <string, string> attributeDetails) { DynamicEntity de = null; try { var conditionExpressions = new List <ConditionExpression>(); foreach (KeyValuePair <string, string> attr in attributeDetails) { var queryCondition = new ConditionExpression { AttributeName = attr.Key, Operator = ConditionOperator.Equal, Values = new object[] { attr.Value } }; conditionExpressions.Add(queryCondition); } var filterExpression = new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = conditionExpressions.ToArray() }; var queryExpression = new QueryExpression { EntityName = EntityName.lead.ToString(), ColumnSet = new AllColumns(), Criteria = filterExpression }; var request = new RetrieveMultipleRequest { Query = queryExpression, ReturnDynamicEntities = true }; var response = (RetrieveMultipleResponse)service.Execute(request); if (response.BusinessEntityCollection.BusinessEntities.Length > 0) { de = (DynamicEntity)response.BusinessEntityCollection.BusinessEntities[0]; } } catch (Exception ex) { throw ex; } return(de); }
private bool CanConnect(CrmConnection crmConnection) { try { var connectionString = XrmHelper.BuildConnectionString(crmConnection.Type, crmConnection.Url, crmConnection.UserName, crmConnection.Password); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var crmServiceClient = new CrmServiceClient(connectionString); CrmService = XrmHelper.GetIOrganizationService(crmServiceClient); CrmService.Execute(new WhoAmIRequest()); return(true); } catch { return(false); } }
private string GetLogicalCollectionName(string entity) { if (entity.StartsWith("_")) { entity = entity.Substring("@".Length); } var request = new RetrieveEntityRequest { EntityFilters = EntityFilters.Attributes, LogicalName = entity }; var response = (RetrieveEntityResponse)CrmService.Execute(request); IsCustomEntity = response.EntityMetadata.IsCustomEntity ?? false; return(response.EntityMetadata.LogicalCollectionName); }
/// <summary> /// Method to Get a Record and return /// it in the form of a Dynamic Entity Object /// to the calling function /// </summary> /// <param name="poGuid"></param> /// <param name="psEntityName"></param> /// <param name="psAttributeName"></param> /// <param name="poService"></param> /// <param name="paColumnSet"></param> /// <returns></returns> public static DynamicEntity GetDynamicEntityBasedOnGuid(Guid poGuid, string psEntityName, string psAttributeName, CrmService poService, ArrayList paColumnSet) { CrmService loService = poService; QueryExpression loQuery = new QueryExpression(); DynamicEntity loDynamicEntity = null; ColumnSet loColSet = new ColumnSet(); foreach (string lsColumnItem in paColumnSet) { loColSet.AddColumn(lsColumnItem); } try { ConditionExpression loCondition = new ConditionExpression(psAttributeName, ConditionOperator.Equal, poGuid); FilterExpression loFilter = new FilterExpression(); loQuery.EntityName = psEntityName; loQuery.ColumnSet = loColSet; loFilter.Conditions.Add(loCondition); loQuery.Criteria = loFilter; RetrieveMultipleRequest loRetrieve = new RetrieveMultipleRequest(); loRetrieve.Query = loQuery; loRetrieve.ReturnDynamicEntities = true; RetrieveMultipleResponse loResponse = (RetrieveMultipleResponse)loService.Execute(loRetrieve); if (loResponse.BusinessEntityCollection.BusinessEntities.Count > 0) { loDynamicEntity = (DynamicEntity)loResponse.BusinessEntityCollection.BusinessEntities[0]; } } catch (System.Web.Services.Protocols.SoapException ex) { MessageBox.Show("Error: " + ex.Detail.InnerXml.ToString()); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message.ToString()); } return(loDynamicEntity); }
private string GetLogicalCollectionName(CrmAttribute crmAttribute) { var value = string.Empty; var entities = crmAttribute.EntityReferenceLogicalName.Split(";".ToCharArray()); foreach (var entity in entities) { var request = new RetrieveEntityRequest { EntityFilters = EntityFilters.Attributes, LogicalName = entity }; var response = (RetrieveEntityResponse)CrmService.Execute(request); value += response.EntityMetadata.LogicalCollectionName + ";"; } return(value.TrimEnd(";".ToCharArray())); }
// /// <summary> /// Make a record inactive /// </summary> /// <param name="dynamicEntityObject">Entity</param> /// <param name="service">CrmService Proxy</param> public static void SetInactive(this DynamicEntity dynamicEntityObject, CrmService crmServiceProxy) { try { SetStateDynamicEntityRequest setInactiveRequest = new SetStateDynamicEntityRequest(); Key recordGuid = (Key)dynamicEntityObject[dynamicEntityObject.Name + "id"]; Moniker entityMoniker = new Moniker(dynamicEntityObject.Name, recordGuid.Value); //HACK: Might not work always since the status are different for quite a few entities setInactiveRequest.Entity = entityMoniker; setInactiveRequest.Status = -1; setInactiveRequest.State = "Inactive"; SetStateDynamicEntityResponse setInactiveResponse = (SetStateDynamicEntityResponse)crmServiceProxy.Execute(setInactiveRequest); } catch (System.Web.Services.Protocols.SoapException) { throw; } }
public BusinessEntityCollection searchContact(string new_config_allid) { try { CrmConnection crmc = new CrmConnection("Crm"); CrmService crmService = crmc.CreateCrmService(); QueryExpression qe = new QueryExpression("new_config_all") { ColumnSet = new ColumnSet(new String[] { "new_config_allid", "new_name", "new_count", "new_current_amount", "new_period", "new_period" }), Criteria = new FilterExpression() { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression("new_config_allid", ConditionOperator.Equal, new_config_allid), } } }; RetrieveMultipleResponse retrived = new RetrieveMultipleResponse(); RetrieveMultipleRequest retrive = new RetrieveMultipleRequest(); retrive.Query = qe; retrive.ReturnDynamicEntities = true; BusinessEntityCollection results = ((RetrieveMultipleResponse)crmService.Execute(retrive)).BusinessEntityCollection; return(results); } catch (SoapException ex) { logger.Error($"Не удалось осуществить поиск конфига с id {new_config_allid}. Ошибка: {ex.Message}"); throw new System.ArgumentException($"Не удалось осуществить поиск конфига с id {new_config_allid}. Ошибка: {ex.Message}", "original"); } }
public BusinessEntityCollection searchContact(string contactid) { try { CrmConnection crmc = new CrmConnection("Crm"); CrmService crmService = crmc.CreateCrmService(); QueryExpression qe = new QueryExpression("contact") { ColumnSet = new ColumnSet(new String[] { "contactid", "salutation", "lastname", "firstname", "middlename", "mobilephone", "emailaddress1", "address1_name", "address1_line1", "address1_city", "address1_stateorprovince", "address1_country", "new_seria", "new_nomer", "new_giveoutby", "gendercode", "new_nationality", "new_type", "familystatuscode", "birthdate", "new_openles", "new_dategiveout", "ownerid" //" address1_postalcode" // }), Criteria = new FilterExpression() { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression("contactid", ConditionOperator.Equal, contactid), } } }; RetrieveMultipleResponse retrived = new RetrieveMultipleResponse(); RetrieveMultipleRequest retrive = new RetrieveMultipleRequest(); retrive.Query = qe; retrive.ReturnDynamicEntities = true; BusinessEntityCollection results = ((RetrieveMultipleResponse)crmService.Execute(retrive)).BusinessEntityCollection; return(results); } catch (SoapException ex) { logger.Error($"Не удалось осуществить поиск контакта с id {contactid}. Ошибка: {ex.Message}"); throw new System.ArgumentException($"Не удалось осуществить поиск контакта с id {contactid}. Ошибка: {ex.Message}", "original"); } }
public BusinessEntityCollection searchnew_reestr(string txn_id) { CrmConnection crmc = new CrmConnection("Crm"); CrmService crmService = crmc.CreateCrmService(); QueryExpression qe = new QueryExpression("new_reestr") { ColumnSet = new ColumnSet(new String[] { "new_txn_id", "new_reestrid", "new_name" }), Criteria = new FilterExpression() { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression("new_txn_id", ConditionOperator.Equal, txn_id), new ConditionExpression("statecode", ConditionOperator.Equal, 0), } } }; try { RetrieveMultipleResponse retrived = new RetrieveMultipleResponse(); RetrieveMultipleRequest retrive = new RetrieveMultipleRequest(); retrive.Query = qe; retrive.ReturnDynamicEntities = true; BusinessEntityCollection results = ((RetrieveMultipleResponse)crmService.Execute(retrive)).BusinessEntityCollection; return(results); } catch (SoapException ex) { logger.Error($"Не удалось осуществить поиск Реестра оплат txn_id = {txn_id}. Ошибка: {ex.Message}"); throw; } }
/// <summary> /// Creates CRM service. /// </summary> /// <param name="settings">The configuration settings</param> /// <returns>The CRM service.</returns> public ICrmServiceV3 CreateService(ConfigurationSettings settings) { Assert.ArgumentNotNull(settings, "settings"); const string CreateServiceKey = "createService"; ConditionalLog.Info("CreateService(settings). Started.", this, TimerAction.Start, CreateServiceKey); CrmService crmService = null; try { crmService = new CrmService(); crmService.Url = settings.Url; crmService.Timeout = 360 * 1000; crmService.Credentials = CrmHelper.CreateNetworkCredential(settings.User, settings.Password); crmService.UnsafeAuthenticatedConnectionSharing = settings.UnsafeAuthenticatedConnectionSharing; crmService.PreAuthenticate = settings.PreAuthenticate; crmService.ConnectionGroupName = CrmHelper.GetConnectionGroupName((NetworkCredential)crmService.Credentials); crmService.Execute(new WhoAmIRequest()); ConditionalLog.Info("CreateService(settings). CRM service has been created.", this, TimerAction.Tick, CreateServiceKey); } catch (Exception e) { ConditionalLog.Error("Couldn't create CRM service.", e, this); return(null); } finally { ConditionalLog.Info("CreateService(settings). Finished.", this, TimerAction.Stop, CreateServiceKey); } return(crmService); }
public static IEnumerable <DynamicEntity> GetByIdOrPrimaryAttribute(CrmService _crmService, MetadataService metadataService, string entityName, Guid id, string primaryAttributeValue, params string[] fields) { List <DynamicEntity> resultList = new List <DynamicEntity>(); DynamicEntity ret = GetById(_crmService, entityName, id); if (ret == null) { string primaryAttribute = MetadataUtility.RetrievePrimaryAttribute(metadataService, entityName); QueryExpression query = new QueryExpression(entityName) { ColumnSet = new ColumnSet(fields) }; ConditionExpression primaryAttributeExpression = new ConditionExpression(primaryAttribute.ToLower(), ConditionOperator.Equal, primaryAttributeValue); query.Criteria.Conditions.Add(primaryAttributeExpression); RetrieveMultipleRequest request = new RetrieveMultipleRequest() { Query = query, ReturnDynamicEntities = true }; RetrieveMultipleResponse response = (RetrieveMultipleResponse)_crmService.Execute(request); if (response.BusinessEntityCollection.BusinessEntities.Count > 0) { resultList.AddRange(response.BusinessEntityCollection.BusinessEntities.ConvertAll <DynamicEntity>(x => (DynamicEntity)x)); } } else { resultList.Add(ret); } return(resultList); }
public bool Run() { try { // Set up the CRM Service. CrmService service = new CrmService(); service.Credentials = System.Net.CredentialCache.DefaultCredentials; CrmAuthenticationToken token = new CrmAuthenticationToken(); // TODO Replace 'AdventureWorksCycle' with your Microsoft CRM organization name. token.OrganizationName = "AdventureWorksCycle"; service.CrmAuthenticationTokenValue = token; // TODO Replace 'localhost:5555' with your CRM server information. service.Url = @"http://*****:*****@" <importexportxml> <entities> <entity>new_bankaccount</entity> <entity>new_safedepositbox</entity> </entities> <nodes/> <securityroles/> <settings/> <workflows/> </importexportxml>" ; // Execute the import. ImportXmlResponse importResponse = (ImportXmlResponse)service.Execute(importRequest); #endregion #region Publish new entities // Create the request. PublishXmlRequest publishRequest = new PublishXmlRequest(); // Supply the request that is being published with the Bank Account and Safe Deposit Box. publishRequest.ParameterXml = @"<importexportxml> <entities> <entity>new_bankaccount</entity> <entity>new_safedepositbox</entity> </entities> <nodes/> <securityroles/> <settings/> <workflows/> </importexportxml>" ; // Execute the request. PublishXmlResponse publishResponse = (PublishXmlResponse)service.Execute(publishRequest); #endregion } catch (System.Web.Services.Protocols.SoapException) { // Add your error handling code here. } return(true); }
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); } }
private string GetBodyOfQuickView(string formXml, string id) { var code = string.Empty; var xdoc = XDocument.Parse(formXml); var node = from x in xdoc .Descendants("tabs") .Descendants("tab") .Descendants("columns") .Descendants("column") .Descendants("sections") .Descendants("section") .Descendants("rows") .Descendants("row") .Descendants("cell") .Elements("control") where x?.Attribute("id")?.Value == id && x?.Attribute("classid")?.Value == $"{{{ControlClassId.QUICK_VIEW_FORM}}}" select x; var node2 = (from x in node .Descendants("parameters") .Descendants("QuickForms") select x.Value ).FirstOrDefault(); if (node2 == null) { return(string.Empty); } var xdoc2 = XDocument.Parse(node2); var formId = (from x in xdoc2.Descendants("QuickFormId") select x.Value).FirstOrDefault(); if (formId == null) { return(string.Empty); } var quickViewFormXml = string.Empty; var quickViewEntityLogicalName = string.Empty; GetFormXml(formId, out quickViewFormXml, out quickViewEntityLogicalName); if (quickViewFormXml == string.Empty) { return(string.Empty); } var xdoc3 = XDocument.Parse(quickViewFormXml); var fields = (from x in xdoc3 .Descendants("tabs") .Descendants("tab") .Descendants("columns") .Descendants("column") .Descendants("sections") .Descendants("section") .Descendants("rows") .Descendants("row") .Descendants("cell") .Descendants("control") select new IdName { Name = x?.Attribute("datafieldname")?.Value, Id = x?.Attribute("id").Value, ClassId = Utility.TrimGuid(x?.Attribute("classid")?.Value?.ToUpper()), ControlId = x?.Attribute("uniqueid")?.Value }).Distinct().ToList(); fields = fields.OrderBy(x => x.Name).ToList(); foreach (var field in fields) { if (field.ClassId == ControlClassId.SUB_GRID || field.ClassId == ControlClassId.SUB_GRID_PANEL || field.ClassId == ControlClassId.TIMER) { continue; } var request = new RetrieveAttributeRequest { EntityLogicalName = quickViewEntityLogicalName, LogicalName = field.Id, RetrieveAsIfPublished = false }; var response = (RetrieveAttributeResponse)CrmService.Execute(request); code += $"\t\t\t\t{response.AttributeMetadata.SchemaName}: {{}},\r\n"; } code = code.TrimEnd(",\r\n".ToCharArray()) + "\r\n"; return(code); }
public bool Run() { try { string configFileName = "demo.ini"; IniConfigSource configSource = new IniConfigSource(configFileName); IConfig demoConfigSection = configSource.Configs["Demo"]; string extractPath = demoConfigSection.Get("extractPath", string.Empty); // Set up the CRM Service. CrmService service = new CrmService(); service.Credentials = System.Net.CredentialCache.DefaultCredentials; CrmAuthenticationToken token = new CrmAuthenticationToken(); // TODO Replace 'AdventureWorksCycle' with your Microsoft CRM organization name. token.OrganizationName = "IBMRational"; service.CrmAuthenticationTokenValue = token; // TODO Replace 'localhost:5555' with your CRM server information. service.Url = @"http://*****:*****@"C:\Users\rsdiasoliveira\Downloads\sdk4\sdk\server\fullsample\importexportpublish\cs\bin\Debug\"; //const string customizationPath = @"C:\AppProject\Smart\ExternalSmartStaff\site\document"; Console.WriteLine(customizationPath); foreach (var file in Directory.GetFiles(customizationPath)) { File.Copy(file, Path.Combine(sourceDir, Path.GetFileName(file)), true); } // Pass the stream of customization XML to the import request. using (StreamReader sr = new StreamReader(Path.Combine(customizationPath + "customizations.xml"))) { string customizationXml = sr.ReadToEnd(); importRequest.CustomizationXml = customizationXml; } // Supply the request that is being imported with the Bank Accounts and Safe Deposit Boxes. // Supply the request that is being imported with the Bank Accounts and Safe Deposit Boxes. importRequest.ParameterXml = @" <importexportxml> <entities> <entity>contact</entity> <entity>incident</entity> <entity>credifin_campanhapromo</entity> </entities> <nodes/> <securityroles/> <settings/> <workflows/> </importexportxml>" ; // Execute the import. ImportXmlResponse importResponse = (ImportXmlResponse)service.Execute(importRequest); #endregion #region Publish new entities // Create the request. PublishXmlRequest publishRequest = new PublishXmlRequest(); // Supply the request that is being published with the Bank Account and Safe Deposit Box. publishRequest.ParameterXml = @"<importexportxml> <entities> <entity>contact</entity> <entity>incident</entity> <entity>credifin_campanhapromo</entity> </entities> <nodes/> <securityroles/> <settings/> <workflows/> </importexportxml>" ; // Execute the request. PublishXmlResponse publishResponse = (PublishXmlResponse)service.Execute(publishRequest); #endregion } catch (System.Web.Services.Protocols.SoapException) { // Add your error handling code here. } return(true); }
public async Task <UserInfo> GetLoginInfo(string username) { UserInfo result = new UserInfo(); var dyCRMSetting = coreConfiguration.DyCRMSetting; try { var xdoc = await Task <XDocument> .Run(() => { var fetchXml = string.Empty; fetchXml = GetUserFetchXml(username, dyCRMSetting.Domain); return(XDocument.Parse(fetchXml)); }); var fetchRequest = new CrmRetrieveMultipleFetchRequestMessage() { EntityName = "systemuser", FetchXml = xdoc }; var dicHead = new Dictionary <string, IEnumerable <string> >(); dicHead.Add("Prefer", new List <string>() { "odata.include-annotations=\"*\"" }); fetchRequest.Headers.Add("Prefer", dicHead["Prefer"]); var fetchResponse = await _crmService.Execute(fetchRequest); if (fetchResponse != null) { var list = fetchResponse as CrmRetrieveMultipleFetchResponseMessage; if (list != null && list.Value.Results != null) { var entity = list.Value.Results[0]; if (entity != null) { if (entity.Attributes["systemuserid"] != null) { result.systemuserid = Guid.Parse(entity.Attributes["systemuserid"].ToString()); } if (entity.Attributes["domainname"] != null) { result.domainname = entity.Attributes["domainname"].ToString(); } if (entity.Attributes["lastname"] != null) { result.lastname = entity.Attributes["lastname"].ToString(); } if (entity.Attributes["firstname"] != null) { result.firstname = entity.Attributes["firstname"].ToString(); } if (entity.Attributes["mcs_staffid"] != null) { result.mcs_staffid = entity.Attributes["mcs_staffid"].ToString(); } if (entity.Attributes["_mcs_dealer_value"] != null) { result.mcs_dealerid = entity.Attributes["_mcs_dealer_value"].ToString(); } if (dyCRMSetting.CrmApiVersion == "9.0") { if (entity.Attributes["dealer.mcs_name"] != null) { result.mcs_dealername = entity.Attributes["dealer.mcs_name"].ToString(); } if (entity.Attributes["dealer.mcs_code"] != null) { result.mcs_dealercode = entity.Attributes["dealer.mcs_code"].ToString(); } } else { if (entity.Attributes["dealer_x002e_mcs_name"] != null) { result.mcs_dealername = entity.Attributes["dealer_x002e_mcs_name"].ToString(); } if (entity.Attributes["dealer_x002e_mcs_code"] != null) { result.mcs_dealercode = entity.Attributes["dealer_x002e_mcs_code"].ToString(); } } } } } return(result); } catch (Exception ex) { return(result); } }