コード例 #1
0
ファイル: DeploymentService.cs プロジェクト: aylosx/xrm-suite
        public void UpdateServiceEndpoint(string primaryKey, string namespaceAddress, string sharedAccessKey, string serviceNamespace)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (string.IsNullOrWhiteSpace(primaryKey))
            {
                throw new ArgumentNullException(nameof(primaryKey));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Primary key: {0}.", primaryKey);

            bool isValidGuid = Guid.TryParse(primaryKey, out Guid key);

            if (!isValidGuid)
            {
                throw new ArgumentException("Primary key argument is invalid.");
            }

            if (string.IsNullOrWhiteSpace(namespaceAddress))
            {
                throw new ArgumentNullException(nameof(namespaceAddress));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Namespace address: {0}.", namespaceAddress);

            if (string.IsNullOrWhiteSpace(sharedAccessKey))
            {
                throw new ArgumentNullException(nameof(sharedAccessKey));
            }

            if (string.IsNullOrWhiteSpace(serviceNamespace))
            {
                throw new ArgumentNullException(nameof(serviceNamespace));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Service namespace: {0}.", serviceNamespace);

            ServiceEndpoint serviceEndpoint = CrmService.GetServiceEndpoint(key);

            if (serviceEndpoint == null)
            {
                throw new EntityNotFoundException("Service endpoint not found.");
            }

            OrganizationServiceContext.ClearChanges();

            ServiceEndpoint se = new ServiceEndpoint
            {
                ServiceEndpointId       = serviceEndpoint.Id,
                ContentTypeOfTheMessage = ServiceEndpointMessageFormat.Json,
                NamespaceAddress        = namespaceAddress,
                //SASKey = sharedAccessKey, //TO-DO
                ServiceNamespace = serviceNamespace
            };

            OrganizationServiceContext.Attach(se);

            OrganizationServiceContext.UpdateObject(se);

            CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
コード例 #2
0
ファイル: SolutionService.cs プロジェクト: aylosx/xrm-suite
        public void UpdateSolutionVersion(string solutionName, string timeZone, string version)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (string.IsNullOrWhiteSpace(solutionName))
            {
                throw new ArgumentNullException(nameof(solutionName));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Solution name: {0}.", solutionName);

            if (string.IsNullOrWhiteSpace(timeZone))
            {
                throw new ArgumentNullException(nameof(timeZone));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Time zone: {0}.", timeZone);

            if (solutionName.ToUpperInvariant().Equals("DEFAULT"))
            {
                Logger.Warn(CultureInfo.InvariantCulture, "Version update of the default solution is not allowed.");
                Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
                return;
            }

            IList <Solution> solutions = CrmService.GetSolutions(solutionName);

            OrganizationServiceContext.ClearChanges();

            foreach (Solution solution in solutions)
            {
                Logger.Info(CultureInfo.InvariantCulture, "Processing solution '{0} {1}'.", solution.DisplayName, solution.Version);

                if (solution.PackageType.GetValueOrDefault())
                {
                    throw new PlatformException("Version update of managed solutions is not allowed.");
                }

                Solution updatedSolution = new Solution
                {
                    SolutionId = solution.Id,
                    Version    = string.IsNullOrWhiteSpace(version) ? CalculateVersion(timeZone) : version
                };

                OrganizationServiceContext.Attach(updatedSolution);
                OrganizationServiceContext.UpdateObject(updatedSolution);

                Logger.Info(CultureInfo.InvariantCulture, "Solution {0} version set to {1}.", solution.DisplayName, updatedSolution.Version);
            }

            if (OrganizationServiceContext.GetAttachedEntities().OfType <Solution>().Any())
            {
                CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);
            }

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
コード例 #3
0
ファイル: NumeratorClass.cs プロジェクト: pro100ham/SoftLine
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                var context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                var serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = serviceFactory.CreateOrganizationService(context.UserId);

                if (context.MessageName.ToLower() != "create")
                {
                    return;
                }

                using (var orgContext = new OrganizationServiceContext(service))
                {
                    var supp = (Entity)context.InputParameters["Target"];

                    if (supp.GetAttributeValue <EntityReference>("new_contractorder") == null ||
                        supp.GetAttributeValue <EntityReference>("new_contractorder").Id == null)
                    {
                        return;
                    }

                    var count = service.Retrieve("salesorder", supp.GetAttributeValue <EntityReference>("new_contractorder").Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(new[] { "new_agreemnumber" }));
                    if (count != null)
                    {
                        var number = count.GetAttributeValue <string>("new_agreemnumber") ?? "1";
                        supp["new_name"] = number;
                        orgContext.ClearChanges();
                        orgContext.Attach(supp);
                        orgContext.UpdateObject(supp);

                        Entity upOrder = new Entity();
                        upOrder.Id          = supp.GetAttributeValue <EntityReference>("new_contractorder").Id;
                        upOrder.LogicalName = supp.GetAttributeValue <EntityReference>("new_contractorder").LogicalName;
                        upOrder.Attributes.Add("new_agreemnumber", (Convert.ToInt32(number) + 1).ToString());

                        service.Update(upOrder);
                        orgContext.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
コード例 #4
0
        public static T AddOrGetExistingDocumentLocationAndSave <T>(this OrganizationServiceContext context, Entity sharePointSite, Entity entity, string relativeUrl)
            where T : Entity, new()
        {
            var location = context.AddOrGetExistingDocumentLocation <T>(sharePointSite, entity, relativeUrl);

            if (location.EntityState == EntityState.Created || location.EntityState == EntityState.Changed)
            {
                context.SaveChanges();

                // refresh the context and result entity

                context.ClearChanges();

                location = context.CreateQuery(_sharepointdocumentlocation).FirstOrDefault(loc => loc.GetAttributeValue <Guid>(_sharepointdocumentlocationid) == location.Id) as T;
            }

            return(location);
        }
コード例 #5
0
ファイル: NumeratorClass.cs プロジェクト: pro100ham/SoftLine
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                var serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                var service = serviceFactory.CreateOrganizationService(context.UserId);

                if (context.MessageName.ToLower() != "create")
                    return;

                using (var orgContext = new OrganizationServiceContext(service))
                {
                    var supp = (Entity)context.InputParameters["Target"];

                    if (supp.GetAttributeValue<EntityReference>("new_contractorder") == null ||
                        supp.GetAttributeValue<EntityReference>("new_contractorder").Id == null)
                        return;

                    var count = service.Retrieve("salesorder", supp.GetAttributeValue<EntityReference>("new_contractorder").Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(new[] { "new_agreemnumber" }));
                    if (count != null)
                    {
                        var number = count.GetAttributeValue<string>("new_agreemnumber") ?? "1";
                        supp["new_name"] = number;
                        orgContext.ClearChanges();
                        orgContext.Attach(supp);
                        orgContext.UpdateObject(supp);

                        Entity upOrder = new Entity();
                        upOrder.Id = supp.GetAttributeValue<EntityReference>("new_contractorder").Id;
                        upOrder.LogicalName = supp.GetAttributeValue<EntityReference>("new_contractorder").LogicalName;
                        upOrder.Attributes.Add("new_agreemnumber", (Convert.ToInt32(number) + 1).ToString());

                        service.Update(upOrder);
                        orgContext.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
コード例 #6
0
        private void UpdateOrganizationSettings(string replaceString, string blockedAttachments)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (string.IsNullOrWhiteSpace(blockedAttachments))
            {
                throw new ArgumentNullException(nameof(blockedAttachments));
            }

            Logger.Info(CultureInfo.InvariantCulture, "Updating blocked attachments.");

            Organization organizationSettings = CrmService.GetOrganizationSettings();

            if (organizationSettings == null)
            {
                throw new EntityNotFoundException("No organization record can be found in the system.");
            }

            OrganizationServiceContext.ClearChanges();

            Organization updatedOrganizationSettings = new Organization
            {
                Id = organizationSettings.Id,
                BlockAttachments = blockedAttachments.Replace(replaceString, string.Empty),
            };

            OrganizationServiceContext.Attach(updatedOrganizationSettings);

            OrganizationServiceContext.UpdateObject(updatedOrganizationSettings);

            CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);

            Thread.Sleep(60000);

            Logger.Info(CultureInfo.InvariantCulture, "Blocked attachments updated to: {0}.", updatedOrganizationSettings.BlockAttachments);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
コード例 #7
0
ファイル: DeploymentService.cs プロジェクト: aylosx/xrm-suite
        public void UpdateOrganizationSettings(Organization organization)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (organization == null)
            {
                throw new ArgumentNullException(nameof(organization));
            }

            Organization organizationSettings = CrmService.GetOrganizationSettings();

            if (organizationSettings == null)
            {
                throw new EntityNotFoundException("No organization record can be found in the system.");
            }

            OrganizationServiceContext.ClearChanges();

            //TO-DO: this is in experimental mode

            Organization updatedOrganizationSettings = new Organization
            {
                Id = organizationSettings.Id,
                //BlockAttachments = organization.BlockAttachments,
                OrganizationName = organization.OrganizationName
            };

            OrganizationServiceContext.Attach(updatedOrganizationSettings);

            OrganizationServiceContext.UpdateObject(updatedOrganizationSettings);

            CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);

            //Logger.Info(CultureInfo.InvariantCulture, "Blocked attachments updated to: {0}.", updatedOrganizationSettings.BlockAttachments);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
コード例 #8
0
ファイル: SolutionService.cs プロジェクト: aylosx/xrm-suite
        private void WaitForSystemJob(Guid systemJobId, int pollingInterval, int pollingTimeout, bool throwsException, int waitedFor = 0)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (Guid.Empty.Equals(systemJobId))
            {
                throw new ArgumentNullException(nameof(systemJobId));
            }
            if (pollingInterval < 1)
            {
                throw new PlatformException("Interval must be 1 second or more.");
            }
            pollingInterval *= 1000; pollingTimeout *= 1000; bool inProgress = true;

            while (inProgress)
            {
                try
                {
                    OrganizationServiceContext.ClearChanges();

                    SystemJob systemJob = CrmService.GetSystemJob(systemJobId);

                    if (systemJob == null)
                    {
                        throw new PlatformException("The requested job doesn't exist.");
                    }

                    switch (systemJob.StatusReason)
                    {
                    case SystemJobStatusReason.Succeeded:
                        inProgress = false;
                        break;

                    case SystemJobStatusReason.Canceling:
                    case SystemJobStatusReason.Canceled:
                    case SystemJobStatusReason.Failed:
                    case SystemJobStatusReason.Pausing:
                        if (throwsException)
                        {
                            throw new PlatformException(string.Format(CultureInfo.InvariantCulture, "The requested job failed. {0} {1}", systemJob.StatusReason, systemJob.Message));
                        }
                        inProgress = false;
                        break;
                    }
                }
                catch (MessageSecurityException ex)
                {
                    Logger.Warn(CultureInfo.InvariantCulture, "Oups ... a security exception occurred, we will try to reconnect.");
                    Logger.Warn(ex.Message);

                    Connection.SetOrganizationService();

                    OrganizationServiceContext.Dispose();
                    OrganizationServiceContext = new CrmServiceContext(Connection.OrganizationService);

                    CrmService.Dispose();
                    CrmService = new CrmService(OrganizationServiceContext, Connection);

                    WaitForSystemJob(systemJobId, pollingInterval / 1000, pollingTimeout / 1000, throwsException, waitedFor);
                    break;
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    if (ex.Detail != null && ex.Detail.ErrorCode == -2147020463)
                    {
                        Logger.Warn(CultureInfo.InvariantCulture, "Oups ... another solution is currently installing, we will retry in a minute.");
                        Logger.Warn(ex.Detail.Message);

                        Thread.Sleep(60000); WaitForSystemJob(systemJobId, pollingInterval, pollingTimeout, throwsException);
                    }
                    else
                    {
                        throw;
                    }
                }

                if (waitedFor > pollingTimeout)
                {
                    if (throwsException)
                    {
                        throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "The system job {0} timed out.", systemJobId));
                    }
                    inProgress = false;
                }

                Logger.Info(CultureInfo.InvariantCulture, "The system job is running for {0} seconds.", waitedFor / 1000);
                Thread.Sleep(pollingInterval); waitedFor += pollingInterval;
            }

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
コード例 #9
0
ファイル: SolutionService.cs プロジェクト: aylosx/xrm-suite
        private void WaitForImportJob(Guid importJobId, Guid systemJobId, int pollingInterval, int pollingTimeout, bool throwsException, int waitedFor = 0)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (Guid.Empty.Equals(systemJobId))
            {
                throw new ArgumentNullException(nameof(systemJobId));
            }
            if (pollingInterval < 1)
            {
                throw new PlatformException("Interval must be 1 second or more.");
            }
            pollingInterval *= 1000; pollingTimeout *= 1000; bool inProgress = true;

            while (inProgress)
            {
                try
                {
                    OrganizationServiceContext.ClearChanges();

                    SystemJob systemJob = CrmService.GetSystemJob(systemJobId);

                    if (systemJob == null)
                    {
                        throw new PlatformException("The requested job doesn't exist.");
                    }

                    switch (systemJob.StatusReason)
                    {
                    case SystemJobStatusReason.Succeeded:
                        inProgress = false;
                        break;

                    case SystemJobStatusReason.Canceling:
                    case SystemJobStatusReason.Canceled:
                    case SystemJobStatusReason.Failed:
                    case SystemJobStatusReason.Pausing:
                        if (throwsException)
                        {
                            throw new PlatformException(string.Format(CultureInfo.InvariantCulture, "The requested job failed. {0} {1}", systemJob.StatusReason, systemJob.Message));
                        }
                        inProgress = false;
                        break;
                    }

                    ImportJob importJob = CrmService.GetImportJob(importJobId);

                    if (importJob != null && importJob.Progress != null)
                    {
                        int progress = Convert.ToInt32(importJob.Progress.GetValueOrDefault(0));
                        Logger.Info(CultureInfo.InvariantCulture, "Importing solution ... progress: {0}%", progress);
                        if (progress >= 100)
                        {
                            if (!string.IsNullOrWhiteSpace(importJob.Data))
                            {
                                IEnumerable <ImportJobResult> importJobResults = ParseImportJobXmlData(importJob.Data);

                                int warningCount = 0; int errorCount = 0; int fatalErrorCount = 0;

                                foreach (ImportJobResult importJobResult in importJobResults)
                                {
                                    string name      = GetNameText(importJobResult);
                                    string processed = GetProcessedText(importJobResult);
                                    string result    = GetResultText(importJobResult);

                                    switch (importJobResult.Result)
                                    {
                                    case ImportJobStatus.Warning:
                                        Logger.Warn(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", importJobResult.ElementName, name, processed, result);
                                        warningCount++;
                                        break;

                                    case ImportJobStatus.Error:
                                        Logger.Error(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", importJobResult.ElementName, name, processed, result);
                                        if (importJobResult.ErrorCode != "0")
                                        {
                                            errorCount++;
                                        }
                                        break;

                                    case ImportJobStatus.Failure:
                                        Logger.Fatal(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", importJobResult.ElementName, name, processed, result);
                                        if (importJobResult.ErrorCode != "0")
                                        {
                                            fatalErrorCount++;
                                        }
                                        break;

                                    default:
                                        Logger.Info(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", importJobResult.ElementName, name, processed, result);
                                        break;
                                    }
                                }

                                if (errorCount > 0 || fatalErrorCount > 0)
                                {
                                    throw new PlatformException("One or more error(s) occurred whilst importing the solution.");
                                }
                            }

                            inProgress = false;
                        }
                    }
                }
                catch (MessageSecurityException ex)
                {
                    Logger.Warn(CultureInfo.InvariantCulture, "Oups ... a security exception occurred, we will try to reconnect.");
                    Logger.Warn(ex.Message);

                    Connection.SetOrganizationService();

                    OrganizationServiceContext.Dispose();
                    OrganizationServiceContext = new CrmServiceContext(Connection.OrganizationService);

                    CrmService.Dispose();
                    CrmService = new CrmService(OrganizationServiceContext, Connection);

                    WaitForImportJob(importJobId, systemJobId, pollingInterval / 1000, pollingTimeout / 1000, throwsException, waitedFor);
                    break;
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    if (ex.Detail != null && ex.Detail.ErrorCode == -2147020463)
                    {
                        Logger.Warn(CultureInfo.InvariantCulture, "Oups ... another solution is currently installing, we will retry in a minute.");
                        Logger.Warn(ex.Detail.Message);

                        Thread.Sleep(60000); WaitForImportJob(importJobId, systemJobId, pollingInterval, pollingTimeout, throwsException);
                    }
                    else
                    {
                        throw;
                    }
                }

                if (waitedFor > pollingTimeout)
                {
                    if (throwsException)
                    {
                        throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "The system job {0} timed out.", systemJobId));
                    }
                    inProgress = false;
                }

                Thread.Sleep(pollingInterval); waitedFor += pollingInterval;
            }

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
コード例 #10
0
        /// <summary>
        /// Clears the context and returns it. can be used as chaining method
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static OrganizationServiceContext Clear(this OrganizationServiceContext context)
        {
            context.ClearChanges();

            return(context);
        }
コード例 #11
0
        public void UpdateWebFiles(string inputPath, string websitePrimaryKey, string blockedAttachments)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException(nameof(inputPath));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Input path: {0}.", inputPath);

            if (!Directory.Exists(Path.GetDirectoryName(inputPath)))
            {
                throw new FileNotFoundException("The input file path does not exist.");
            }

            if (string.IsNullOrWhiteSpace(websitePrimaryKey))
            {
                throw new ArgumentNullException(nameof(websitePrimaryKey));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Web site primary key: {0}.", websitePrimaryKey);

            bool isValid = Guid.TryParse(websitePrimaryKey, out Guid websiteId);

            if (!isValid)
            {
                throw new ArgumentException("The web site primary key is not valid");
            }

            IList <FileInfo> files = new List <FileInfo>();

            EnumerateFiles(inputPath, files);

            UpdateOrganizationSettings("js;", blockedAttachments);

            IList <WebFile> webFiles = CrmService.GetWebsiteFiles(websiteId);

            OrganizationServiceContext.ClearChanges();

            foreach (FileInfo file in files)
            {
                Logger.Info(CultureInfo.InvariantCulture, "Processing file {0}.", file.FullName);
                WebFile webFile = webFiles.SingleOrDefault(x => x.Name.ToUpperInvariant().Equals(file.Name.ToUpperInvariant()));
                if (webFile == null)
                {
                    Logger.Warn(CultureInfo.InvariantCulture, "There is no portal web file entity for the file {0}.", file.Name);
                    continue;
                }

                Note annotation = CrmService.GetAnnotations(webFile.Id).OrderByDescending(x => x.CreatedOn).FirstOrDefault();

                if (annotation == null)
                {
                    Logger.Info(CultureInfo.InvariantCulture, "A new annotation {0} will be created.", file.Name);

                    annotation = new Note {
                        Document   = Convert.ToBase64String(File.ReadAllBytes(file.FullName)),
                        FileName   = file.Name,
                        IsDocument = true,
                        MimeType   = MimeMapping.GetMimeMapping(file.Name),
                        ObjectType = webFile.LogicalName,
                        Regarding  = new EntityReference(webFile.LogicalName, webFile.Id),
                    };

                    OrganizationServiceContext.AddObject(annotation);
                }
                else if (!annotation.Document.Equals(Convert.ToBase64String(File.ReadAllBytes(file.FullName))))
                {
                    Logger.Info(CultureInfo.InvariantCulture, "The annotation {0} will be updated.", file.Name);

                    annotation = new Note
                    {
                        AnnotationId = annotation.Id,
                        Document     = Convert.ToBase64String(File.ReadAllBytes(file.FullName))
                    };

                    OrganizationServiceContext.Attach(annotation);
                    OrganizationServiceContext.UpdateObject(annotation);
                }
            }

            CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);

            UpdateOrganizationSettings("nothing really", blockedAttachments);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
コード例 #12
0
        public void UpdateWebTemplates(string inputPath, string websitePrimaryKey)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException(nameof(inputPath));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Input path: {0}.", inputPath);

            if (!Directory.Exists(Path.GetDirectoryName(inputPath)))
            {
                throw new FileNotFoundException("The input file path does not exist.");
            }

            if (string.IsNullOrWhiteSpace(websitePrimaryKey))
            {
                throw new ArgumentNullException(nameof(websitePrimaryKey));
            }
            Logger.Info(CultureInfo.InvariantCulture, "Web site primary key: {0}.", websitePrimaryKey);

            bool isValid = Guid.TryParse(websitePrimaryKey, out Guid websiteId);

            if (!isValid)
            {
                throw new ArgumentException("The web site primary key is not valid");
            }

            IList <FileInfo> files = new List <FileInfo>();

            EnumerateFiles(inputPath, files);

            IList <WebTemplate> webTemplates = CrmService.GetWebTemplates(websiteId);

            OrganizationServiceContext.ClearChanges();

            foreach (FileInfo file in files)
            {
                Logger.Info(CultureInfo.InvariantCulture, "Processing file {0}.", file.FullName);

                string fileName = file.Name.ToUpperInvariant().Replace(".HTML", string.Empty);

                WebTemplate webTemplate = webTemplates.SingleOrDefault(x => x.Name.ToUpperInvariant().Equals(fileName));

                if (webTemplate == null)
                {
                    Logger.Warn(CultureInfo.InvariantCulture, "There is no portal web template entity for the file {0}.", file.Name);
                    continue;
                }

                string source = File.ReadAllText(file.FullName);
                if (source.Equals(webTemplate.Source))
                {
                    continue;
                }

                var updatedWebTemplate = new WebTemplate
                {
                    Id     = webTemplate.Id,
                    Source = source
                };

                OrganizationServiceContext.Attach(updatedWebTemplate);
                OrganizationServiceContext.UpdateObject(updatedWebTemplate);
            }

            CrmService.SaveChanges(OrganizationServiceContext, SaveChangesOptions.None);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }