Example #1
0
 public CrmImporter(IEnhancedOrgService service, CrmLog log, MigrationMetadataHelper metadataHelper)
 {
     this.service        = service;
     context             = new OrganizationServiceContext(service);
     this.log            = log;
     this.metadataHelper = metadataHelper;
 }
 protected JobRun(CustomJob job, EngineParams engineParams, IOrganizationService service, CrmLog log)
 {
     Job          = job;
     EngineParams = engineParams;
     Service      = service;
     this.log     = log;
 }
Example #3
0
 protected JobTarget(CustomJob job, IOrganizationService service, IOrganizationServiceFactory serviceFactory,
                     CrmLog log)
 {
     Job            = job;
     Service        = service;
     ServiceFactory = serviceFactory;
     this.log       = log;
 }
 internal RegistrationHelper(IOrganizationService service, CrmLog log)
 {
     this.service = service;
     this.log     = log;
     xrmContext   = new XrmServiceContext(service)
     {
         MergeOption = MergeOption.NoTracking
     };
 }
 internal Parser(IOrganizationService service, Entity entity, CrmLog log, Guid userIdForTimeZone, string orgId,
                 IDictionary <string, string> cachedValues)
 {
     this.log               = log;
     this.service           = service;
     this.entity            = entity;
     this.userIdForTimeZone = userIdForTimeZone;
     this.orgId             = orgId;
     this.cachedValues      = cachedValues;
 }
Example #6
0
        internal static JobRun GetJobRun(CustomJob job, bool isRetry, IOrganizationService service,
                                         IOrganizationServiceFactory factory, CrmLog log)
        {
            try
            {
                log.LogFunctionStart();

                if (IsRecurrent(job, log))
                {
                    return(new RecurrentRunJob(job, service, log));
                }

                log.Log("Single run job.");

                JobTarget target;

                if (IsSingleOrNoTarget(job, log))
                {
                    target = new SingleTargetJob(job, service, factory, log);
                }
                else if (IsPaging(job, log))
                {
                    if (isRetry)
                    {
                        target = new PagingRetryJob(job, service, factory, log);
                    }
                    else
                    {
                        target = new PagingNormalJob(job, service, factory, log);
                    }
                }
                else
                {
                    if (isRetry)
                    {
                        target = new NoPagingRetryJob(job, service, factory, log);
                    }
                    else
                    {
                        target = new NoPagingNormalJob(job, service, factory, log);
                    }
                }

                return(new SingleRunJob(job, target, service, log));
            }
            catch (Exception ex)
            {
                log.Log(ex);
                throw;
            }
            finally
            {
                log.LogFunctionEnd();
            }
        }
Example #7
0
        static void Main(string[] args)
        {
            var log = new CrmLog(true, LogLevel.Debug);

            log.InitOfflineLog("log.csv", false,
                               new FileConfiguration
            {
                FileSplitMode  = SplitMode.Size,
                MaxFileSize    = 1024,
                FileDateFormat = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss-fff}"
            });

            try
            {
                var settings = GetConfigurationParams(args);

                var service = ConnectToCrm(settings.ConnectionString, log);

                if (service == null)
                {
                    return;
                }

                foreach (var solutionConfig in settings.SolutionConfigs)
                {
                    try
                    {
                        var(solutionVersion, exportXml) = RetrieveSolution(solutionConfig.SolutionName, log, service);
                        var outputPath = string.IsNullOrWhiteSpace(solutionConfig.OutputPath)
                                                        ? settings.DefaultOutputPath
                                                        : solutionConfig.OutputPath;
                        var fullPath = BuildOutputPath(outputPath, solutionConfig.OutputFilename,
                                                       solutionConfig.SolutionName, solutionVersion);
                        Directory.CreateDirectory(outputPath);
                        log.Log($"Writing solution to '{fullPath}'...");
                        File.WriteAllBytes($"{fullPath}", exportXml);
                        log.Log($"Solution file written.");
                    }
                    catch (Exception e)
                    {
                        log.Log(e);
                    }
                }
            }
            catch (Exception e)
            {
                log.Log(e);
                log.ExecutionFailed();
            }
            finally
            {
                log.LogExecutionEnd();
            }
        }
