void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { MessageBox.Show(this, CrmExceptionHelper.GetErrorMessage(e.Error, false), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Close(); } else { foreach (Entity dashboard in ((EntityCollection)e.Result).Entities) { var item = new ListViewItem(dashboard.Contains("name") ? dashboard["name"].ToString() : "N/A") { Tag = dashboard }; lstDashboards.Items.Add(item); } lstDashboards.Sort(); lstDashboards.Enabled = true; btnCancel.Enabled = true; btnOK.Enabled = true; btnRefresh.Enabled = true; } }
internal static IEnumerable <Entity> RetrieveUserViews(string entityLogicalName, List <EntityMetadata> entitiesCache, IOrganizationService service) { try { EntityMetadata currentEmd = entitiesCache.Find(e => e.LogicalName == entityLogicalName); QueryByAttribute qba = new QueryByAttribute { EntityName = "userquery", ColumnSet = new ColumnSet(true) }; qba.Attributes.AddRange("returnedtypecode", "querytype"); // ReSharper disable once PossibleInvalidOperationException qba.Values.AddRange(currentEmd.ObjectTypeCode.Value, 0); EntityCollection views = service.RetrieveMultiple(qba); List <Entity> viewsList = new List <Entity>(); foreach (Entity entity in views.Entities) { viewsList.Add(entity); } return(viewsList); } catch (Exception error) { string errorMessage = CrmExceptionHelper.GetErrorMessage(error, false); throw new Exception("Error while retrieving user views: " + errorMessage); } }
private void bwUpdateAttributes_DoWork(object sender, DoWorkEventArgs e) { var bw = (BackgroundWorker)sender; var arg = (Tuple <List <ListViewItem>, UpdateSettings>)e.Argument; var itemsToManage = arg.Item1; var us = arg.Item2; int attributesProcessed = 0; // We process the items foreach (ListViewItem item in itemsToManage) { var amd = (AttributeMetadata)item.Tag; try { attributesProcessed++; if (amd.IsCustomizable.Value || amd.IsManaged.HasValue && amd.IsManaged.Value == false) { if (us.UpdateValidForAdvancedFind) { amd.IsValidForAdvancedFind.Value = item.Checked; } if (us.UpdateAuditIsEnabled) { amd.IsAuditEnabled.Value = item.Checked; } if (us.UpdateRequirementLevel && us.RequirementLevelValue.HasValue) { amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(us.RequirementLevelValue.Value); } if (us.UpdateIsSecured) { amd.IsSecured = item.Checked; } innerService.Execute(new UpdateAttributeRequest { Attribute = amd, EntityName = amd.EntityLogicalName }); AddItemToInformationList(bw, Convert.ToInt32(attributesProcessed * 100 / itemsToManage.Count), amd.DisplayName.UserLocalizedLabel.Label, null, Result.Success); } else { AddItemToInformationList(bw, Convert.ToInt32(attributesProcessed * 100 / itemsToManage.Count), amd.DisplayName.UserLocalizedLabel.Label, "Attribute not customizable!", Result.Warning); } } catch (Exception error) { string errorMessage = CrmExceptionHelper.GetErrorMessage(error, false); AddItemToInformationList(bw, Convert.ToInt32(attributesProcessed * 100 / itemsToManage.Count), amd.DisplayName.UserLocalizedLabel.Label, errorMessage, Result.Error); } } }
private async Task GetSelectedSolutionAsync() { comboBoxSolutions.Items.Clear(); solutions = new List <SolutionDetail>(); try { var entity = await RetrieveSolutionAsync(detail); var solDetail = new SolutionDetail() { SolutionId = entity.Id, UniqueName = entity.GetAttributeValue <string>("uniquename"), FriendlyName = entity.GetAttributeValue <string>("friendlyname"), PublisherPrefix = entity.GetAttributeValue <AliasedValue>("publisher.customizationprefix") == null ? null : entity.GetAttributeValue <AliasedValue>("publisher.customizationprefix").Value.ToString() }; if (solutions == null) { solutions = new List <SolutionDetail>(); } solutions.Add(solDetail); comboBoxSolutions.Items.Add(new Solution { SolutionDetail = solDetail }); comboBoxSolutions.SelectedIndex = 0; } catch (Exception ex) { var errorMessage = CrmExceptionHelper.GetErrorMessage(ex, false); MessageBox.Show(this, "An error occured while retrieving solutions: " + errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Retrieve the list of views for a specific entity /// </summary> /// <param name="entityDisplayName">Logical name of the entity</param> /// <param name="entitiesCache">Entities cache</param> /// <param name="service">Organization Service</param> /// <returns>List of views</returns> public static List <Entity> RetrieveViews(string entityLogicalName, List <EntityMetadata> entitiesCache, IOrganizationService service) { try { EntityMetadata currentEmd = entitiesCache.Find(delegate(EntityMetadata emd) { return(emd.LogicalName == entityLogicalName); }); QueryByAttribute qba = new QueryByAttribute { EntityName = "savedquery", ColumnSet = new ColumnSet(true) }; qba.Attributes.Add("returnedtypecode"); qba.Values.Add(currentEmd.ObjectTypeCode.Value); EntityCollection views = service.RetrieveMultiple(qba); List <Entity> viewsList = new List <Entity>(); foreach (Entity entity in views.Entities) { viewsList.Add(entity); } return(viewsList); } catch (Exception error) { string errorMessage = CrmExceptionHelper.GetErrorMessage(error, false); throw new Exception("Error while retrieving views: " + errorMessage); } }
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { MessageBox.Show(this, CrmExceptionHelper.GetErrorMessage(e.Error, false), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Close(); } }
private void UpdateWorkflows() { List <WorkflowList> items = new List <WorkflowList>(); WorkAsync(new WorkAsyncInfo { Message = "Updating Workflows...", Work = (bw, evt) => { int totalItems = checkedListBox1.Items.Count; for (int i = 0; i < totalItems; i++) { if (errorMsg.Length > 0) { errorMsg = ""; break; } WorkflowList item = (WorkflowList)checkedListBox1.Items[i]; //Guid wfGuid = new Guid(item.RealValue); bool origStatus = item.State; bool currentStatus = checkedListBox1.GetItemCheckState(i).ToString() == "Checked" ? true : false; string currentStatusValue = currentStatus ? "Activated" : "Draft"; if (origStatus != currentStatus) { item.State = currentStatus; items.Add(item); SetStateWorkflow(item, currentStatusValue, Service); } } }, PostWorkCallBack = evt => { if (evt.Error != null) { string errorMessage = CrmExceptionHelper.GetErrorMessage(evt.Error, true); MessageBox.Show(this, errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } foreach (WorkflowList item in items) { checkedListBox1.Items[checkedListBox1.Items.IndexOf(item)] = item; } }, AsyncArgument = null, IsCancelable = true, MessageWidth = 340, MessageHeight = 150 }); }
private void LoadEntities() { fetchXml = string.Empty; lvEntities.Items.Clear(); gbEntities.Enabled = false; tsbLoadEntities.Enabled = false; tsbRefresh.Enabled = false; tsbExportExcel.Enabled = false; tsbEditInFxb.Enabled = false; lvViews.Items.Clear(); txtFetchXml.Text = ""; WorkAsync(new WorkAsyncInfo("Loading entities...", e => { e.Result = MetadataHelper.RetrieveEntities(Service); }) { PostWorkCallBack = completedargs => { if (completedargs.Error != null) { string errorMessage = CrmExceptionHelper.GetErrorMessage(completedargs.Error, true); CommonDelegates.DisplayMessageBox(ParentForm, errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { entitiesCache = (List <EntityMetadata>)completedargs.Result; lvEntities.Items.Clear(); var list = new List <ListViewItem>(); foreach (EntityMetadata emd in (List <EntityMetadata>)completedargs.Result) { var item = new ListViewItem { Text = emd.DisplayName.UserLocalizedLabel.Label, Tag = emd.LogicalName }; item.SubItems.Add(emd.LogicalName); list.Add(item); } lvEntities.Items.AddRange(list.ToArray()); lvEntities.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); gbEntities.Enabled = true; gbEntities.Enabled = true; tsbLoadEntities.Enabled = true; tsbRefresh.Enabled = true; } } }); }
private async void BGetOrganizationsClick(object sender, EventArgs e) { if (FillConnectionDetails()) { // Launch organization retrieval comboBoxOrganizations.Items.Clear(); organizations = new List <OrganizationDetail>(); Cursor = Cursors.WaitCursor; bGetOrganizations.Enabled = false; var orgs = await RetrieveOrganizationsAsync(detail); try { foreach (OrganizationDetail orgDetail in orgs) { organizations.Add(orgDetail); comboBoxOrganizations.Items.Add(new Organization { OrganizationDetail = orgDetail }); comboBoxOrganizations.SelectedIndex = 0; } if (comboBoxOrganizations.Items.Count > 0) { comboBoxOrganizations.Enabled = true; bGetSolutions.Enabled = true; } } catch (Exception ex) { var errorMessage = CrmExceptionHelper.GetErrorMessage(ex, false); MessageBox.Show(this, "An error occured while retrieving organizations: " + errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } bGetOrganizations.Enabled = true; Cursor = Cursors.Default; //var bw = new BackgroundWorker(); //bw.DoWork += BwGetOrgsDoWork; //bw.RunWorkerCompleted += BwGetOrgsRunWorkerCompleted; //bw.RunWorkerAsync(); } }
/// <summary> /// Gets specified entity metadata (include attributes) /// </summary> /// <param name="logicalName">Logical name of the entity</param> /// <param name="oService">Crm organization service</param> /// <returns>Entity metadata</returns> public static EntityMetadata RetrieveEntity(string logicalName, IOrganizationService oService) { try { var response = (RetrieveEntityResponse)oService.Execute(new RetrieveEntityRequest { LogicalName = logicalName, EntityFilters = EntityFilters.Attributes, RetrieveAsIfPublished = true }); return(response.EntityMetadata); } catch (Exception error) { string errorMessage = CrmExceptionHelper.GetErrorMessage(error, false); throw new Exception("Error while retrieving entity: " + errorMessage); } }
private async Task GetSelectedOrganizationAsync() { comboBoxOrganizations.Items.Clear(); organizations = new List <OrganizationDetail>(); try { var orgDetail = await RetrieveOrganizationAsync(detail); organizations.Add(orgDetail); comboBoxOrganizations.Items.Add(new Organization { OrganizationDetail = orgDetail }); comboBoxOrganizations.SelectedIndex = 0; } catch (Exception ex) { var errorMessage = CrmExceptionHelper.GetErrorMessage(ex, false); MessageBox.Show(this, "An error occured while retrieving organizations: " + errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Copy view layout form source view to all specified target views /// </summary> /// <param name="sourceView">Source view</param> /// <param name="targetViews">List of target views</param> /// <param name="includeSorting">Indicates if sorting must be included in replication operation</param> /// <param name="service">Crm organization service</param> /// <returns>Indicates if all views have been updated</returns> public static List <Tuple <string, string> > PropagateLayout(ViewDefinition sourceView, List <ViewDefinition> targetViews, bool includeSorting, IOrganizationService service) { var errors = new List <Tuple <string, string> >(); string multiObjectAttribute = string.Empty; try { foreach (ViewDefinition targetView in targetViews) { if (targetView.Id != sourceView.Id) { #region Replace target view cells by source view cells // Update grid cells XmlDocument targetLayout = new XmlDocument(); targetLayout.LoadXml(targetView.LayoutXml); XmlAttribute multiAttr = targetLayout.SelectSingleNode("grid/row").Attributes["multiobjectidfield"]; if (multiAttr != null) { multiObjectAttribute = multiAttr.Value; } // We empty the existing cells for (int i = targetLayout.SelectSingleNode("grid/row").ChildNodes.Count; i > 0; i--) { XmlNode toDelete = targetLayout.SelectSingleNode("grid/row").ChildNodes[i - 1]; targetLayout.SelectSingleNode("grid/row").RemoveChild(toDelete); } XmlDocument sourceLayout = new XmlDocument(); sourceLayout.LoadXml(sourceView.LayoutXml); XmlNodeList sourceCellNodes = sourceLayout.SelectNodes("grid/row/cell"); var cells = new List <string>(); foreach (XmlNode cellNode in sourceCellNodes) { if (!cellNode.Attributes["name"].Value.Contains(".") || targetView.Type != VIEW_ASSOCIATED) { cells.Add(cellNode.Attributes["name"].Value); XmlNode nodeDest = targetLayout.ImportNode(cellNode.Clone(), true); targetLayout.SelectSingleNode("grid/row").AppendChild(nodeDest); } } targetView.LayoutXml = targetLayout.OuterXml; #endregion Replace target view cells by source view cells // Retrieve target fetch data if (!string.IsNullOrEmpty(targetView.FetchXml)) { XmlDocument targetFetchDoc = new XmlDocument(); targetFetchDoc.LoadXml(targetView.FetchXml); XmlDocument sourceFetchDoc = new XmlDocument(); sourceFetchDoc.LoadXml(sourceView.FetchXml); XmlNodeList sourceAttrNodes = sourceFetchDoc.SelectNodes("fetch/entity/attribute"); foreach (XmlNode attrNode in sourceAttrNodes) { if (targetFetchDoc.SelectSingleNode("fetch/entity/attribute[@name='" + attrNode.Attributes["name"].Value + "']") == null) { XmlNode attrNodeToAdd = targetFetchDoc.ImportNode(attrNode, true); targetFetchDoc.SelectSingleNode("fetch/entity").AppendChild(attrNodeToAdd); } } foreach (XmlNode cellNode in sourceCellNodes) { string name = cellNode.Attributes["name"].Value; if (!name.Contains(".") && targetFetchDoc.SelectSingleNode("fetch/entity/attribute[@name='" + name + "']") == null) { XmlElement attrNodeToAdd = targetFetchDoc.CreateElement("attribute"); attrNodeToAdd.SetAttribute("name", name); targetFetchDoc.SelectSingleNode("fetch/entity").AppendChild(attrNodeToAdd); } } if (includeSorting) { #region Copy Sorting settings to target views XmlNodeList sourceSortNodes = sourceFetchDoc.SelectNodes("fetch/entity/order"); XmlNodeList targetSortNodes = targetFetchDoc.SelectNodes("fetch/entity/order"); // Removes existing sorting for (int i = targetSortNodes.Count; i > 0; i--) { XmlNode toDelete = targetSortNodes[i - 1]; targetSortNodes[i - 1].ParentNode.RemoveChild(toDelete); } // Append source sorting foreach (XmlNode orderNode in sourceSortNodes) { XmlNode orderNodeToAdd = targetFetchDoc.ImportNode(orderNode, true); targetFetchDoc.SelectSingleNode("fetch/entity").AppendChild(orderNodeToAdd); } #endregion Copy Sorting settings to target views } #region Replicate link entities information // Retrieve source fetch data if (!string.IsNullOrEmpty(sourceView.FetchXml)) { //XmlDocument sourceFetchDoc = new XmlDocument(); //sourceFetchDoc.LoadXml(sourceView["fetchxml"].ToString()); XmlNodeList linkNodes = sourceFetchDoc.SelectNodes("fetch/entity/link-entity"); foreach (XmlNode sourceLinkNode in linkNodes) { var alias = sourceLinkNode.Attributes["alias"].Value; if (cells.FirstOrDefault(c => c.StartsWith(alias + ".")) == null) { continue; } XmlNode targetLinkNode = targetFetchDoc.SelectSingleNode("fetch/entity/link-entity[@alias=\"" + alias + "\"]"); // Adds the missing link-entity node if (targetLinkNode == null) { XmlNode nodeDest = targetFetchDoc.ImportNode(sourceLinkNode.Clone(), true); XmlAttribute typeAttr = nodeDest.Attributes["link-type"]; if (typeAttr == null) { typeAttr = targetFetchDoc.CreateAttribute("link-type"); typeAttr.Value = "outer"; nodeDest.Attributes.Append(typeAttr); } else { typeAttr.Value = "outer"; } targetFetchDoc.SelectSingleNode("fetch/entity").AppendChild(nodeDest); } // Retrieves node again (if it was added) targetLinkNode = targetFetchDoc.SelectSingleNode("fetch/entity/link-entity[@alias=\"" + alias + "\"]"); // Removes existing attributes for (int i = targetLinkNode.ChildNodes.Count; i > 0; i--) { if (targetLinkNode.ChildNodes[i - 1].Name == "attribute") { XmlNode toDelete = targetLinkNode.ChildNodes[i - 1]; targetLinkNode.RemoveChild(toDelete); } } // Adds the attribute nodes from the source node foreach (XmlNode node in sourceLinkNode.ChildNodes) { if (node.Name == "attribute") { XmlNode attributeNode = targetLinkNode.SelectSingleNode("attribute[@name='" + node.Attributes["name"].Value + "']"); if (attributeNode == null) { XmlNode nodeDest = targetFetchDoc.ImportNode(node.Clone(), true); targetLinkNode.AppendChild(nodeDest); } } } } } // Suppression des éléments Attribute inutiles dans la requête List <string> attributesToRemove = new List <string>(); foreach (XmlNode attributeNode in targetFetchDoc.SelectNodes("//attribute")) { if (attributeNode.Attributes["name"].Value == multiObjectAttribute) { break; } bool isFoundInCell = false; foreach (XmlNode cellNode in sourceLayout.SelectNodes("grid/row/cell")) { if (attributeNode.ParentNode.Name == "link-entity") { if (cellNode.Attributes["name"].Value == attributeNode.ParentNode.Attributes["alias"].Value + "." + attributeNode.Attributes["name"].Value) { isFoundInCell = true; break; } } else { if (attributeNode.Attributes["name"].Value == (attributeNode.ParentNode.Attributes["name"].Value + "id") || cellNode.Attributes["name"].Value == attributeNode.Attributes["name"].Value) { isFoundInCell = true; break; } } } if (!isFoundInCell) { if (attributeNode.ParentNode.Name == "link-entity") { attributesToRemove.Add(attributeNode.ParentNode.Attributes["alias"].Value + "." + attributeNode.Attributes["name"].Value); } else { attributesToRemove.Add(attributeNode.Attributes["name"].Value); } } } foreach (string attributeName in attributesToRemove) { XmlNode node; if (attributeName.Contains(".")) { node = targetFetchDoc.SelectSingleNode("fetch/entity/link-entity[@alias='" + attributeName.Split('.')[0] + "']/attribute[@name='" + attributeName.Split('.')[1] + "']"); targetFetchDoc.SelectSingleNode("fetch/entity/link-entity[@alias='" + node.ParentNode.Attributes["alias"].Value + "']").RemoveChild(node); } else { node = targetFetchDoc.SelectSingleNode("fetch/entity/attribute[@name='" + attributeName + "']"); targetFetchDoc.SelectSingleNode("fetch/entity").RemoveChild(node); } } foreach (XmlNode linkentityNode in targetFetchDoc.SelectNodes("fetch/entity/link-entity")) { if (linkentityNode != null && linkentityNode.ChildNodes.Count == 0) { targetFetchDoc.SelectSingleNode("fetch/entity").RemoveChild(linkentityNode); } } targetView.FetchXml = targetFetchDoc.OuterXml; #endregion Replicate link entities information } #region Save target view try { targetView.InnerRecord.Attributes.Remove("statecode"); targetView.InnerRecord.Attributes.Remove("statuscode"); service.Update(targetView.InnerRecord); } catch (Exception error) { errors.Add(new Tuple <string, string>(targetView.Name, error.Message)); } #endregion Save target view } } return(errors); } catch (Exception error) { string errorMessage = CrmExceptionHelper.GetErrorMessage(error, false); throw new Exception("Error while copying layout to target views: " + errorMessage); } }
private async void BGetSolutionsClick(object sender, EventArgs e) { if (FillConnectionDetails()) { var organization = (Organization)comboBoxOrganizations.SelectedItem; var organizationDetail = organization.OrganizationDetail; detail.OrganizationId = organizationDetail.OrganizationId.ToString(); detail.OrganizationServiceUrl = organizationDetail.Endpoints[EndpointType.OrganizationService]; detail.Organization = organizationDetail.UniqueName; detail.OrganizationUrlName = organizationDetail.UrlName; detail.OrganizationFriendlyName = organizationDetail.FriendlyName; detail.OrganizationVersion = organizationDetail.OrganizationVersion; // Launch organization retrieval comboBoxSolutions.Items.Clear(); solutions = new List <SolutionDetail>(); Cursor = Cursors.WaitCursor; bGetSolutions.Enabled = false; try { var solutionsResponse = await RetrieveSolutionsAsync(detail); foreach (Entity entity in solutionsResponse) { var solutionDetail = new SolutionDetail() { SolutionId = entity.Id, UniqueName = entity.GetAttributeValue <string>("uniquename"), FriendlyName = entity.GetAttributeValue <string>("friendlyname"), PublisherPrefix = entity.GetAttributeValue <AliasedValue>("publisher.customizationprefix") == null ? null : entity.GetAttributeValue <AliasedValue>("publisher.customizationprefix").Value.ToString() }; solutions.Add(solutionDetail); comboBoxSolutions.Items.Add(new Solution() { SolutionDetail = solutionDetail }); comboBoxSolutions.SelectedIndex = 0; } if (comboBoxSolutions.Items.Count > 0) { comboBoxSolutions.Enabled = true; } } catch (Exception ex) { var errorMessage = CrmExceptionHelper.GetErrorMessage(ex, false); MessageBox.Show(this, "An error occured while retrieving solutions: " + errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } bGetSolutions.Enabled = true; Cursor = Cursors.Default; //var bw = new BackgroundWorker(); //bw.DoWork += BwGetSolutionsDoWork; //bw.RunWorkerCompleted += BwGetSolutionsRunWorkerCompleted; //bw.RunWorkerAsync(); } }
public static List <Tuple <string, string> > TransferViews(List <Entity> sourceViews, IOrganizationService sourceService, IOrganizationService targetService, EntityMetadata savedQueryMetadata) { var errors = new List <Tuple <string, string> >(); try { foreach (var sourceView in sourceViews) { // Identifiy ownerid domainname if userquery string userDomainName = null; if (sourceView.LogicalName == "userquery") { var sourceUser = sourceService.Retrieve("systemuser", sourceView.GetAttributeValue <EntityReference>("ownerid").Id, new ColumnSet("domainname")); userDomainName = sourceUser.GetAttributeValue <string>("domainname"); } var targetViewQuery = new QueryExpression(sourceView.LogicalName); targetViewQuery.ColumnSet = new ColumnSet { AllColumns = true }; targetViewQuery.Criteria.AddCondition(sourceView.LogicalName + "id", ConditionOperator.Equal, sourceView.Id); var targetViews = targetService.RetrieveMultiple(targetViewQuery); if (targetViews.Entities.Count > 0) { // We need to update the existing view var targetView = CleanEntityForUpdate(savedQueryMetadata, sourceView); // Replace ObjectTypeCode in layoutXml ReplaceLayoutXmlObjectTypeCode(targetView, targetService); try { targetService.Update(targetView); } catch (Exception error) { errors.Add(new Tuple <string, string>(targetView["name"].ToString(), error.Message)); } } else { // We need to create the view var targetView = CleanEntityForCreate(savedQueryMetadata, sourceView); if (targetView.LogicalName == "userquery") { // Let's find the user based on systemuserid or domainname var targetUser = targetService.RetrieveMultiple(new QueryExpression("systemuser") { Criteria = new FilterExpression(LogicalOperator.Or) { Conditions = { new ConditionExpression("domainname", ConditionOperator.Equal, userDomainName ?? "dummyValueNotExpectedAsDomainNameToAvoidSystemAccount"), new ConditionExpression("systemuserid", ConditionOperator.Equal, sourceView.GetAttributeValue <EntityReference>("ownerid").Id), } } }).Entities.FirstOrDefault(); if (targetUser != null) { targetView["ownerid"] = targetUser.ToEntityReference(); } else { throw new Exception(string.Format( "Unable to find a user in the target organization with domain name '{0}' or id '{1}'", userDomainName, sourceView.GetAttributeValue <EntityReference>("ownerid").Id)); } } // Replace ObjectTypeCode in layoutXml ReplaceLayoutXmlObjectTypeCode(targetView, targetService); try { targetService.Create(targetView); } catch (Exception error) { errors.Add(new Tuple <string, string>(sourceView["name"].ToString(), error.Message)); } } } return(errors); } catch (Exception error) { string errorMessage = CrmExceptionHelper.GetErrorMessage(error, false); throw new Exception("Error while transfering views: " + errorMessage); } }
public void FillOrganizations() { try { Guid applicationId = new Guid("6f4cad4a-e3d4-41d7-8ac7-cd17a69c3997");// Guid.NewGuid();// //// SetCursor(this, Cursors.WaitCursor); WebRequest.GetSystemWebProxy(); var connection = CrmConnection.Parse(_connectionDetail.GetDiscoveryCrmConnectionString()); var service = new DiscoveryService(connection); var request = new RetrieveOrganizationsRequest(); var response = (RetrieveOrganizationsResponse)service.Execute(request); _organizations = new List <OrganizationDetail>(); foreach (OrganizationDetail orgDetail in response.Details) { _organizations.Add(orgDetail); cbbOrganizations.Items.Add(new OrgDetail { Detail = orgDetail }); } cbbOrganizations.SelectedIndex = 0; //var sc = new ServerConnection(); //sc.config = sc.GetServerConfiguration(_connectionDetail, applicationId); //WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy(); //using (var serviceProxy = new DiscoveryServiceProxy(sc.config.DiscoveryUri, sc.config.HomeRealmUri, sc.config.Credentials, sc.config.DeviceCredentials)) //{ // _organizations = new List<OrganizationDetail>(); // // Obtain information about the organizations that the system user belongs to. // var orgsCollection = sc.DiscoverOrganizations(serviceProxy); // foreach (var orgDetail in orgsCollection) // { // _organizations.Add(orgDetail); // cbbOrganizations.Items.Add(new OrgDetail{Detail = orgDetail}); // //AddItem(comboBoxOrganizations, new Organization() { OrganizationDetail = orgDetail }); // //SelectUniqueValue(comboBoxOrganizations); // } // cbbOrganizations.SelectedIndex = 0; //} //// SetEnableState(comboBoxOrganizations, true); } catch (Exception error) { string errorMessage = CrmExceptionHelper.GetErrorMessage(error, false); MessageBox.Show(errorMessage); //if (error.InnerException != null) //DisplayMessageBox(this, "Error while retrieving organizations : " + errorMessage + "\r\n" + error.InnerException.Message + "\r\n" + error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); //else //DisplayMessageBox(this, "Error while retrieving organizations : " + errorMessage + "\r\n" + error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { //SetCursor(this, Cursors.Default); } }
public string GetErrorMessage(Exception error, bool returnWithStackTrace) { return(CrmExceptionHelper.GetErrorMessage(error, false)); }