internal static void GetUsage() { foreach (var en in App.AllEntities) { foreach (var attr in en.OptionAttributes) { if (attr.LeftOnlyOptions.Count > 0) { foreach (var o in attr.LOptions) { o.Usage = CrmHelper.IsOptionValueUsed(en.LogicalName, attr.Name, o.Value); } } } } foreach (var en in App.MigEntities) { foreach (var attr in en.OptionAttributes) { if (attr.LeftOnlyOptions.Count > 0) { foreach (var o in attr.LOptions) { foreach (var ue in App.MigEntities.Where(ce => ce.OptionAttributes.Where(at => at.Name == attr.Name && at.LOptions.Where(op => op.Name == o.Name && op.Usage).Any()).Any())) { o.AllUsageEntities += $"- {ue.LogicalName}"; } o.AllUsage = !string.IsNullOrEmpty(o.AllUsageEntities); } } } } }
public ActionResult IncomingCall(string callId, string callDate, string caller, string userShortNumber) { DateTime date = DateTime.Parse(callDate); CrmHelper crm = new CrmHelper(); CallerHepler callerHelper = crm.CreatePhoneCall(callId, date, caller, userShortNumber); if (callerHelper.Code == 200) { CrmHub signalRUser = new CrmHub(); ResponseHelper response = signalRUser.ExecuteSignalRIncomingCall(callerHelper); if (response.IsError) { if (response.Code == 500) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } else if (response.Code == 404) { return(new HttpNotFoundResult("Not Found")); } } } else { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } return(new HttpStatusCodeResult(HttpStatusCode.OK)); }
/// <summary> /// Fetches the entity loist from CRM and display it under selct entity combobox control /// </summary> private void CrmEntitiesFetch() { WorkAsync(new WorkAsyncInfo { // Showing message until background work is completed Message = "Retrieving Entities Information", // Main task which will be executed asynchronously Work = (worker, args) => { CrmHelper crmHelper = new CrmHelper(Service); args.Result = crmHelper.GetEntitylist(); }, // Work is completed, results can be shown to user PostWorkCallBack = (args) => { if (args.Error != null) { MessageBox.Show(args.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Binding result data to ListBox Control var result = args.Result as List <EntityMetadata>; selectEntitiesComboBox.Items.Clear(); selectAttributeComboBox.Items.Clear(); foreach (var entityMetadata in result) { selectEntitiesComboBox.Items.Add(entityMetadata); } } }); }
public void DeployFormula(Guid id, bool exists) { try { var lformula = CrmConnManager.LService.Retrieve("north52_formula", id, new ColumnSet(true)); var e = new Entity("north52_formula"); e.Id = lformula.Id; foreach (var a in lformula.Attributes) { if (a.Key.StartsWith("north52_")) { e[a.Key] = lformula[a.Key]; } } if (!exists) { CrmConnManager.RService.Create(e); } else { CrmConnManager.RService.Update(e); } int stateCode = (lformula["statecode"] as OptionSetValue).Value; int statusCode = (lformula["statuscode"] as OptionSetValue).Value; CrmHelper.SetStatus(CrmConnManager.RService, lformula.LogicalName, lformula.Id, stateCode, statusCode); } catch (Exception ex) { MessageBox.Show($"FormulaManager:DeployFormula:Exception: {ex.Message}"); } }
public static EntityCollection GetStringMapData(IOrganizationService service) { EntityCollection ec = new EntityCollection(); EntityCollection rs; int pageNum = 1; string pagingCookie = ""; do { if (pagingCookie != null && pagingCookie != "") { pagingCookie = pagingCookie.Replace("\"", "'").Replace(">", ">").Replace("<", "<"); } var fetchXml = CrmHelper.GetOptionFetch(pageNum, pagingCookie); rs = service.RetrieveMultiple(new FetchExpression(fetchXml)); ec.Entities.AddRange(rs.Entities); pagingCookie = rs.PagingCookie; pageNum++; }while (rs.MoreRecords && pageNum < 20); MessageBox.Show($"Last Page: {pageNum} Total number of records: {ec.Entities.Count}"); return(ec); }
public string Summary(string callId) { CrmHelper crm = new CrmHelper(); string result = crm.GetSummaryFields(callId); return(result); }
/// <summary> /// Запуск ответа на звонок из браузера /// </summary> /// <param name="callId">ID звонка</param> /// <returns>status code</returns> public ResponseHelper Answer(string callId) { ResponseHelper response = new ResponseHelper(); try { Guid connectionId = new Guid(Context.ConnectionId); SignalRUser user = connectionsList.Find(x => x.ConnectionId.Contains(connectionId)); CrmHelper crm = new CrmHelper(); response = crm.SetAttrsAnswer(callId); if (!response.IsError) { response = crm.CreateIncident(callId); Guid[] connectionsIds = user.ConnectionId.ToArray(); string[] connectionsIdsToString = Array.ConvertAll(connectionsIds, x => x.ToString()); var context = GlobalHost.ConnectionManager.GetHubContext <CrmHub>(); context.Clients.Clients(connectionsIdsToString).SuccessAnswer(response.TransferParam); } } catch (Exception e) { response.IsError = true; response.ErrorMessage = e.Message; response.Code = 500; return(response); } return(response); }
protected override void Execute(CodeActivityContext executionContext) { //Create the tracing service ITracingService tracingService = executionContext.GetExtension <ITracingService>(); //Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService crmService = serviceFactory.CreateOrganizationService(context.UserId); int customOfferApprovalValidityInDays = CrmHelper.GetCustomOfferApprovalValidity(crmService); DateTime customOfferApprovedDate = CustomOfferApprovedDate.Get <DateTime>(executionContext); bool isCustomOfferApprovalValid = DateTime.Today.Subtract(customOfferApprovedDate.Date).TotalDays <= customOfferApprovalValidityInDays; CustomOfferApprovalValid.Set(executionContext, isCustomOfferApprovalValid); //if(!isCustomOfferApprovalValid) //{ /// Guid opportunityRecordId = OpportunityRecord.Get<EntityReference>(executionContext).Id; // Entity opportunity = new Entity("opportunity", opportunityRecordId); // opportunity["fdx_approvalstatus"] = null; // opportunity["fdx_triggercustomofferapprovalemailnotificati"] = false; // crmService.Update(opportunity); //} tracingService.Trace("Custom Offer Approval Validity In Days " + customOfferApprovalValidityInDays); tracingService.Trace("Custom Offer Approved Date " + customOfferApprovedDate.Date.ToString()); tracingService.Trace("Today " + DateTime.Today.ToString()); tracingService.Trace("Is Custom Offer Approval Valid?" + isCustomOfferApprovalValid.ToString()); }
/// <summary> /// Method to populate the fist column attribute combobox with list of string attributes /// </summary> /// <param name="entityLogicalName"></param> private void PopulateFirstAttributeList(string entityLogicalName) { WorkAsync(new WorkAsyncInfo { // Showing message until background work is completed Message = "Retrieving Attributes Information", // Main task which will be executed asynchronously Work = (worker, args) => { var crmHelper = new CrmHelper(Service); var pluginControlHelper = new PluginControlHelper(); var attributeList = crmHelper.GetAttributeListFromEntity(entityLogicalName); args.Result = pluginControlHelper.GetStringAttributes(attributeList); }, // Work is completed, results can be shown to user PostWorkCallBack = (args) => { if (args.Error != null) { MessageBox.Show(args.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Binding result data to ListBox Control var result = args.Result as List <AttributeMetadata>; selectUniqueAttributeComboBox.Items.Clear(); foreach (var attributeMetadata in result) { selectUniqueAttributeComboBox.Items.Add(attributeMetadata); } } }); }
private void PassEnquiryToCrm() { Store store = AbleContext.Current.Store; StoreSettingsManager settings = store.Settings; Order order = new Order(); order.BillToEmail = StringHelper.StripHtml(Email.Text); order.BillToFirstName = StringHelper.StripHtml(FirstName.Text); order.BillToLastName = StringHelper.StripHtml(LastName.Text); order.BillToPhone = StringHelper.StripHtml(Phone.Text); order.BillToCompany = StringHelper.StripHtml(Company.Text); order.OrderDate = DateTime.Now; // The list of files that have been uploaded are included in the HiddenFilesField. var files = (List <FileAttachment>)Session["UPLOADED"]; if (files == null) { files = new List <FileAttachment>(); } CrmHelper.SaveEnquiry(order, StringHelper.StripHtml(Comments.Text), files, store); FailureMessage.Visible = false; SuccessMessage.Visible = true; MessagePanel.Visible = true; ContactFormPanel.Visible = false; }
private void BtnDeactivateFormulas_Click(object sender, EventArgs e) { var fetchXml = string.Empty; if (string.IsNullOrEmpty(txtInput.Text)) { fetchXml = CrmHelper.GetFormulaFetchForMigrationEntities(); } else { fetchXml = txtInput.Text; } var result = CrmConnManager.LService.RetrieveMultiple(new FetchExpression(fetchXml)).Entities; txtLog.AppendText($"Number of active formulas: {result.Count}"); int count = 0;; foreach (var en in result) { if (count++ % 50 == 0) { txtLog.AppendText($"Deactivated formulas count: {count}"); } var id = en.Id; var entityName = en.GetAttributeValue <string>("north52_sourceentityname"); var name = en.GetAttributeValue <string>("north52_name"); var formula = new CrmFormula() { Id = id, Name = name, Type = new MigrationHelper.Option() { Value = en.GetAttributeValue <OptionSetValue>("north52_formulatype").Value, Name = en.FormattedValues["north52_formulatype"] }, StatusCode = new MigrationHelper.Option() { Value = en.GetAttributeValue <OptionSetValue>("statuscode").Value, Name = en.FormattedValues["statuscode"] }, StateCode = new MigrationHelper.Option() { Value = en.GetAttributeValue <OptionSetValue>("statecode").Value, Name = en.FormattedValues["statecode"] }, }; //txtLog.AppendText($"Formula Name: {entityName}:{formula.Name}, Type: {formula.Type.Name} {Environment.NewLine}"); CrmHelper.DeactivateRecord("north52_formula", formula.Id, CrmConnManager.LService); } }
/// <summary> /// Выход из extension /// </summary> /// <param name="inputNumber">Короткий номер пользователя</param> /// <returns>status code</returns> public ResponseHelper SignOut(string inputNumber) { CrmHelper crm = new CrmHelper(); Guid connectionId = new Guid(Context.ConnectionId); ResponseHelper response = crm.LogOff(inputNumber); if (!response.IsError) { SignalRUser user = connectionsList.Find(x => x.ShortNumber.Equals(inputNumber)); connectionsList.Remove(user); } return(response); }
private RetrieveCrmTicketResponse GetAdTicket() { var crmDiscoveryService = new CrmDiscoveryService(); crmDiscoveryService.Url = this.Settings.Url.ToLower().Replace("crmservice.asmx", "AD/crmdiscoveryservice.asmx"); crmDiscoveryService.Credentials = CrmHelper.CreateNetworkCredential(this.Settings.User, this.Settings.Password); var crmTicketRequest = new RetrieveCrmTicketRequest(); crmTicketRequest.OrganizationName = this.Settings.Organization; return((RetrieveCrmTicketResponse)crmDiscoveryService.Execute(crmTicketRequest)); }
private void OnPremiseLogin_Click(object sender, RoutedEventArgs e) { try { if (txtServerOnPremise.Text.Equals(string.Empty) || txtDomainOnPremise.Text.Equals(string.Empty) || txtUserNameOnPremise.Text.Equals(string.Empty) || txtPasswordOnPremise.Password.Equals(string.Empty)) { MessageBox.Show("Unable to login, please provide required details."); } else { string strAuthType = cmbAuthType.SelectedValue.ToString(); string strServerUrl = txtServerOnPremise.Text; AppendOrgnaisationName(ref strServerUrl); string strDomain = txtDomainOnPremise.Text; string strUserName = txtUserNameOnPremise.Text; string strPassword = txtPasswordOnPremise.Password.ToString(); string strConnectionString = $"AuthType={strAuthType};Url={strServerUrl};Domain={strDomain};Username={strUserName};Password={strPassword}"; string strConStringKeyValue = ConfigurationManager.AppSettings["DynamicsConnectionStringOnPremise"]; if (strConStringKeyValue != strConnectionString) { UpdateConnectionStringValue(strConnectionString, ConnectionType.OnPremise); } PBOnpremiseLogin.Visibility = Visibility.Visible; Tuple <string> strErrorMessage = new Tuple <string>(string.Empty); Task <bool> TaskConnection = Task.Run((async() => await CrmHelper.ConnectUsingConnectionStringAsync(strConnectionString, strErrorMessage))); if (TaskConnection.Result) { var parentWindow = Window.GetWindow(this) as MainWindow; parentWindow.dockPanel.Children.Clear(); FaceIdentify cntrlFaceIdentify = new FaceIdentify(); cntrlFaceIdentify.CloseInitiated += new Close(parentWindow.ClosePanel); parentWindow.dockPanel.Children.Add(cntrlFaceIdentify); parentWindow.dockPanel.Visibility = Visibility.Visible; PBOnpremiseLogin.Visibility = Visibility.Hidden; } else { MessageBox.Show("Unable to login :"******"\r\n" + strErrorMessage); PBOnpremiseLogin.Visibility = Visibility.Hidden; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Sets the values of the specified group of property settings. /// </summary> /// <param name="context">A <see cref="T:System.Configuration.SettingsContext"/> describing the current application usage.</param> /// <param name="collection">A <see cref="T:System.Configuration.SettingsPropertyValueCollection"/> representing the group of property settings to set.</param> /// <exception cref="FormatException">The profile property couldn't be parsed.</exception> public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { if (this.initialized) { bool showMessage = false; var userName = (string)context["UserName"]; if (string.IsNullOrEmpty(userName) || userName.Contains("\\")) { return; } SettingsPropertyValueCollection relevantPropertyValues = this.GetRelevantPropertyValues(collection); var newPropertyValues = new Dictionary <string, object>(); foreach (CrmSettingsPropertyValue property in relevantPropertyValues) { string propertyName = this.ProcessProperty(property.Property, p => (p as CrmSettingsProperty).CrmName); object propertyValue = property.PropertyValue; if ((propertyName != "contactid") && (property.PropertyValue != null) && !showMessage) { if (this.ReadOnly) { showMessage = property.IsDirty; } else { if (property.IsDirty && this.initialized) { newPropertyValues.Add(propertyName, propertyValue); } } } collection.Remove(property.Name); } if (!this.ReadOnly && (newPropertyValues.Count != 0)) { if (!this.profileRepository.UpdateUserProperties(userName, newPropertyValues)) { ConditionalLog.Error(String.Format("Couldn't save profile changes for the {0} contact in CRM", userName), this); } } if (this.ReadOnly && showMessage) { CrmHelper.ShowMessage("Couldn't update contact properties as the CRM provider is in read-only mode"); } } }
public string CreateAppeal(AppealEntity appealEntity) { var crmGuid = string.Empty; try { var crmHelper = new CrmHelper(crmUri, crmUser, crmPass); crmGuid = crmHelper.CreateAppeal(appealEntity); } catch (Exception e) { return(JsonConvert.SerializeObject(new { code = "500", message = "error", details = e.Message })); } return(JsonConvert.SerializeObject(new { code = "200", message = "ok", guid = crmGuid })); }
/// <summary> /// Метод авторизации extension SignalR (вызывается из браузера) /// </summary> /// <param name="inputNumber">Короткий номер пользователя</param> /// <returns>status code</returns> public ResponseHelper SignIn(string inputNumber) { CrmHelper crm = new CrmHelper(); Guid connectionId = new Guid(Context.ConnectionId); ResponseHelper response = crm.LogIn(inputNumber); if (!response.IsError) { SignalRUser user = new SignalRUser(); user.ConnectionId = new List <Guid> { connectionId }; user.ShortNumber = inputNumber; connectionsList.Add(user); } return(response); }
public ActionResult Answer(string callId) { CrmHelper crm = new CrmHelper(); ResponseHelper response = crm.SetAttrsAnswer(callId); if (response.IsError) { if (response.Code == 500) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } else if (response.Code == 404) { return(new HttpNotFoundResult("Not Found")); } } return(new HttpStatusCodeResult(HttpStatusCode.OK)); }
public ActionResult LogOff(string inputNumber) { CrmHelper crm = new CrmHelper(); ResponseHelper response = crm.LogOff(inputNumber); if (response.IsError) { if (response.Code == 500) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } else if (response.Code == 404) { return(new HttpNotFoundResult("Not Found")); } } return(new HttpStatusCodeResult(HttpStatusCode.OK)); }
public ActionResult CompleteCall(string callId, string completeDate, string reason) { DateTime date = DateTime.Parse(completeDate); CrmHelper crm = new CrmHelper(); ResponseHelper response = crm.SetAttrsCompleteCall(callId, date, reason); if (response.IsError) { if (response.Code == 500) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError)); } else if (response.Code == 404) { return(new HttpNotFoundResult("Not Found")); } } return(new HttpStatusCodeResult(HttpStatusCode.OK)); }
private bool InitializeHelpers() { if (exchangeHelper == null) { exchangeHelper = new ExchangeHelper(userMail, password); } if (crmHelper == null) { crmHelper = new CrmHelper(crmUser, crmPass, crmUri); } if (exchangeHelper != null && crmHelper != null) { return(true); } else { return(false); } }
//Service connection set up internal void CreateServiceConnection() { string _userName = ConfigurationManager.AppSettings[LeadConstants.UserName]; string _password = ConfigurationManager.AppSettings[LeadConstants.Password]; string _domain = ConfigurationManager.AppSettings[LeadConstants.Domain]; string _url = ConfigurationManager.AppSettings[LeadConstants.CrmSdkUrl]; string _metaDataUrl = ConfigurationManager.AppSettings[LeadConstants.MetaDataURL]; string _org = ConfigurationManager.AppSettings[LeadConstants.Organisation]; try { service = CrmHelper.CreateConnection(_url, _org, _userName, _password, _domain); metaDataService = CrmHelper.CreateMetaDataServiceConnection(_metaDataUrl, _org, _userName, _password, _domain); } catch (Exception) { //throw; } }
private void BtnDeactivateFormulas_Click(object sender, EventArgs e) { var sb = new StringBuilder(); int count = 0; foreach (var f in mgr.FormulaDiffRecords) { if (f.RFormula != null) { var ff = f.RFormula; if (!ff.Type.Name.StartsWith("Client") && ff.StateCode.Value == 0) { CrmHelper.DeactivateRecord("north52_formula", ff.Id, CrmConnManager.RService); } } } MessageBox.Show(sb.ToString()); }
private void BtnActivateFormulas_Click(object sender, EventArgs e) { var fetchXml = string.Empty; if (string.IsNullOrEmpty(txtInput.Text)) { fetchXml = CrmHelper.GetFormulaFetchForMigrationEntities(); } else { fetchXml = txtInput.Text; } var result = CrmConnManager.LService.RetrieveMultiple(new FetchExpression(fetchXml)).Entities; txtLog.AppendText($"Number of active formulas: {result.Count}"); int count = 0; foreach (var en in result) { if (count++ % 50 == 0) { txtLog.AppendText($"Activated formulas count: {count}"); } var id = en.Id; var entityName = en.GetAttributeValue <string>("north52_sourceentityname"); var name = en.GetAttributeValue <string>("north52_name"); try { CrmHelper.ActivateRecord("north52_formula", id, CrmConnManager.RService); } catch (Exception ex) { txtLog.AppendText($"**** Exception while activating formula: {name} {Environment.NewLine}"); txtLog.AppendText($"**** Message: {ex.Message} {Environment.NewLine}"); } } }
/// <summary> /// Creates CRM metadata service. /// </summary> /// <param name="settings">The configuration settings</param> /// <returns>The CRM metadata service.</returns> public IMetadataServiceV4 CreateMetadataService(ConfigurationSettings settings) { Assert.ArgumentNotNull(settings, "settings"); const string CreateMetadataServiceKey = "createMetadataService"; ConditionalLog.Info("CreateMetadataService(settings). Started.", this, TimerAction.Start, CreateMetadataServiceKey); ManagedTokenMetadataService wrapper = null; try { var metadataService = new MetadataService(); metadataService.Url = settings.Url.Replace("crmservice.asmx", "metadataservice.asmx"); metadataService.Timeout = 360 * 1000; metadataService.Credentials = CrmHelper.CreateNetworkCredential(settings.User, settings.Password); metadataService.UnsafeAuthenticatedConnectionSharing = settings.UnsafeAuthenticatedConnectionSharing; metadataService.PreAuthenticate = settings.PreAuthenticate; metadataService.ConnectionGroupName = CrmHelper.GetConnectionGroupName((NetworkCredential)metadataService.Credentials); metadataService.CrmAuthenticationTokenValue = new crm4.metadataservice.CrmAuthenticationToken { AuthenticationType = (int)settings.AuthenticationType, OrganizationName = settings.Organization }; wrapper = new ManagedTokenMetadataService(metadataService, settings); wrapper.Execute(new RetrieveTimestampRequest()); ConditionalLog.Info("CreateMetadataService(settings). CRM metadata service has been created.", this, TimerAction.Tick, CreateMetadataServiceKey); } catch (Exception e) { ConditionalLog.Error("Couldn't create CRM metadata service.", e, this); return(null); } finally { ConditionalLog.Info("CreateMetadataService(settings). Finished.", this, TimerAction.Stop, CreateMetadataServiceKey); } return(wrapper); }
/// <summary> /// Запуск завершения звонка из браузера /// </summary> /// <param name="callId">ID звонка</param> /// <param name="completeDate">Дата завершения звонка</param> /// <param name="reason">Описание(причина) завершения</param> /// <returns>status code</returns> public ResponseHelper CompleteCall(string callId, DateTime completeDate, string reason) { ResponseHelper response = new ResponseHelper(); try { Guid connectionId = new Guid(Context.ConnectionId); SignalRUser user = connectionsList.Find(x => x.ConnectionId.Contains(connectionId)); CrmHelper crm = new CrmHelper(); response = crm.SetAttrsCompleteCall(callId, completeDate, reason); Guid[] connectionsIds = user.ConnectionId.ToArray(); string[] connectionsIdsToString = Array.ConvertAll(connectionsIds, x => x.ToString()); var context = GlobalHost.ConnectionManager.GetHubContext <CrmHub>(); context.Clients.Clients(connectionsIdsToString).BackToPage(); } catch (Exception e) { response.IsError = true; response.ErrorMessage = e.Message; response.Code = 500; return(response); } return(response); }
/// <summary> /// Creates CRM metadata service. /// </summary> /// <param name="settings">The configuration settings</param> /// <returns>The CRM metadata service.</returns> public IMetadataServiceV3 CreateMetadataService(ConfigurationSettings settings) { Assert.ArgumentNotNull(settings, "settings"); const string CreateMetadataServiceKey = "createMetadataService"; ConditionalLog.Info("CreateMetadataService(settings). Started.", this, TimerAction.Start, CreateMetadataServiceKey); MetadataService metadataService = null; try { metadataService = new MetadataService(); metadataService.Url = settings.Url.Replace("crmservice.asmx", "metadataservice.asmx"); metadataService.Timeout = 360 * 1000; metadataService.Credentials = CrmHelper.CreateNetworkCredential(settings.User, settings.Password); metadataService.UnsafeAuthenticatedConnectionSharing = settings.UnsafeAuthenticatedConnectionSharing; metadataService.PreAuthenticate = settings.PreAuthenticate; metadataService.ConnectionGroupName = CrmHelper.GetConnectionGroupName((NetworkCredential)metadataService.Credentials); metadataService.GetTimestamp(); ConditionalLog.Info("CreateMetadataService(settings). CRM metadata service has been created.", this, TimerAction.Tick, CreateMetadataServiceKey); } catch (Exception e) { ConditionalLog.Error("Couldn't create CRM metadata service.", e, this); return(null); } finally { ConditionalLog.Info("CreateMetadataService(settings). Finished.", this, TimerAction.Stop, CreateMetadataServiceKey); } return(metadataService); }
/// <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 IEnumerable <Guid> CommitEnumerable() { var response = new List <Guid>(); var transactionRequest = new ExecuteTransactionRequest { Requests = new OrganizationRequestCollection() }; foreach (var entity in Added.Keys) { Added[entity].PersistAdded(entity); } foreach (var entity in Modified.Keys) { Modified[entity].PersistUpdated(entity); } foreach (var entity in Removed.Keys) { Removed[entity].PersistRemoved(entity); } Added.Clear(); Modified.Clear(); Removed.Clear(); try { for (int i = 0; i < Requests.Count; i += _batchSize) { var requestBatch = Requests.Skip(i).Take(_batchSize); transactionRequest.Requests.AddRange(requestBatch); var multipleResponse = (ExecuteTransactionResponse)_service.Execute(transactionRequest); response.AddRange(CrmHelper.GetGuidsAsEnumerable(multipleResponse)); transactionRequest = new ExecuteTransactionRequest { Requests = new OrganizationRequestCollection() }; } } catch (FaultException <OrganizationServiceFault> fault) { if (fault.Detail.ErrorDetails.Contains("MaxBatchSize")) { int maxBatchSize = Convert.ToInt32(fault.Detail.ErrorDetails["MaxBatchSize"]); if (maxBatchSize < transactionRequest.Requests.Count) { var errMsg = string.Format( "The input request collection contains {0} requests, which exceeds the maximum allowed {1}", transactionRequest.Requests.Count, maxBatchSize); throw new InvalidOperationException(errMsg, fault); } } throw; } return(response); }
internal void ProcessLeadInfo(LeadInfo leadInfo, ref ReturnInfo mRetInfo) { string leadid = string.Empty; string leadStatus = string.Empty; string leadSource = string.Empty; DateTime createdOn = DateTime.Now; DateTime modifiedOn = DateTime.Now; DateTime reactivateOn = DateTime.Now; //Need to get from dynamic entity Dictionary <string, string> attributes = new Dictionary <string, string>(); try { attributes.Add(LeadConstants.AttrEmail, leadInfo.Email); DynamicEntity de = LeadDAL.SelectLead(service, attributes); if (de == null) { attributes.Clear(); attributes.Add(LeadConstants.AttrMobile, leadInfo.MobilePhone); attributes.Add(LeadConstants.AttrFirstName, leadInfo.Firstname); de = LeadDAL.SelectLead(service, attributes); if (de == null) { //Create New Lead and exit //to write //RC 1 mRetInfo.ReturnCode = 1; return; } } //Get the existing lead status foreach (Property p in de.Properties) { if (p.Name == LeadConstants.AttrLeadID) { leadid = CrmHelper.GetSourceValue(p.GetType().Name, p); } if (p.Name == LeadConstants.AttrLeadStatus) { leadStatus = CrmHelper.GetSourceValue(p.GetType().Name, p); } else if (p.Name == LeadConstants.AttrLeadSource) { leadSource = CrmHelper.GetSourceValue(p.GetType().Name, p); } else if (p.Name == LeadConstants.AttrCreatedOn) { createdOn = Convert.ToDateTime(CrmHelper.GetSourceValue(p.GetType().Name, p)); } else if (p.Name == LeadConstants.AttrModifiedOn) { modifiedOn = Convert.ToDateTime(CrmHelper.GetSourceValue(p.GetType().Name, p)); } //else if (p.Name == LeadConstants.AttrReactivateOn) //{ // reactivateOn = Convert.ToDateTime(CrmHelper.GetSourceValue(p.GetType().Name, p)); //} } Guid _leadid = new Guid(leadid); mRetInfo.LeadID = _leadid.ToString(); //UpdateOnly = False if (!leadInfo.UpdateOnly) { if (leadStatus.ToLower() == LeadConstants.StatusOpen) { if (leadSource == LeadConstants.AdminUpload) { //Send Email //need info //RC 3 mRetInfo.ReturnCode = 3; } else { //RC 2 mRetInfo.ReturnCode = 2; } //Create a Note <LeadDetails> LeadDAL.AddNoteToLead(service, _leadid, leadInfo.LeadDetails); } else { //Reactivate Lead and update info. LeadDAL.ReactivateLead(service, metaDataService, leadInfo, _leadid, de); LeadDAL.AddNoteToLead(service, _leadid, leadInfo.LeadDetails); //RC 4 mRetInfo.ReturnCode = 4; } } else { if (leadStatus.ToLower() == LeadConstants.StatusOpen) { if ((createdOn == leadInfo.CreateOn) || (reactivateOn == leadInfo.CreateOn)) { //update refferal name, lead source, enquiry source, campaign source //RC 5 mRetInfo.ReturnCode = 5; } else { //RC 7 mRetInfo.ReturnCode = 7; } //Create a Note <LeadDetails> LeadDAL.AddNoteToLead(service, _leadid, leadInfo.LeadDetails); } else { if (modifiedOn == leadInfo.CreateOn) { //RC 6 mRetInfo.ReturnCode = 6; } else { //RC 8 mRetInfo.ReturnCode = 8; } } } } catch (Exception ex) { mRetInfo.ErrorMessage = ex.Message; } }