Example #8
0
        static int Main(string[] args)
        {
            args.RequireCountAtLeast(2, "Command Line Arguments",
                                     "A JSON file name must be passed to the program as argument.");

            var logLevel = ConfigurationManager.AppSettings["LogLevel"];

            log = new CrmLog(true, (LogLevel)int.Parse(logLevel));
            log.InitOfflineLog("log.csv", false,
                               new FileConfiguration
            {
                FileSplitMode  = SplitMode.Size,
                MaxFileSize    = 1024,
                FileDateFormat = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss-fff}"
            });

            try
            {
                ParseCmdArgs(args);

                foreach (var config in configs)
                {
                    log.Log($"Parsing config file {config} ...");
                    var settings = GetConfigurationParams(config);
                    var result   = ProcessConfiguration(settings);
                    log.Log($"Finished parsing config file {config}.");

                    if (result > 0)
                    {
                        return(result);
                    }
                }

                return(0);
            }
            catch (Exception e)
            {
                log.Log(e);
                log.ExecutionFailed();
                return(1);
            }
            finally
            {
                log.LogExecutionEnd();

                if (isPauseOnExit)
                {
                    Console.WriteLine();
                    Console.WriteLine("Press any key to exit ...");
                    Console.ReadKey();
                }
            }
        }
        protected override void ExecuteLogic()
        {
            log1 = log;
            // get the triggering record
            ////var target = (Entity)context.InputParameters["Target"];
            ////var typedTarget = target.ToEntity<Entity>();

            ////LinkDev.Libraries.Common.CrmHelpers.LogAttributeValues(target.Attributes, target, log);
            log.Log("TEST!");

            Test(out var i);
            // plugin logic ...
        }
 internal AutoNumberingEngine(IOrganizationService service, CrmLog log,
                              AutoNumbering autoNumberConfig, Entity target, Entity image, string orgId,
                              IEnumerable <string> inputParams = null)
 {
     this.log              = log;
     this.service          = service;
     this.orgId            = orgId;
     this.autoNumberConfig = autoNumberConfig;
     isInlineConfig        = autoNumberConfig.Id == Guid.Empty;
     this.target           = target;
     this.image            = image;
     this.inputParams      = inputParams;
 }
Example #11
0
        private static bool IsRecurrent(CustomJob job, CrmLog log)
        {
            try
            {
                log.LogFunctionStart();

                var isRecurrent = job.RecurrentJob == true;
                log.Log($"{isRecurrent}");
                return(isRecurrent);
            }
            catch (Exception ex)
            {
                log.Log(ex);
                throw;
            }
            finally
            {
                log.LogFunctionEnd();
            }
        }
Example #12
0
        private static CrmServiceClient ConnectToCrm(string connectionString, CrmLog log)
        {
            log.Log($"Connecting to '{connectionString}' ...");
            var service = new CrmServiceClient(connectionString);

            if (!string.IsNullOrWhiteSpace(service.LastCrmError) || service.LastCrmException != null)
            {
                log.LogError($"Failed to connect => {service.LastCrmError}");

                if (service.LastCrmException != null)
                {
                    throw service.LastCrmException;
                }

                return(null);
            }

            log.Log($"Connected!");
            return(service);
        }
Example #13
0
        private static bool IsPaging(CustomJob job, CrmLog log)
        {
            try
            {
                log.LogFunctionStart();

                var isPaging = job.RecordsPerPage > 0;
                log.Log($"{isPaging}");
                return(isPaging);
            }
            catch (Exception ex)
            {
                log.Log(ex);
                throw;
            }
            finally
            {
                log.LogFunctionEnd();
            }
        }
