private OrganizationRequestCollection GetOrgRequestsForCreateOrUpdate(Dictionary <string, Entity> recordsToBeProcessed, Operation operation) { OrganizationRequestCollection orgReqs = new OrganizationRequestCollection(); foreach (var recordKvp in recordsToBeProcessed) { // Guid requestId = Guid.NewGuid(); if (operation == Operation.Create) { CreateRequest createRequest = new CreateRequest { Target = recordKvp.Value }; orgReqs.Add(createRequest); } else if (operation == Operation.Update) { UpdateRequest updateRequest = new UpdateRequest { Target = recordKvp.Value }; orgReqs.Add(updateRequest); } } return(orgReqs); }
private static void DeployWebResource(DTE dte, CrmServiceClient crmServiceClient, string crmUrl, string fullFileName, string fileName, Guid webResourceId) { var requests = new OrganizationRequestCollection(); var webResource = new Entity("webresource") { Id = webResourceId }; webResource["content"] = Convert.ToBase64String(File.ReadAllBytes(fullFileName)); var request = new UpdateRequest { Target = webResource }; requests.Add(request); var publishXml = $"<importexportxml><webresources><webresource>{webResource.Id}</webresource></webresources></importexportxml>"; var pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; requests.Add(pubRequest); var multipleRequest = new ExecuteMultipleRequest { Requests = requests, Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; UtilityPackage.SetDTEStatusBar(dte, $"[{crmUrl}] Updating & Publishing WebResource"); var multipleResponse = (ExecuteMultipleResponse)crmServiceClient.Execute(multipleRequest); foreach (var response in multipleResponse.Responses) { if (response.Fault == null) { continue; } UtilityPackage.SetDTEStatusBar(dte, $"[{crmUrl}] Deploy WebResource failed"); return; } var webResourceName = string.Empty; var selected = DevKitSetting.SelectedWebResources.Where(x => x.FullFileName == fullFileName).FirstOrDefault(); if (selected != null) { webResourceName = selected.WebResourceName; } UtilityPackage.SetDTEStatusBar(dte, $"Deployed: [{fileName}] to [{webResourceName}]"); }
/// <summary> /// Adds a retrieve multiple request to the current OrganizationRequestCollection. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requests">The requests.</param> /// <param name="columnSet">The column set.</param> /// <param name="columnNameAndValuePairs">The column name and value pairs.</param> public static void AddRetrieveMultiple <T>(this OrganizationRequestCollection requests, ColumnSet columnSet, params object[] columnNameAndValuePairs) where T : Entity { requests.Add(new RetrieveMultipleRequest { Query = QueryExpressionFactory.Create <T>(columnSet, columnNameAndValuePairs), }); }
/// <summary> /// Adds a retrieve multiple request to the current OrganizationRequestCollection. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requests">The requests.</param> /// <param name="anonymousTypeInitializer">The anonymous type initializer.</param> /// <param name="columnNameAndValuePairs">The column name and value pairs.</param> public static void AddRetrieveMultiple <T>(this OrganizationRequestCollection requests, Expression <Func <T, object> > anonymousTypeInitializer, params object[] columnNameAndValuePairs) where T : Entity { requests.Add(new RetrieveMultipleRequest { Query = QueryExpressionFactory.Create(anonymousTypeInitializer, columnNameAndValuePairs), }); }
private static OrganizationRequestCollection ToOrganizationRequestCollection(IEnumerable <OrganizationRequest> requests) { var collection = new OrganizationRequestCollection(); foreach (var request in requests) { collection.Add(request); } return(collection); }
/// <summary> /// Execute Multiple Request /// </summary> /// <param name="service">Organization Service</param> /// <param name="crmRequestType">Request Type</param> /// <param name="entityCollection">Entity Collection</param> /// <param name="continueOnError">Continue on Error Indicator</param> /// <returns>Failed Record Count</returns> private static int ExecuteMultipleRequest(IOrganizationService service, RequestType crmRequestType, EntityCollection entityCollection, bool continueOnError) { int failCount = 0; if (entityCollection != null && entityCollection.Entities != null && entityCollection.Entities.Count > 0) { OrganizationRequestCollection requestCollection = new OrganizationRequestCollection(); foreach (var entity in entityCollection.Entities) { switch (crmRequestType) { case RequestType.Create: requestCollection.Add(new CreateRequest { Target = entity }); break; case RequestType.Update: requestCollection.Add(new UpdateRequest { Target = entity }); break; } if (requestCollection.Count == 1000) { failCount = failCount + ProcessExecuteMultipleAndReturnFailCount(requestCollection, service, continueOnError); requestCollection.Clear(); } } if (requestCollection.Count > 0) { failCount = failCount + ProcessExecuteMultipleAndReturnFailCount(requestCollection, service, continueOnError); } } return(failCount); }
private static OrganizationRequestCollection CreateUpdateRequests(List <Entity> webResources) { OrganizationRequestCollection requests = new OrganizationRequestCollection(); foreach (Entity webResource in webResources) { UpdateRequest request = new UpdateRequest { Target = webResource }; requests.Add(request); } return(requests); }
private OrganizationRequestCollection GetOrgRequestsForRetrieveMultiple(Dictionary <string, QueryExpression> queriesToBeProcessed) { OrganizationRequestCollection orgReqs = new OrganizationRequestCollection(); foreach (var queryRecord in queriesToBeProcessed) { RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest { Query = queryRecord.Value }; orgReqs.Add(retrieveMultipleRequest); } return(orgReqs); }
/// <summary> /// Data is assumed to be there, so use TryDelete /// </summary> /// <param name="service"></param> protected virtual void CleanupDataPostInitialization(IOrganizationService service) { var totalWatch = new Stopwatch(); totalWatch.Start(); var requests = new OrganizationRequestCollection(); foreach (var id in EntityIds.Where(e => e.Key != "businessunit").SelectMany(entityType => entityType.Value)) { requests.Add(new DeleteRequest { Target = Entities[id] }); } if (requests.Any()) { var response = (ExecuteMultipleResponse)service.Execute( new ExecuteMultipleRequest() { Settings = new ExecuteMultipleSettings() { ContinueOnError = true, ReturnResponses = false }, Requests = requests, }); ThrowExceptionForFaults(response, requests); totalWatch.Stop(); Debug.WriteLine("Total Time to delete {0} entities of types {1} (ms): {2}", requests.Count, String.Join(", ", requests.Select(s => ((DeleteRequest)s).Target.LogicalName).Distinct()), totalWatch.ElapsedMilliseconds); } List <Guid> businessIds; if (!EntityIds.TryGetValue("businessunit", out businessIds)) { return; } foreach (var id in businessIds) { service.DeleteBusinessUnit(id); } }
internal static void UpdateDataWithEntities(Context context, IOrganizationService service, ref List <DataLine> data) { OrganizationRequestCollection retrieveMultipleRequestsCollection = new OrganizationRequestCollection( ); int firstDataIndex = 0; int dataTotalCount = data.Count; for (int i = 0; i < dataTotalCount; i++) { if (data [i].IsOk) { QueryExpression queryExpression = new QueryExpression { TopCount = 1, ColumnSet = new ColumnSet(false) }; foreach (var item in context.ColumnItems.Where(a => a.ColumnType == ColumnTypeCode.DynamicConditionExpression)) { queryExpression.Criteria.AddCondition(item.LogicalName, item.ConditionOperatorCode, data [i].LineData [context.ColumnItems.IndexOf(item)]); } retrieveMultipleRequestsCollection.Add(new RetrieveMultipleRequest( ) { Query = queryExpression }); if (retrieveMultipleRequestsCollection.Count( ) >= context.BatchSize) { ExecuteRetrieveMultiple(service, retrieveMultipleRequestsCollection, firstDataIndex, ref data); //initialisation retrieveMultipleRequestsCollection.Clear( ); firstDataIndex = i + 1; } } } if (retrieveMultipleRequestsCollection.Count != 0) { ExecuteRetrieveMultiple(service, retrieveMultipleRequestsCollection, firstDataIndex, ref data); } }
private void CopyData(IOrganizationService service, AttributeMetadata from, AttributeMetadata to, Action actions) { if (!MigrateData) { return; } var total = GetRecordCount(service, from); var count = 0; Trace("Copying data from {0} to {1}", from.LogicalName, to.LogicalName); var requests = new OrganizationRequestCollection(); // Grab from and to, and only update if not equal. This is to speed things up if it has failed part way through foreach (var entity in service.GetAllEntities <Entity>(new QueryExpression(from.EntityLogicalName) { ColumnSet = new ColumnSet(from.LogicalName, to.LogicalName) })) { if (count++ % 100 == 0 || count == total) { if (requests.Any()) { PerformUpdates(service, requests); } Trace("Copying {0} / {1}", count, total); requests.Clear(); } var value = entity.GetAttributeValue <Object>(from.LogicalName); if (actions.HasFlag(Action.ChangeType) && from.GetType() != to.GetType()) { value = CopyValue(from, to, value); } var toValue = entity.GetAttributeValue <Object>(to.LogicalName); if (value != null) { if (value.Equals(toValue)) { continue; } entity.Attributes[to.LogicalName] = value; requests.Add(new UpdateRequest { Target = entity }); } else if (toValue != null) { entity.Attributes[to.LogicalName] = null; requests.Add(new UpdateRequest { Target = entity }); } } if (requests.Any()) { PerformUpdates(service, requests); } Trace("Data Migration Complete", count, total); }
private void UpdateAndPublishMultiple(CrmConnection connection, ProjectItem projectItem, Guid webResourceId) { try { ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; OrganizationRequestCollection requests = new OrganizationRequestCollection(); string publishXml = "<importexportxml><webresources>"; Entity webResource = new Entity("webresource") { Id = webResourceId }; string extension = Path.GetExtension(projectItem.FileNames[1]); string content = extension != null && (extension.ToUpper() != ".TS") ? File.ReadAllText(projectItem.FileNames[1]) : File.ReadAllText(Path.ChangeExtension(projectItem.FileNames[1], ".js")); webResource["content"] = EncodeString(content); UpdateRequest request = new UpdateRequest { Target = webResource }; requests.Add(request); publishXml += "<webresource>{" + webResource.Id + "}</webresource>"; publishXml += "</webresources></importexportxml>"; PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; requests.Add(pubRequest); emRequest.Requests = requests; using (OrganizationService orgService = new OrganizationService(connection)) { _dte.StatusBar.Text = "Updating & publishing web resource..."; _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); ExecuteMultipleResponse emResponse = (ExecuteMultipleResponse)orgService.Execute(emRequest); bool wasError = false; foreach (var responseItem in emResponse.Responses) { if (responseItem.Fault == null) { continue; } _logger.WriteToOutputWindow( "Error Updating And Publishing Web Resources To CRM: " + responseItem.Fault.Message + Environment.NewLine + responseItem.Fault.TraceText, Logger.MessageType.Error); wasError = true; } if (wasError) { MessageBox.Show("Error Updating And Publishing Web Resources To CRM. See the Output Window for additional details."); } else { _logger.WriteToOutputWindow("Updated And Published Web Resource", Logger.MessageType.Info); } } } catch (FaultException <OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); } catch (Exception ex) { _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); } _dte.StatusBar.Clear(); _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); }
public void Execute(IServiceProvider serviceProvider) { ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = factory.CreateOrganizationService(context.UserId); Entity unitEntity = null; if (!context.InputParameters.Contains(Constants.TARGET)) { return; } if (((Entity)context.InputParameters[Constants.TARGET]).LogicalName != Constants.Units.LogicalName) { return; } try { switch (context.MessageName) { case Constants.Messages.Update: if (context.InputParameters.Contains(Constants.TARGET) && context.InputParameters[Constants.TARGET] is Entity && context.PostEntityImages.Contains(Constants.POST_IMAGE)) { unitEntity = context.PostEntityImages[Constants.POST_IMAGE] as Entity; } else { return; } break; } if (unitEntity is Entity) { OrganizationRequestCollection orgRequestCollection = new OrganizationRequestCollection(); int cnt = 0; //Retrieve All Project Task from System... List <Entity> projectTaskEntityList = CommonMethods.RetrieveAllProjectTaskByUnit(tracer, service, unitEntity.ToEntityReference()); foreach (Entity projectTaskEntity in projectTaskEntityList) { Entity tmpEntity = new Entity(projectTaskEntity.LogicalName); tmpEntity.Id = projectTaskEntity.Id; bool isUpdateRequired = false; //Access Notes if (unitEntity.Attributes.Contains(Constants.Units.AccessNotes)) { if (!string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.AccessNotes))) { if (projectTaskEntity.Attributes.Contains(Constants.Units.AccessNotes) && unitEntity.GetAttributeValue <string>(Constants.Units.AccessNotes).Equals(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.AccessNotes))) { tmpEntity[Constants.ProjectTasks.AccessNotes] = unitEntity.GetAttributeValue <string>(Constants.Units.AccessNotes); isUpdateRequired = true; } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.AccessNotes) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.AccessNotes))) { tmpEntity[Constants.ProjectTasks.AccessNotes] = null; isUpdateRequired = true; } } } //LockBox Removed if (unitEntity.Attributes.Contains(Constants.Units.LockBoxRemoved)) { if (!string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.LockBoxRemoved))) { if (projectTaskEntity.Attributes.Contains(Constants.Units.LockBoxRemoved) && unitEntity.GetAttributeValue <string>(Constants.Units.LockBoxRemoved).Equals(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.LockBoxRemoved))) { tmpEntity[Constants.ProjectTasks.LockBoxRemoved] = unitEntity.GetAttributeValue <DateTime>(Constants.Units.LockBoxRemoved); isUpdateRequired = true; } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.LockBoxRemoved) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.LockBoxRemoved))) { tmpEntity[Constants.ProjectTasks.LockBoxRemoved] = null; isUpdateRequired = true; } } } //Mechanical Lockbox if (unitEntity.Attributes.Contains(Constants.Units.MechanicalLockBox)) { if (!string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBox))) { if (projectTaskEntity.Attributes.Contains(Constants.Units.MechanicalLockBox) && unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBox).Equals(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.MechanicalLockBox))) { tmpEntity[Constants.ProjectTasks.MechanicalLockBox] = unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBox); isUpdateRequired = true; } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.MechanicalLockBox) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.MechanicalLockBox))) { tmpEntity[Constants.ProjectTasks.MechanicalLockBox] = null; isUpdateRequired = true; } } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.MechanicalLockBox) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.MechanicalLockBox))) { tmpEntity[Constants.ProjectTasks.MechanicalLockBox] = null; isUpdateRequired = true; } } //Mechanical Lockbox Note if (unitEntity.Attributes.Contains(Constants.Units.MechanicalLockBoxNote)) { if (!string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBoxNote))) { if (projectTaskEntity.Attributes.Contains(Constants.Units.MechanicalLockBoxNote) && unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBoxNote).Equals(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.MechanicalLockBoxNote))) { tmpEntity[Constants.ProjectTasks.MechanicalLockBoxNote] = unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBoxNote); isUpdateRequired = true; } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.MechanicalLockBoxNote) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.MechanicalLockBoxNote))) { tmpEntity[Constants.ProjectTasks.MechanicalLockBoxNote] = null; isUpdateRequired = true; } } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.MechanicalLockBoxNote) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.MechanicalLockBoxNote))) { tmpEntity[Constants.ProjectTasks.MechanicalLockBoxNote] = null; isUpdateRequired = true; } } //Property Gate Code if (unitEntity.Attributes.Contains(Constants.Units.PropertyGateCode)) { if (!string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBoxNote))) { if (projectTaskEntity.Attributes.Contains(Constants.Units.MechanicalLockBoxNote) && unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBoxNote).Equals(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.MechanicalLockBoxNote))) { tmpEntity[Constants.ProjectTasks.PropertyGateCode] = unitEntity.GetAttributeValue <string>(Constants.Units.PropertyGateCode); isUpdateRequired = true; } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.MechanicalLockBoxNote) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.MechanicalLockBoxNote))) { tmpEntity[Constants.ProjectTasks.MechanicalLockBoxNote] = null; isUpdateRequired = true; } } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.MechanicalLockBoxNote) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.MechanicalLockBoxNote))) { tmpEntity[Constants.ProjectTasks.MechanicalLockBoxNote] = null; isUpdateRequired = true; } } //Rently Lockbox if (unitEntity.Attributes.Contains(Constants.Units.RentlyLockBox)) { if (!string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.RentlyLockBox))) { if (projectTaskEntity.Attributes.Contains(Constants.Units.RentlyLockBox) && unitEntity.GetAttributeValue <string>(Constants.Units.RentlyLockBox).Equals(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.RentlyLockBox))) { tmpEntity[Constants.ProjectTasks.RentlyLockBox] = unitEntity.GetAttributeValue <string>(Constants.Units.RentlyLockBox); isUpdateRequired = true; } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.RentlyLockBox) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.RentlyLockBox))) { tmpEntity[Constants.ProjectTasks.RentlyLockBox] = null; isUpdateRequired = true; } } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.RentlyLockBox) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.RentlyLockBox))) { tmpEntity[Constants.ProjectTasks.RentlyLockBox] = null; isUpdateRequired = true; } } //Rently Lock Box Note if (unitEntity.Attributes.Contains(Constants.Units.RentlyLockBoxNote)) { if (!string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.RentlyLockBoxNote))) { if (projectTaskEntity.Attributes.Contains(Constants.Units.RentlyLockBoxNote) && unitEntity.GetAttributeValue <string>(Constants.Units.RentlyLockBoxNote).Equals(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.RentlyLockBoxNote))) { tmpEntity[Constants.ProjectTasks.RentlyLockBoxNote] = unitEntity.GetAttributeValue <string>(Constants.Units.RentlyLockBoxNote); isUpdateRequired = true; } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.RentlyLockBoxNote) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.RentlyLockBoxNote))) { tmpEntity[Constants.ProjectTasks.RentlyLockBoxNote] = null; isUpdateRequired = true; } } } else { if (projectTaskEntity.Attributes.Contains(Constants.Units.RentlyLockBoxNote) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.RentlyLockBoxNote))) { tmpEntity[Constants.ProjectTasks.RentlyLockBoxNote] = null; isUpdateRequired = true; } } if (isUpdateRequired) { orgRequestCollection.Add(new UpdateRequest() { Target = tmpEntity }); } else { tracer.Trace($"No updates available to update Unit Info. Existing loop. and plugin."); break; } cnt++; if (cnt > 998) { CommonMethods.PerformExecuteMultipleRequest(service, orgRequestCollection); orgRequestCollection = new OrganizationRequestCollection(); cnt = 0; } } if (cnt > 0) { CommonMethods.PerformExecuteMultipleRequest(service, orgRequestCollection); } } } catch (Exception e) { throw new InvalidPluginExecutionException(e.Message); } }
private static void ExecuteWebResource(AsyncPackage package) { Dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); var activeDocument = Dte.ActiveDocument; var solutionFullName = Dte.Solution.FullName; var fInfo = new FileInfo(solutionFullName); var devKitCrmConfigFile = $"{fInfo.DirectoryName}\\PL.DynamicsCrm.DevKit.json"; Dte.StatusBar.Text = "Reading PL.DynamicsCrm.DevKit.json config"; if (Config == null) { Config = DevKitCrmConfigHelper.GetDevKitCrmConfig(Dte); } var defaultConnection = Config.CrmConnections.Where(conn => conn.Name == Config.DefaultCrmConnection).FirstOrDefault(); Dte.StatusBar.Text = "Connecting to Dynamics 365"; if (defaultConnection == null) { Dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); Dte.StatusBar.Text = " !!! Connection to Dynamics 365 failed !!! "; MessageBox.Show("Default Crm connection not found!", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (Config.SolutionPrefix == null) { Dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); Dte.StatusBar.Text = " !!! Connection to Dynamics 365 failed !!! "; MessageBox.Show("PL.DynamicsCrm.DevKit.json config not found SolutionPrefix data", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var check = SharedGlobals.GetGlobal("CrmService", Dte); if (check == null) { try { var uri = new Uri(defaultConnection.Url); var clientCredentials = new ClientCredentials(); clientCredentials.UserName.UserName = defaultConnection.UserName; clientCredentials.UserName.Password = TryDecryptPassword(defaultConnection.Password); check = new OrganizationServiceProxy(uri, null, clientCredentials, null); SharedGlobals.SetGlobal("CrmService", check, Dte); } catch { Dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); Dte.StatusBar.Text = " !!! Connection to Dynamics 365 fail !!! "; MessageBox.Show("Connection to Dynamics 365 fail!", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } var crmService = (OrganizationServiceProxy)SharedGlobals.GetGlobal("CrmService", Dte); Dte.StatusBar.Text = " !!! Connected Dynamics 365 !!! "; var fileName = activeDocument.FullName; var parts = fileName.Split("\\".ToCharArray()); var condition = string.Empty; for (var i = 1; i < parts.Length; i++) { var value = $"{Config.SolutionPrefix}/{parts[i]}/"; for (var j = i + 1; j < parts.Length; j++) { value += $"{parts[j]}/"; } if (value.EndsWith("/")) { value = value.TrimEnd("/".ToCharArray()); } if (value.StartsWith("/")) { value = value.Substring(1); } condition += $"<condition attribute='name' operator='ends-with' value='{value}'/>"; } var fetchXml = $@" <fetch> <entity name='webresource'> <attribute name='name' /> <filter type='or'> {condition} </filter> </entity> </fetch>"; var rows = crmService.RetrieveMultiple(new FetchExpression(fetchXml)); if (rows.Entities.Count == 0) { Dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); Dte.StatusBar.Text = " !!! WebResource not found !!! "; MessageBox.Show("WebResource not found!", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var webResourceId = rows.Entities[0].Id; try { var emRequest = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; var requests = new OrganizationRequestCollection(); var publishXml = "<importexportxml><webresources>"; var webResource = new Entity("webresource") { Id = webResourceId }; var content = File.ReadAllText(fileName); webResource["content"] = EncodeString(content); var request = new UpdateRequest { Target = webResource }; requests.Add(request); publishXml += "<webresource>{" + webResource.Id + "}</webresource>"; publishXml += "</webresources></importexportxml>"; var pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; requests.Add(pubRequest); emRequest.Requests = requests; Dte.StatusBar.Text = "Updating & publishing WebResource ... "; var emResponse = (ExecuteMultipleResponse)crmService.Execute(emRequest); var wasError = false; foreach (var responseItem in emResponse.Responses) { if (responseItem.Fault == null) { continue; } wasError = true; } if (wasError) { Dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); Dte.StatusBar.Text = " !!! Deploy WebResource failed !!! "; MessageBox.Show("Deploy WebResource failed.", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { Dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); Dte.StatusBar.Text = " !!! Deploy WebResource succeeded !!! "; return; } } catch (FaultException <OrganizationServiceFault> ) { Dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); Dte.StatusBar.Text = " !!! Deploy WebResource failed !!! "; MessageBox.Show("Deploy WebResource failed.", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } catch { Dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); Dte.StatusBar.Text = " !!! Deploy WebResource failed !!! "; MessageBox.Show("Deploy WebResource failed.", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } }
public static MsCrmResult Process() { MsCrmResult returnValue = new MsCrmResult(); Console.WriteLine("Update Contact Title Case working...."); int errorCount = 0; int successCount = 0; IOrganizationService service = MSCRM.GetOrgService(true); SqlDataAccess sda = new SqlDataAccess(); sda.openConnection(Globals.ConnectionString); #region | SQL QUERY | string sqlQuery = @"SELECT c.ContactId ,c.FirstName ,c.LastName FROM Contact AS c (NOLOCK) WHERE c.StateCode=0 --AND --c.ContactId IN ('09055AF4-95F4-E411-80D0-005056A60603','B40A2ADB-94F4-E411-80D0-005056A60603') ORDER BY c.CreatedOn DESC" ; #endregion DataTable dt = sda.getDataTable(sqlQuery); Console.SetCursorPosition(0, 2); Console.WriteLine("Data Count:" + dt.Rows.Count.ToString()); if (dt.Rows.Count > 0) { OrganizationRequestCollection reqList = new OrganizationRequestCollection(); int packetCount = dt.Rows.Count % 1000; int packetCounter = 0; for (int i = 0; i < dt.Rows.Count; i++) { Console.SetCursorPosition(0, 3); Console.WriteLine("COUNTER:" + (i + 1).ToString()); try { string firstName = dt.Rows[i]["FirstName"] != DBNull.Value ? dt.Rows[i]["FirstName"].ToString() : string.Empty; string lastName = dt.Rows[i]["LastName"] != DBNull.Value ? dt.Rows[i]["LastName"].ToString() : string.Empty; string newFirstName = string.Empty; string newLastName = string.Empty; if (firstName != string.Empty) { newFirstName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(firstName.ToLower()); } if (lastName != string.Empty) { newLastName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lastName.ToLower()); } Entity ent = new Entity("contact"); ent.Id = (Guid)dt.Rows[i]["ContactId"]; ent["firstname"] = newFirstName; ent["lastname"] = newLastName; UpdateRequest updateRequest = new UpdateRequest(); updateRequest.Target = ent; reqList.Add(updateRequest); if (reqList.Count == 1000) { MigrationHelper.executeMultipleWithRequests(reqList, "contacttitlecase", service); reqList = new OrganizationRequestCollection(); packetCounter++; Console.SetCursorPosition(0, 8); Console.WriteLine("Packet:" + packetCounter.ToString()); } if (packetCounter > packetCount && (i + 1) == dt.Rows.Count) { MigrationHelper.executeMultipleWithRequests(reqList, "contacttitlecase", service); reqList = new OrganizationRequestCollection(); } //service.Update(ent); successCount++; Console.SetCursorPosition(0, 5); Console.WriteLine("Success:" + successCount.ToString()); } catch (Exception ex) { errorCount++; Console.SetCursorPosition(0, 6); Console.WriteLine("Error:" + errorCount.ToString()); } } } return(returnValue); }
private void CopyData(IOrganizationService service, AttributeMetadata from, AttributeMetadata to, Action actions) { if (!MigrateData) { return; } var total = GetRecordCount(service, from); var count = 0; Trace("Copying data from {0} to {1}", from.LogicalName, to.LogicalName); var requests = new OrganizationRequestCollection(); // Grab from and to, and only update if not equal. This is to speed things up if it has failed part way through foreach (var entity in service.GetAllEntities<Entity>(new QueryExpression(from.EntityLogicalName) { ColumnSet = new ColumnSet(from.LogicalName, to.LogicalName) })) { if (count++ % 100 == 0 || count == total) { if (requests.Any()) { PerformUpdates(service, requests); } Trace("Copying {0} / {1}", count, total); requests.Clear(); } var value = entity.GetAttributeValue<Object>(from.LogicalName); if (actions.HasFlag(Action.ChangeType) && from.GetType() != to.GetType()) { value = CopyValue(from, to, value); } var toValue = entity.GetAttributeValue<Object>(to.LogicalName); if (value != null) { if (value.Equals(toValue)) continue; entity.Attributes[to.LogicalName] = value; requests.Add(new UpdateRequest { Target = entity }); } else if (toValue != null) { entity.Attributes[to.LogicalName] = null; requests.Add(new UpdateRequest { Target = entity }); } } if (requests.Any()) { PerformUpdates(service, requests); } Trace("Data Migration Complete", count, total); }
/// <summary> /// Data is assumed to be there, so use TryDelete /// </summary> /// <param name="service"></param> protected virtual void CleanupDataPostInitialization(IOrganizationService service) { var totalWatch = new Stopwatch(); totalWatch.Start(); var requests = new OrganizationRequestCollection(); foreach (var id in EntityIds.Where(e => e.Key != "businessunit").SelectMany(entityType => entityType.Value)) { requests.Add(new DeleteRequest { Target = Entities[id] }); } if (requests.Any()) { var response = (ExecuteMultipleResponse)service.Execute( new ExecuteMultipleRequest() { Settings = new ExecuteMultipleSettings() { ContinueOnError = true, ReturnResponses = false }, Requests = requests, }); ThrowExceptionForFaults(response, requests); totalWatch.Stop(); Debug.WriteLine("Total Time to delete {0} entities of types {1} (ms): {2}", requests.Count, String.Join(", ", requests.Select(s => ((DeleteRequest)s).Target.LogicalName).Distinct()), totalWatch.ElapsedMilliseconds); } List<Guid> businessIds; if (!EntityIds.TryGetValue("businessunit", out businessIds)) { return; } foreach (var id in businessIds) { service.DeleteBusinessUnit(id); } }
private void UpdateAndPublishMultiple(CrmConnection connection, ProjectItem projectItem, Guid webResourceId) { try { ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; OrganizationRequestCollection requests = new OrganizationRequestCollection(); string publishXml = "<importexportxml><webresources>"; Entity webResource = new Entity("webresource") { Id = webResourceId }; string extension = Path.GetExtension(projectItem.FileNames[1]); string content = extension != null && (extension.ToUpper() != ".TS") ? File.ReadAllText(projectItem.FileNames[1]) : File.ReadAllText(Path.ChangeExtension(projectItem.FileNames[1], ".js")); webResource["content"] = EncodeString(content); UpdateRequest request = new UpdateRequest { Target = webResource }; requests.Add(request); publishXml += "<webresource>{" + webResource.Id + "}</webresource>"; publishXml += "</webresources></importexportxml>"; PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; requests.Add(pubRequest); emRequest.Requests = requests; using (OrganizationService orgService = new OrganizationService(connection)) { _dte.StatusBar.Text = "Updating & publishing web resource..."; _dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); ExecuteMultipleResponse emResponse = (ExecuteMultipleResponse)orgService.Execute(emRequest); bool wasError = false; foreach (var responseItem in emResponse.Responses) { if (responseItem.Fault == null) continue; _logger.WriteToOutputWindow( "Error Updating And Publishing Web Resources To CRM: " + responseItem.Fault.Message + Environment.NewLine + responseItem.Fault.TraceText, Logger.MessageType.Error); wasError = true; } if (wasError) MessageBox.Show("Error Updating And Publishing Web Resources To CRM. See the Output Window for additional details."); else _logger.WriteToOutputWindow("Updated And Published Web Resource", Logger.MessageType.Info); } } catch (FaultException<OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); } catch (Exception ex) { _logger.WriteToOutputWindow("Error Updating And Publishing Web Resource To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); } _dte.StatusBar.Clear(); _dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); }
internal static void AddToQueue(TraceLogger logger, CrmServiceClient service, string filepath) { const string SEPERATOR = "------------------------------------------------------"; logger.Log(SEPERATOR, TraceEventType.Information); logger.Log("Starting to queue items... this may take a while... ", TraceEventType.Information); if (!File.Exists(filepath)) { logger.Log(new FileNotFoundException($"Unable to locate queueitems.json at $filepath")); logger.Log(SEPERATOR, TraceEventType.Information); return; } var json = File.ReadAllText(filepath); if (string.IsNullOrWhiteSpace(json)) { logger.Log(new FileLoadException("Queueitems.json was empty.")); logger.Log(SEPERATOR, TraceEventType.Information); return; } try { dynamic data = JsonConvert.DeserializeObject(json); var requests = new OrganizationRequestCollection(); if (data == null) { logger.Log("Json data was null", TraceEventType.Information); logger.Log(SEPERATOR, TraceEventType.Information); return; } int i = 0, j = 0; foreach (var queueitem in data) { i++; if (i >= QUEUEITEMBATCHSIZE && i % QUEUEITEMBATCHSIZE == 0) { j++; } var request = new AddToQueueRequest(); if (Guid.TryParse(queueitem.queueid.ToString(), out Guid queueid)) { if (Guid.TryParse(queueitem.targetid.ToString(), out Guid targetid)) { if (!String.IsNullOrEmpty(queueitem.targetentity.ToString())) { try { request.Target = new EntityReference(queueitem.targetentity.ToString(), targetid); request.DestinationQueueId = queueid; request.QueueItemProperties = new Entity("queueitem"); requests.Add(request); if (requests.Count >= QUEUEITEMBATCHSIZE) { ExecuteMultipleRequests(logger, service, requests, j); } } catch (Exception ex) { logger.Log("Unable to queue current item."); logger.Log(ex); } } else { logger.Log($"Item {i} - There was an empty target entity in the queueitems.json", TraceEventType.Information); } } else { logger.Log($"Item {i} - Unable to parse targetid guid: {queueitem.targetid.ToString()}", TraceEventType.Information); } } else { logger.Log($"Item {i} - Unable to parse queueid guid: {queueitem.queueid.ToString()}", TraceEventType.Information); } } if (requests.Count > 0) { ExecuteMultipleRequests(logger, service, requests, j); } } catch (Exception ex) { logger.Log("Unable to queue items."); logger.Log(ex); } finally { logger.Log(SEPERATOR, TraceEventType.Information); } }
private void DoTransfer(bool useBulk = false, int bulkCount = 200) { if (sourceRecords == null || targetRecords == null) { return; } var recordCount = sourceRecords.Entities.Count; var missingCount = 0; var createCount = 0; var updateCount = 0; var deleteCount = 0; var skipCount = 0; var errorCount = 0; var totalTaskCount = sourceRecords.Entities.Count; var bulk = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = true } }; int processed = 0; // Delete the missing source records in the target environment if ((transfermode & TransferMode.Delete) == TransferMode.Delete) { var missing = targetRecords.Entities.Select(e => e.Id).Except(sourceRecords.Entities.Select(e => e.Id)).ToArray(); missingCount = missing.Length; totalTaskCount += missingCount; for (int i = 0; i < missingCount; i++) { if (worker.CancellationPending) { return; } processed++; var recordid = missing[i]; SetProgress(i / totalTaskCount, ""); SetStatusMessage("{0}/{1}: delete record", i + 1, missingCount); if ((transfermode & TransferMode.Preview) != TransferMode.Preview) { if (useBulk) { bulk.Requests.Add(new DeleteRequest { Target = new EntityReference(entity.LogicalName, recordid) }); } else { targetService.Delete(entity.LogicalName, recordid); } } else { var record = targetRecords.Entities.Where(e => e.Id.Equals(recordid)).FirstOrDefault(); var recordname = record.GetAttributeValue <string>(this.entity.PrimaryNameAttribute); var lvrecord = ToListViewItem(recordname, record, "DELETE"); PreviewList.Add(lvrecord); } if (useBulk) { if (bulk.Requests.Count % bulkCount == 0 || processed == missingCount) { var bulkResponse = (ExecuteMultipleResponse)targetService.Execute(bulk); // MscrmTools (26/11/2020): Should we need to handle potential exceptions? deleteCount += bulk.Requests.Count; bulk.Requests = new OrganizationRequestCollection(); } } else { deleteCount++; } } } // Transfer records processed = 0; for (int i = 0; i < recordCount; i++) { if (worker.CancellationPending) { return; } processed++; try { var record = sourceRecords.Entities[i]; var targetEntity = targetRecords.Entities.FirstOrDefault(e => e.Id.Equals(record.Id)); var recordexist = targetEntity != null; var name = entity.DisplayName.UserLocalizedLabel == null ? string.Empty : entity.DisplayName.UserLocalizedLabel.Label; SetProgress((i + missingCount) / totalTaskCount, "Transfering entity '{0}'...", name); // BC 22/11/2016: some attributes are auto added in the result query var recordname = record.GetAttributeValue <string>(this.entity.PrimaryNameAttribute); AddMissingAttributes(record); // BC 19/12/2017: null values are not retrieved var sourceStateAndStatus = RemoveStateAndStatus(record); RemoveUnwantedAttributes(record); if (recordexist && ((transfermode & TransferMode.Update) == TransferMode.Update)) { // Update existing record SetStatusMessage( useBulk ? "{0}/{1}: Adding record '{2}' for update" : "{0}/{1}: update record '{2}'", i + 1, recordCount, recordname); ApplyEntityCollectionMappings(record); ApplyMappings(record); if ((transfermode & TransferMode.Preview) != TransferMode.Preview) { if (useBulk) { var setStateRequest = GetSetState(record, sourceStateAndStatus, targetEntity); var requests = new OrganizationRequestCollection { new UpdateRequest { Target = record } }; if (setStateRequest != null) { requests.Add(setStateRequest); } bulk.Requests.Add(new ExecuteTransactionRequest { Requests = requests }); } else { targetService.Update(record); SetState(record, sourceStateAndStatus, targetEntity); } } else { PreviewList.Add(ToListViewItem(recordname, record, "UPDATE")); } if (!useBulk) { updateCount++; } } else if (!recordexist && ((transfermode & TransferMode.Create) == TransferMode.Create)) { // Create missing record SetStatusMessage( useBulk ? "{0}/{1}: Adding record '{2}' for create" : "{0}/{1}: create record '{2}'", i + 1, recordCount, recordname); ApplyEntityCollectionMappings(record); ApplyMappings(record); if ((transfermode & TransferMode.Preview) != TransferMode.Preview) { if (useBulk) { var setStateRequest = GetSetState(record, sourceStateAndStatus); var requests = new OrganizationRequestCollection { new CreateRequest { Target = record } }; if (setStateRequest != null) { requests.Add(setStateRequest); } bulk.Requests.Add(new ExecuteTransactionRequest { Requests = requests }); } else { targetService.Create(record); SetState(record, sourceStateAndStatus); } } else { PreviewList.Add(ToListViewItem(recordname, record, "CREATE")); } if (!useBulk) { createCount++; } } else { SetStatusMessage("{0}/{1}: skip record", i + 1, recordCount); skipCount++; } if (useBulk) { if (bulk.Requests.Count > 0 && bulk.Requests.Count % bulkCount == 0 || processed == recordCount) { SetStatusMessage($"Processing records {processed - bulk.Requests.Count} to {processed} of {recordCount}"); var bulkResponse = (ExecuteMultipleResponse)targetService.Execute(bulk); // MscrmTools (26/11/2020): Should we need to handle potential exceptions? var errorIndexes = new List <int>(); foreach (var response in bulkResponse.Responses) { if (response.Fault != null) { errorIndexes.Add(response.RequestIndex); this.Messages.Add(response.Fault.Message); errorCount++; } } for (var j = 0; j < bulk.Requests.Count; j++) { if (errorIndexes.Contains(j)) { continue; } if (bulk.Requests[j] is ExecuteTransactionRequest etr) { if (etr.Requests.First() is CreateRequest) { createCount++; } else { updateCount++; } } } bulk.Requests = new OrganizationRequestCollection(); } } } catch (System.ServiceModel.FaultException <OrganizationServiceFault> error) { this.Messages.Add(error.Message); errorCount++; } } if ((transfermode & TransferMode.Preview) != TransferMode.Preview) { SetStatusMessage("{0} created; {1} updated; {2} deleted; {3} skipped; {4} errors", createCount, updateCount, deleteCount, skipCount, errorCount); } else { SetStatusMessage("PREVIEW: {0} created; {1} updated; {2} deleted; {3} skipped; {4} errors", createCount, updateCount, deleteCount, skipCount, errorCount); } }
private void MenuItemCallback(object sender, EventArgs e) { var dte = (EnvDTE.DTE) this.ServiceProvider.GetService(typeof(EnvDTE.DTE)); dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); var activeDocument = dte.ActiveDocument; var solutionFullName = dte.Solution.FullName; var fInfo = new FileInfo(solutionFullName); var devKitCrmConfigFile = $"{fInfo.DirectoryName}\\PL.DynamicsCrm.DevKit.json"; dte.StatusBar.Text = "Read PL.DynamicsCrm.DevKit.json config"; var config = DevKitCrmConfigHelper.GetDevKitCrmConfig(dte); var defaultConnection = config.CrmConnections.Where(conn => conn.Name == config.DefaultCrmConnection).FirstOrDefault(); if (defaultConnection == null) { ShowError("Default Crm connection not found!"); goto CLEAR_STATUS; } if (string.IsNullOrEmpty(config.SolutionPrefix)) { ShowError("PL.DynamicsCrm.DevKit.json config not found SolutionPrefix data"); goto CLEAR_STATUS; } dte.StatusBar.Text = "Connecting ..."; var check = SharedGlobals.GetGlobal("CrmService", dte); if (check == null) { try { var uri = new Uri(defaultConnection.Url); var clientCredentials = new ClientCredentials(); clientCredentials.UserName.UserName = defaultConnection.UserName; clientCredentials.UserName.Password = defaultConnection.Password; check = new OrganizationServiceProxy(uri, null, clientCredentials, null); SharedGlobals.SetGlobal("CrmService", check, dte); } catch { ShowError("Connecting Fail!"); goto CLEAR_STATUS; } } var crmService = (OrganizationServiceProxy)SharedGlobals.GetGlobal("CrmService", dte); dte.StatusBar.Text = "Connected ..."; var fileName = activeDocument.FullName; var parts = fileName.Split("\\".ToCharArray()); var condition = string.Empty; for (var i = 1; i < parts.Length; i++) { var value = $"{config.SolutionPrefix}/{parts[i]}/"; for (var j = i + 1; j < parts.Length; j++) { value += $"{parts[j]}/"; } if (value.EndsWith("/")) { value = value.TrimEnd("/".ToCharArray()); } condition += $"<condition attribute='name' operator='ends-with' value='{value}'/>"; } var fetchXml = $@" <fetch> <entity name='webresource'> <attribute name='name' /> <filter type='or'> {condition} </filter> </entity> </fetch>"; var rows = crmService.RetrieveMultiple(new FetchExpression(fetchXml)); if (rows.Entities.Count == 0) { ShowError("Web resource not found!"); goto CLEAR_STATUS; } var webResourceId = rows.Entities[0].Id; try { ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; OrganizationRequestCollection requests = new OrganizationRequestCollection(); string publishXml = "<importexportxml><webresources>"; Entity webResource = new Entity("webresource") { Id = webResourceId }; string content = File.ReadAllText(fileName); webResource["content"] = EncodeString(content); UpdateRequest request = new UpdateRequest { Target = webResource }; requests.Add(request); publishXml += "<webresource>{" + webResource.Id + "}</webresource>"; publishXml += "</webresources></importexportxml>"; PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; requests.Add(pubRequest); emRequest.Requests = requests; dte.StatusBar.Text = "Updating & publishing web resource..."; ExecuteMultipleResponse emResponse = (ExecuteMultipleResponse)crmService.Execute(emRequest); bool wasError = false; foreach (var responseItem in emResponse.Responses) { if (responseItem.Fault == null) { continue; } wasError = true; } if (wasError) { ShowError("Error Updating And Publishing Web Resources To CRM. See the Output Window for additional details."); goto CLEAR_STATUS; } else { dte.StatusBar.Text = "Updated And Published Web Resource"; goto CLEAR_STATUS; } } catch (FaultException <OrganizationServiceFault> crmEx) { ShowError("Error Updating And Publishing Web Resource To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace); goto CLEAR_STATUS; } catch (Exception ex) { ShowError("Error Updating And Publishing Web Resource To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace); } CLEAR_STATUS: dte.StatusBar.Clear(); dte.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); }
private void UpdateWebResources(List <WebResourceItem> items) { //TODO: Handle CRM 2011 w/o execute multiple ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; OrganizationRequestCollection requests = new OrganizationRequestCollection(); string projectName = ((ComboBoxItem)Projects.SelectedItem).Content.ToString(); Project project = GetProjectByName(projectName); if (project == null) { return; } string publishXml = "<importexportxml><webresources>"; foreach (var webResourceItem in items) { Entity webResource = new Entity("webresource") { Id = webResourceItem.WebResourceId }; string filePath = Path.GetDirectoryName(project.FullName) + webResourceItem.BoundFile.Replace("/", "\\"); if (!File.Exists(filePath)) { continue; } string content = File.ReadAllText(filePath); webResource["content"] = EncodeString(content); UpdateRequest request = new UpdateRequest { Target = webResource }; requests.Add(request); publishXml += "<webresource>{" + webResource.Id + "}</webresource>"; } publishXml += "</webresources></importexportxml>"; PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; requests.Add(pubRequest); emRequest.Requests = requests; string connString = ((CrmConn)Connections.SelectedItem).ConnectionString; CrmConnection connection = CrmConnection.Parse(connString); using (OrganizationService orgService = new OrganizationService(connection)) { DisplayStatusMessage("Updating & publishing web resources"); ExecuteMultipleResponse emResponse = (ExecuteMultipleResponse)orgService.Execute(emRequest); foreach (var responseItem in emResponse.Responses) { if (responseItem.Fault == null) { continue; } //Some error - do something //TODO: handle error DisplayStatusMessage(String.Empty); return; } MessageBox.Show("Published");//change to status message that goes away itself DisplayStatusMessage(String.Empty); } }
internal static void Click(DTE dte) { try { dte.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); var config = UtilityPackage.IsValid(dte); if (config == null) { return; } UtilityPackage.SetDTEStatusBar(dte, " !!! Read DynamicsCrm.DevKit.Cli.json config !!! "); var check = UtilityPackage.GetGlobal("CrmService", dte); if (check == null) { var connection = UtilityPackage.IsConnection(config.CrmConnection); if (connection == null) { UtilityPackage.SetDTEStatusBar(dte, " !!! Connection Dynamics CRM failed !!! ", true); return; } UtilityPackage.SetGlobal("CrmService", connection, dte); } var crmService = (OrganizationServiceProxy)UtilityPackage.GetGlobal("CrmService", dte); UtilityPackage.SetDTEStatusBar(dte, " !!! Connected Dynamics CRM !!! "); var webResourceId = IsFoundWebResource(dte, crmService, config.JsonWebResource.prefix); if (webResourceId == Guid.Empty) { UtilityPackage.SetDTEStatusBar(dte, " !!! WebResource not found !!! ", true); return; } var requests = new OrganizationRequestCollection(); var webResource = new Entity("webresource") { Id = webResourceId }; var content = File.ReadAllText(dte.ActiveDocument.FullName); webResource["content"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(content)); var request = new UpdateRequest { Target = webResource }; requests.Add(request); var publishXml = $"<importexportxml><webresources><webresource>{webResource.Id}</webresource></webresources></importexportxml>"; var pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; requests.Add(pubRequest); var multipleRequest = new ExecuteMultipleRequest { Requests = requests, Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; UtilityPackage.SetDTEStatusBar(dte, " !!! Updating & publishing WebResource !!! "); var multipleResponse = (ExecuteMultipleResponse)crmService.Execute(multipleRequest); foreach (var response in multipleResponse.Responses) { if (response.Fault == null) { continue; } UtilityPackage.SetDTEStatusBar(dte, " !!! Deploy WebResource failed !!! ", true); return; } UtilityPackage.SetDTEStatusBar(dte, " !!! Deploy WebResource succeeded !!! ", true); } catch { UtilityPackage.SetDTEStatusBar(dte, " !!! Deploy WebResource failed !!! ", true); } }
private void UpdateWebResources(List<WebResourceItem> items) { //TODO: Handle CRM 2011 w/o execute multiple ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; OrganizationRequestCollection requests = new OrganizationRequestCollection(); string projectName = ((ComboBoxItem)Projects.SelectedItem).Content.ToString(); Project project = GetProjectByName(projectName); if (project == null) return; string publishXml = "<importexportxml><webresources>"; foreach (var webResourceItem in items) { Entity webResource = new Entity("webresource") { Id = webResourceItem.WebResourceId }; string filePath = Path.GetDirectoryName(project.FullName) + webResourceItem.BoundFile.Replace("/", "\\"); if (!File.Exists(filePath)) continue; string content = File.ReadAllText(filePath); webResource["content"] = EncodeString(content); UpdateRequest request = new UpdateRequest { Target = webResource }; requests.Add(request); publishXml += "<webresource>{" + webResource.Id + "}</webresource>"; } publishXml += "</webresources></importexportxml>"; PublishXmlRequest pubRequest = new PublishXmlRequest { ParameterXml = publishXml }; requests.Add(pubRequest); emRequest.Requests = requests; string connString = ((CrmConn)Connections.SelectedItem).ConnectionString; CrmConnection connection = CrmConnection.Parse(connString); using (OrganizationService orgService = new OrganizationService(connection)) { DisplayStatusMessage("Updating & publishing web resources"); ExecuteMultipleResponse emResponse = (ExecuteMultipleResponse)orgService.Execute(emRequest); foreach (var responseItem in emResponse.Responses) { if (responseItem.Fault == null) continue; //Some error - do something //TODO: handle error DisplayStatusMessage(String.Empty); return; } MessageBox.Show("Published");//change to status message that goes away itself DisplayStatusMessage(String.Empty); } }