Example #14
0
        private static bool IsSingleOrNoTarget(CustomJob job, CrmLog log)
        {
            try
            {
                log.LogFunctionStart();

                var isSingleOrNoTarget = string.IsNullOrWhiteSpace(job.TargetLogicalName) ||
                                         job.TargetID?.Split(',').Length <= 1;
                log.Log($"{isSingleOrNoTarget}");
                return(isSingleOrNoTarget);
            }
            catch (Exception ex)
            {
                log.Log(ex);
                throw;
            }
            finally
            {
                log.LogFunctionEnd();
            }
        }
Example #15
0
        /// <summary>
        /// Registers the type mappings with the Unity container.
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            container.RegisterType <CrmLog>(
                new InjectionFactory(
                    c =>
            {
                var crmLog = new CrmLog("C:\\Logs\\LinkDev.DataMigration.csv", LogLevel.Debug,
                                        new FileConfiguration
                {
                    FileDateFormat = "yyyy-MM-dd_HH-mm-ss-fff",
                    FileSplitMode  = SplitMode.Size,
                    MaxFileSize    = 10000
                }, "");
                crmLog.LogEntryAdded += (sender, args) => ProgressHub.PublishLog(
                    args.LogEntry.Message, args.LogEntry.StartDate?.ToLocalTime() ?? DateTime.Now,
                    args.LogEntry.Level, args.LogEntry.Information);
                return(crmLog);
            }));
            container.RegisterType <IEnhancedOrgService>(new InjectionFactory(c => CrmService.GetService()));
        }
Example #16
0
        private static bool IsSinglePage(CustomJob job, CrmLog log, IOrganizationService service)
        {
            if (string.IsNullOrWhiteSpace(job.TargetXML) || IsSingleOrNoTarget(job, log))
            {
                return(true);
            }

            log.Log("Converting FetchXML to QueryExpression ...", LogLevel.Debug);
            var query = ((FetchXmlToQueryExpressionResponse)
                         service.Execute(
                             new FetchXmlToQueryExpressionRequest
            {
                FetchXml = job.TargetXML
            })).Query;

            log.Log("Converted.", LogLevel.Debug);

            // we only need to check if there are more pages or not
            query.ColumnSet = new ColumnSet(false);

            query.PageInfo =
                new PagingInfo
            {
                Count        = job.RecordsPerPage ?? 5000,
                PageNumber   = job.PageNumber ?? 1,
                PagingCookie = job.PagingCookie
            };

            log.Log($"Retrieving a max of {query.PageInfo.Count} per page ...", LogLevel.Debug);
            log.Log($"Retrieving page {query.PageInfo.PageNumber} ...", LogLevel.Debug);
            var result = service.RetrieveMultiple(query);

            log.Log($"More records: {result.MoreRecords}.");

            return(result.MoreRecords);
        }
        private static StandardKernel CreateKernel()
        {
            var kernel = new StandardKernel();

            kernel.Bind <IEnhancedOrgService>().ToMethod(context => CrmService.GetService());
            kernel.Bind <CrmLog>().ToMethod(
                context =>
            {
                var crmLog = new CrmLog(
                    "C:\\Logs\\LinkDev.DataMigration.csv",
                    LogLevel.Debug,
                    new FileConfiguration
                {
                    FileDateFormat = "yyyy-MM-dd_HH-mm-ss-fff",
                    FileSplitMode  = SplitMode.Size,
                    MaxFileSize    = 10000
                });
                crmLog.LogEntryAdded += (sender, args) => ProgressHub.PublishLog(
                    args.LogEntry.Message, args.LogEntry.StartDate?.ToLocalTime() ?? DateTime.Now,
                    args.LogEntry.Level, args.LogEntry.Information);
                return(crmLog);
            });
            return(kernel);
        }
Example #18
0
 public RecurrentRunJob(CustomJob job, IOrganizationService service, CrmLog log) : base(job, service, log)
 {
 }
Example #19
0
 public RecurrentRunJob(CustomJob job, EngineParams engineParams, IOrganizationService service, CrmLog log)
     : base(job, engineParams, service, log)
 {
 }
 internal RoutingHelper(IOrganizationService service, CrmLog log)
 {
     this.service = service;
     this.log     = log;
 }
 protected JobRun(CustomJob job, IOrganizationService service, CrmLog log)
 {
     Job      = job;
     Service  = service;
     this.log = log;
 }
Example #22
0
        internal static AutoNumbering GetAutoNumberingConfig(Entity target, string config,
                                                             IPluginExecutionContext context, IOrganizationService service, CrmLog log, out bool isBackLogged)
        {
            var xrmContext = new XrmServiceContext(service)
            {
                MergeOption = MergeOption.NoTracking
            };

            var configIds      = config.Split(',').Select(item => item.Trim()).ToArray();
            var isInlineConfig = config.Contains(";;");

            AutoNumbering autoNumberConfig = null;

            if (isInlineConfig)
            {
                autoNumberConfig = GetInlineConfig(config, context.UserId);
            }

            // get it once to check for generator field update below
            log.Log("Getting auto-numbering config ...");

            // if a condition is found in any of the configs, then don't throw an error if none match
            // it simply means that the user wants the auto-numbering to work only if the condition is satisified
            // this is useful for multiple fields
            var isConditioned = false;

            // if using a backlog, then no need to lock
            isBackLogged = false;

            if (!isInlineConfig)
            {
                var autoNumberConfigTemp = GetBackloggedConfig(context, service, log);

                if (autoNumberConfigTemp == null)
                {
                    foreach (var configId in configIds)
                    {
                        autoNumberConfigTemp =
                            (from autoNumberQ in xrmContext.AutoNumberingSet
                             where autoNumberQ.UniqueID == configId || autoNumberQ.Name == configId &&
                             autoNumberQ.Status == AutoNumbering.StatusEnum.Active
                             select autoNumberQ).FirstOrDefault();

                        if (autoNumberConfigTemp == null)
                        {
                            continue;
                        }

                        if (autoNumberConfigTemp.Condition != null)
                        {
                            isConditioned = true;
                            log.Log($"Checking condition for '{autoNumberConfigTemp.Name}':'{autoNumberConfigTemp.Id}' ...");
                            var parsedCondition = ParseAttributeVariables(service, autoNumberConfigTemp.Condition, target,
                                                                          context.UserId, context.OrganizationId.ToString());
                            var isConditionMet = IsConditionMet(service, parsedCondition,
                                                                target.ToEntityReference(), context.OrganizationId.ToString());

                            if (isConditionMet)
                            {
                                log.Log("Condition met for auto-numbering record.");
                                autoNumberConfig = autoNumberConfigTemp;
                                break;
                            }

                            log.Log("Condition not met for auto-numbering record.");
                        }
                        else if (autoNumberConfig == null)
                        {
                            autoNumberConfig = autoNumberConfigTemp;
                        }
                    }
                }
                else
                {
                    autoNumberConfig = autoNumberConfigTemp;
                    isBackLogged     = true;
                }
            }

            return(PreValidation(service, target, autoNumberConfig, log, isConditioned, isBackLogged));
        }
        public static void UpdateRetryTargetDate(IOrganizationService service, CustomJob job, CrmLog log)
        {
            DateTime?nextRecurrence;

            if (job.RetrySchedule == null)
            {
                log.Log("No retry schedule.");
                nextRecurrence = DateTime.UtcNow.AddMinutes(1);
            }
            else
            {
                log.Log($"Getting next retry occurrence for {job.RetrySchedule}.", LogLevel.Debug);
                var action = new GlobalActions.ldv_CustomJobGetNextRecurrenceDate(
                    new EntityReference(RecurrenceRule.EntityLogicalName, job.RetrySchedule.Value), service);
                nextRecurrence = action.Execute().NextTargetDate;
                log.Log($"Next retry occurrence: '{nextRecurrence}'.");
            }

            var targetDate = nextRecurrence > new DateTime(1900) ? nextRecurrence : null;

            log.Log($"Updating target date to '{targetDate}' UTC ...", LogLevel.Debug);
            service.Update(
                new CustomJob
            {
                Id         = job.Id,
                TargetDate = targetDate
            });
            log.Log($"Updated target date to '{targetDate}' UTC");
        }
Example #24
0
 public PagingNormalJob(CustomJob job, IOrganizationService service, IOrganizationServiceFactory serviceFactory,
                        CrmLog log) : base(job, service, serviceFactory, log)
 {
 }
Example #25
0
 protected NoPagingJob(CustomJob job, EngineParams engineParams, IOrganizationService service, CrmLog log)
     : base(job, engineParams, service, log)
 {
 }
 public SingleRunJob(CustomJob job, JobTarget target, IOrganizationService service, CrmLog log)
     : base(job, service, log)
 {
     JobTarget = target;
 }
 protected MultiTargetJob(CustomJob job, EngineParams engineParams, IOrganizationService service, CrmLog log)
     : base(job, engineParams, service, log)
 {
 }
 public NoPagingRetryJob(CustomJob job, EngineParams engineParams, IOrganizationService service, CrmLog log)
     : base(job, engineParams, service, log)
 {
 }
 public SingleTargetJob(CustomJob job, IOrganizationService service, IOrganizationServiceFactory factory,
                        CrmLog log) : base(job, service, factory, log)
 {
 }
Example #30
0
        internal static AutoNumbering PreValidation(IOrganizationService service, Entity target,
                                                    AutoNumbering autoNumberingConfig, CrmLog log, bool isConditioned, bool isBackLogged)
        {
            if (autoNumberingConfig == null)
            {
                // condition satisfaction failed before, so there's nothing to do here
                if (isConditioned)
                {
                    return(null);
                }

                throw new InvalidPluginExecutionException("Couldn't find an auto-numbering configuration.");
            }

            // if the auto-numbering is inactive, then don't apply
            if (autoNumberingConfig.Status == AutoNumbering.StatusEnum.Inactive)
            {
                //throw new InvalidPluginExecutionException("Autonumbering config record is inactive.");
                log.Log("AutoNumbering record is inactive.");
                return(null);
            }

            // exit if auto-number field is updating to prevent looping
            if (target != null && autoNumberingConfig.FieldLogicalName != null &&
                target.Contains(autoNumberingConfig.FieldLogicalName))
            {
                log.Log("Numbering is in progress in another instance.");
                return(null);
            }

            if (autoNumberingConfig.Id == Guid.Empty)
            {
                log.Log("Using inline config.");
                return(autoNumberingConfig);
            }

            if (autoNumberingConfig.Condition != null &&
                autoNumberingConfig.EntityLogicalName_ldv_EntityLogicalName == null)
            {
                throw new InvalidPluginExecutionException("Condition is set but entity name is not set in auto-numbering config.");
            }

            // only lock if an index is needed
            if (autoNumberingConfig.FormatString.Contains("{!index!}") && !isBackLogged)
            {
                log.Log("Locking ...", LogLevel.Debug);

                // ensure locking
                service.Update(
                    new AutoNumbering
                {
                    Id      = autoNumberingConfig.Id,
                    Locking = new Random().Next(999999, 999999999).ToString()
                });

                log.Log("Refetching numbering record ...", LogLevel.Debug);

                // get it again to ensure locking took effect
                var currentIndex =
                    (from autoNumberQ in new XrmServiceContext(service).AutoNumberingSet
                     where autoNumberQ.AutoNumberingId == autoNumberingConfig.Id &&
                     autoNumberQ.Status == AutoNumbering.StatusEnum.Active
                     select autoNumberQ.CurrentIndex).First();

                autoNumberingConfig.CurrentIndex = currentIndex;
            }

            return(autoNumberingConfig);
        }