コード例 #1
0
        public object ExecuteCommand(string guid, string command, string stringFormat)
        {
            var serializer = new JavaScriptSerializer();
            var output     = new StringBuilder();

            if (!IsLoggedInUserAuthorized ||
                !SessionElevationManager.IsSessionTokenElevated(ApplicationNames.Console))
            {
                return(serializer.Serialize(
                           new
                {
                    status = StatusElevationRequired,
                    result =
                        "You need to be authenticated, elevated and have sufficient privileges to use the PowerShell console. Please (re)login to Sitecore.",
                    prompt = "PS >",
                    background = OutputLine.ProcessHtmlColor(ConsoleColor.DarkBlue)
                }));
            }

            PowerShellLog.Info($"Arbitrary script execution in Console session '{guid}' by user: '******'");

            var session = GetScriptSession(guid);

            session.Interactive = true;
            session.SetItemContextFromLocation();
            try
            {
                var handle     = ID.NewID.ToString();
                var jobOptions = new JobOptions(GetJobId(guid, handle), "PowerShell", "shell", this, nameof(RunJob),
                                                new object[] { session, command })
                {
                    AfterLife      = new TimeSpan(0, 0, 20),
                    ContextUser    = Sitecore.Context.User,
                    EnableSecurity = true,
                    ClientLanguage = Sitecore.Context.ContentLanguage
                };
                JobManager.Start(jobOptions);
                Thread.Sleep(WebServiceSettings.CommandWaitMillis);
                return(PollCommandOutput(guid, handle, stringFormat));
            }
            catch (Exception ex)
            {
                return
                    (serializer.Serialize(
                         new Result
                {
                    status = StatusError,
                    result =
                        output +
                        ScriptSession.GetExceptionString(ex, ScriptSession.ExceptionStringFormat.Console) +
                        "\r\n" +
                        "\r\n[[;#f00;#000]Uh oh, looks like the command you ran is invalid or something else went wrong. Is it something we should know about?]\r\n" +
                        "[[;#f00;#000]Please submit a support ticket here https://git.io/spe with error details, screenshots, and anything else that might help.]\r\n\r\n" +
                        "[[;#f00;#000]We also have a user guide here http://doc.sitecorepowershell.com/.]\r\n\r\n",
                    prompt = $"PS {session.CurrentLocation}>",
                    background = OutputLine.ProcessHtmlColor(session.PrivateData.BackgroundColor),
                    color = OutputLine.ProcessHtmlColor(session.PrivateData.ForegroundColor)
                }));
            }
        }
コード例 #2
0
        public void ExecuteSync(string title, Action <ClientPipelineArgs> action, Action <ClientPipelineArgs> postAction)
        {
            if (!(Context.ClientPage.CurrentPipelineArgs is ClientPipelineArgs args))
            {
                return;
            }

            if (args.IsPostBack && !string.IsNullOrEmpty(handleString))
            {
                postAction?.Invoke(args);
                handleString = null;
                return;
            }

            var jobOption = new JobOptions(title, "UI", Client.Site.Name, action.Target, action.Method.Name, new object[] { args })
            {
                ContextUser    = Context.User,
                ClientLanguage = Context.Language
            };

            var job = JobManager.Start(jobOption);
            var longRunningOption = new LongRunningOptions(job.Handle.ToString())
            {
                Title = title,
                Icon  = string.Empty
            };

            handleString = job.Handle.ToString();

            longRunningOption.ShowModal(true);
            args.WaitForPostBack();
        }
コード例 #3
0
        protected void ImportTranslation()
        {
            List <string> languages = this.GetClientLanguages();

            foreach (string filePath in this.GetTranslationFiles())
            {
                foreach (string db in new [] { "core", "master" })
                {
                    JobOptions options = new JobOptions("ImportLanguage", "ImportLanguage", "shell", new ImportLanguageForm.Importer(db, filePath, languages), "Import")
                    {
                        ContextUser = Context.User
                    };
                    Job job = JobManager.Start(options);
                    job.Wait();
                }
                try
                {
                    File.Delete(filePath);
                }
                catch (Exception ex)
                {
                    LogHelper.Error("Error during removing processed translation file", this, ex);
                }
            }
        }
        public ActionResult AnalyzeAll(string id, string language, string database, bool overwrite)
        {
            if (!IsSitecoreUser())
            {
                return(LoginPage());
            }

            Item item = DataWrapper.GetItemByIdValue(id, database);

            if (item == null)
            {
                return(ViewAnalyzeAll(id, language, database));
            }

            string handleName = $"BatchImageAnalysis{new Random(DateTime.Now.Millisecond).Next(0, 100)}";

            var jobOptions = new JobOptions(
                handleName,
                "Cognitive Image Analysis",
                Sitecore.Context.Site.Name,
                AnalysisService,
                "AnalyzeImagesRecursively",
                new object[] { item, database, overwrite });

            JobManager.Start(jobOptions);

            var result = AnalyzeAllFactory.Create(id, database, language, handleName);

            return(Json(result));
        }
コード例 #5
0
		public static Handle ImportUsers(string userSheetItemId, string database, bool downloadFile, bool ignoreDate)
		{
			UserImportStatus importStatus = new UserImportStatus();
			UserImportOptions options = new UserImportOptions()
			{
				CsvSheetItemId = userSheetItemId,
				Database = database,
				DownloadLatestFile = downloadFile, 
				IgnoreFileDate = ignoreDate
			};
			JobOptions options1 = new JobOptions("ImportCsvUsers", "UserImportManager", "shell", (object)new UserImportManager(), "DoImport", new object[2]
      {
        (object) options,
        (object) importStatus
      });
			options1.ContextUser = Context.User;
			options1.ClientLanguage = Context.Language;
			options1.AfterLife = TimeSpan.FromMilliseconds(1000);
			options1.Priority = ThreadPriority.Normal;
			options1.ExecuteInManagedThreadPool = true;
			importStatus.State = JobState.Queued;
			Job job = JobManager.Start(options1);
			job.Options.CustomData = (object)importStatus;
			return job.Handle;
		}
コード例 #6
0
        protected virtual IDisposable RegisterJobExecutor(JobOptions jobOptions)
        {
            var jobExecutorType = _defaultJobExecutorType.MakeGenericType(jobOptions.ExecutorType);
            var jobExecutor     = (IJobExecutor)_services.GetRequiredService(jobExecutorType);

            return(Connection.On(jobOptions.JobInfo.MethodName, jobExecutor.ExecuteJobAsync));
        }
コード例 #7
0
        public static void StartJob(
            [NotNull] string jobName,
            [NotNull] string category,
            [NotNull] string siteName,
            [NotNull] object obj,
            [NotNull] string methodName,
            [CanBeNull] object[] parameters,
            [CanBeNull] User contextUser)
        {
            Assert.ArgumentNotNullOrEmpty(jobName, "jobName");
            Assert.ArgumentNotNullOrEmpty(category, "category");
            Assert.ArgumentNotNullOrEmpty(siteName, "siteName");
            Assert.ArgumentNotNull(obj, "obj");
            Assert.ArgumentNotNullOrEmpty(methodName, "methodName");

            var options = new JobOptions(jobName, category, siteName, obj, methodName, parameters)
            {
                ContextUser = contextUser
            };

            lock (LockObj)
            {
                if (JobManager.IsJobRunning(jobName) || JobManager.IsJobQueued(jobName))
                {
                    return;
                }

                JobManager.Start(options);
            }
        }
コード例 #8
0
 public FinalizeJobConsumer(IJobService jobService, JobOptions <TJob> options, Guid jobTypeId, string jobConsumerTypeName)
 {
     _jobService          = jobService;
     _options             = options;
     _jobTypeId           = jobTypeId;
     _jobConsumerTypeName = jobConsumerTypeName;
 }
コード例 #9
0
        public void Run(ID batchItemId, IPlugin[] plugins)
        {
            var batchItem = Sitecore.Configuration.Factory.GetDatabase("master")
                            .GetItem(batchItemId);


            if (PipelineBatchRunner == null || batchItem == null || !Helper.IsPipelineBatchItem(batchItem))
            {
                return;
            }

            var pipelineBatch = Helper.GetPipelineBatch(batchItem);

            if (pipelineBatch == null)
            {
                return;
            }

            var pipelineBatchRunner = (InProcessPipelineBatchRunner)PipelineBatchRunner;

            if (pipelineBatchRunner != null && (!pipelineBatchRunner.IsRunningRemotely(pipelineBatch) || !PipelineBatchRunner.IsRunning(pipelineBatch.Identifier)))
            {
                const string category = "Data Exchange";

                var parameters = new object[]
                {
                    pipelineBatch,
                    GetRunAsUser(),
                    plugins
                };

                var options = new JobOptions(batchItem.Name, category, "Data Exchange Framework", this, "RunPipelineBatch", parameters);
                PipelineBatchRunner.CurrentProcesses[pipelineBatch.Identifier] = JobManager.Start(options);
            }
        }
コード例 #10
0
        private string RebuildIndex(string indexName)
        {
            SearchIndexResolver resolver = new SearchIndexResolver();
            IIndex index = resolver.GetIndex(indexName);

            if (index == null)
            {
                ContentSearchResolver contentSearchResolver = new ContentSearchResolver();
                index = contentSearchResolver.GetIndex(indexName);
                if (index == null)
                {
                    throw new InvalidOperationException("unknown index");
                }
            }

            string jobId = Guid.NewGuid().ToString();

            RebuildIndexJob indexJob = new RebuildIndexJob(index);
            JobOptions      option   = new JobOptions(jobId, "Index rebuild", Sitecore.Context.Site.Name, indexJob, "Start")
            {
                AfterLife = TimeSpan.FromHours(1)
            };

            JobManager.Start(option);
            return(jobId);
        }
コード例 #11
0
        /// <summary>
        /// 添加调度任务的依赖注入。通过配置文件配置任务信息。
        /// </summary>
        /// <param name="serviceBuilder">调度服务构建者<seealso cref="ScheduleServiceBuilder"/></param>
        /// <param name="jobName">调度任务选项对应的任务名称。任务名称必须唯一。不同的调度任务需要以该名称做区分</param>
        /// <param name="configuration">配置调度任务信息的<see cref="IConfiguration"/></param>
        /// <typeparam name="T">调度任务对应的类型参数<seealso cref="IJobExecutor"/></typeparam>
        /// <returns>调度服务构建者</returns>
        /// <exception cref="ArgumentNullException">任务名称为空</exception>
        public static ScheduleServiceBuilder AddScheduleJob <T>(this ScheduleServiceBuilder serviceBuilder, string jobName, IConfiguration configuration)
            where T : class, IJobExecutor
        {
            if (jobName == null)
            {
                throw new ArgumentNullException(nameof(jobName));
            }

            var services = serviceBuilder.Services;

            services.AddOptions <JobInfo <T> >(jobName).Bind(configuration).ValidateDataAnnotations();
            services.TryAddScoped <T>();
            services.TryAddSingleton <IJobExecutor <T>, DefaultJobExecutor <T> >();

            var scheduleOptionsBuilder = serviceBuilder.ScheduleOptionsBuilder;

            scheduleOptionsBuilder.PostConfigure <IOptionsMonitor <JobInfo <T> > >((options, jobInfoOptions) =>
            {
                var jobInfo    = jobInfoOptions.Get(jobName);
                var jobOptions = new JobOptions()
                {
                    ExecutorType = typeof(T),
                    Name         = jobName,
                    JobInfo      = jobInfo
                };
                options.JobOptionsMap[jobName] = jobOptions;
            });
            return(serviceBuilder);
        }
コード例 #12
0
        protected virtual void RunAction(Action <Item, string> scopeAction, Item accountItem, string scope, Tuple <ID, string> jobName)
        {
            var options = new JobOptions(
                string.Format("MediaFramework_ScopeAction_{0}_{1}", accountItem.ID, scope),
                "MediaFramework",
                Context.Site.Name,
                this,
                "Run",
                new object[] { scopeAction, accountItem, scope })
            {
                Priority       = ThreadPriority.Normal,
                ContextUser    = Context.User,
                ClientLanguage = Context.Language,
                EnableSecurity = true,
                CustomData     = Context.Job,
                WriteToLog     = false
            };

            var job = JobManager.Start(options);

            LogHelper.Debug(string.Format("Scope job({0}) has been started", job.Name), this);

            this.ScopeJobs.TryAdd(jobName, job.Handle);

            job.Wait();
        }
コード例 #13
0
 public void StartAsync()
 {
     string jobCategory = typeof(ReferenceReplacementJob).Name;
     string siteName = Context.Site == null ? "No Site Context" : Context.Site.Name;
     JobOptions jobOptions = new JobOptions(GetJobName(), jobCategory, siteName, this, "Start");
     JobManager.Start(jobOptions);
 }
コード例 #14
0
        public static Job CreateJob(ItemReference[] elements, bool convertToBlob)
        {
            MigrationWorker worker  = new MigrationWorker(elements, convertToBlob);
            JobOptions      options = new JobOptions("MediaMigration", "MediaMigration", "shell", worker, "ThreadEntry");

            return(new Job(options));
        }
コード例 #15
0
        public override void Execute(CommandContext context)
        {
            Assert.ArgumentNotNull(context, "context");
            Assert.ArgumentNotNull(context.Items, "context.Items");

            if (context.Items.Length <= 0 || context.Items[0] == null)
            {
                return;
            }

            if (MigrationManager.Providers[context.Parameters["provider"]] == null)
            {
                SheerResponse.Alert(Translations.MigrationProviderIsNotDefined);
                return;
            }

            var jobOptions = new JobOptions("Migrate Content", "UI", Client.Site.Name, this, "Run", new object[] { context })
            {
                Priority       = ThreadPriority.Normal,
                ContextUser    = Context.User,
                ClientLanguage = Context.Language,
                EnableSecurity = true
            };

            var longRunningOptions = new LongRunningOptions(JobManager.Start(jobOptions).Handle.ToString())
            {
                Title     = "Migrate Content",
                Icon      = this.GetIcon(context, string.Empty),
                Threshold = 200,
                Message   = string.Empty
            };

            longRunningOptions.ShowModal();
        }
コード例 #16
0
        protected override void StartJob(JobInfo info, JobSegment segment)
        {
            var options = new JobOptions("ExperienceGenerator-" + info.Id + "/" + segment.Id, "ExperienceGenerator", Context.Site.Name, this, "Run",
                                         new object[] { segment });

            JobManager.Start(options);
        }
コード例 #17
0
        protected override async Task OnInitializedAsync()
        {
            uid       = await((OBAuthenticationStateProvider)Auth).GetCurrentUserId();
            jobEntity = await JobRepo.Get(JobId);

            jobOptions = JsonConvert.DeserializeObject <JobOptionsWrapper>(jobEntity.JobOptions, settings).Options;
        }
コード例 #18
0
 public StartJobConsumer(IJobService jobService, JobOptions <TJob> options, Guid jobTypeId, IPipe <ConsumeContext <TJob> > jobPipe)
 {
     _jobService = jobService;
     _options    = options;
     _jobTypeId  = jobTypeId;
     _jobPipe    = jobPipe;
 }
コード例 #19
0
        public void RunVirtualBatch(string formId, IPlugin[] plugins)
        {
            var virtualBatches = FormProcessingVirtualPipelineBatchBuilder.GetVirtualPipelineBatches(formId);

            if (virtualBatches == null)
            {
                return;
            }

            var pipelineBatchRunner = (InProcessPipelineBatchRunner)PipelineBatchRunner;

            foreach (var virtualBatch in virtualBatches)
            {
                if (pipelineBatchRunner != null && (!pipelineBatchRunner.IsRunningRemotely(virtualBatch) || !PipelineBatchRunner.IsRunning(virtualBatch.Identifier)))
                {
                    const string category = "Data Exchange";

                    var parameters = new object[]
                    {
                        virtualBatch,
                        GetRunAsUser(),
                        plugins
                    };

                    var options = new JobOptions(virtualBatch.Name, category, "Data Exchange Framework", this, "RunPipelineBatch", parameters);
                    PipelineBatchRunner.CurrentProcesses[virtualBatch.Identifier] = JobManager.Start(options);
                }
            }
        }
コード例 #20
0
        /// <summary>
        /// Starts Building Indexes
        /// </summary>
        protected void StartRebuilding()
        {
            var str  = new ListString();
            var str2 = new ListString(this.IndexMap);

            foreach (string str3 in Context.ClientPage.ClientRequest.Form.Keys)
            {
                if (!string.IsNullOrEmpty(str3) && str3.StartsWith("dk_"))
                {
                    int index = str2.IndexOf(str3);
                    if (index >= 0)
                    {
                        str.Add(str2[index + 1]);
                    }
                }
            }

            Registry.SetString("/Current_User/Rebuild Search Index/Selected", str.ToString());


            var options2 = new JobOptions("RebuildSearchIndex", "index", Client.Site.Name,
                                          new Builder(str.ToString()), "Build")
            {
                AfterLife   = TimeSpan.FromMinutes(1.0),
                ContextUser = Context.User
            };
            var options = options2;
            var job     = JobManager.Start(options);

            Context.ClientPage.ServerProperties["handle"] = job.Handle.ToString();
            Context.ClientPage.ClientResponse.Timer("CheckStatus", 500);
        }
コード例 #21
0
        ConnectHandle ConnectStartJobConsumer(IConsumePipeConnector consumePipe, IConsumerSpecification <StartJobConsumer <TJob> > specification,
                                              JobOptions <TJob> options, IJobService jobService, IPipe <ConsumeContext <TJob> > pipe)
        {
            var consumerFactory = new DelegateConsumerFactory <StartJobConsumer <TJob> >(() => new StartJobConsumer <TJob>(jobService, options, pipe));

            return(_startJobConsumerConnector.ConnectConsumer(consumePipe, consumerFactory, specification));
        }
コード例 #22
0
        public string StartJob(Item root)
        {
            JobOptions options = new JobOptions(_JobName, "Serialiaze", Context.Site.Name, this, "SerilizeItems", new object[] { root });

            JobManager.Start(options);
            return(_JobName);
        }
コード例 #23
0
        /// <summary>
        /// Starts the rebuilding.
        /// </summary>
        protected virtual void StartRebuilding()
        {
            ListString databases = new ListString();
            ListString indexMap  = new ListString(this.IndexMap);

            foreach (string formKey in Sitecore.Context.ClientPage.ClientRequest.Form.Keys)
            {
                if (!string.IsNullOrEmpty(formKey) && formKey.StartsWith("dk_"))
                {
                    int index = indexMap.IndexOf(formKey);
                    if (index >= 0)
                    {
                        databases.Add(indexMap[index + 1]);
                    }
                }
            }

            Registry.SetString("/Current_User/Rebuild Search Index/Selected", databases.ToString());
            JobOptions options = new JobOptions("RebuildSearchIndex", "index", Client.Site.Name, new Builder(databases.ToString()), "Build")
            {
                AfterLife   = TimeSpan.FromMinutes(1.0),
                ContextUser = Sitecore.Context.User
            };
            Job job = JobManager.Start(options);

            Sitecore.Context.ClientPage.ServerProperties["handle"] = job.Handle.ToString();
            Sitecore.Context.ClientPage.ClientResponse.Timer("CheckStatus", 500);
        }
コード例 #24
0
ファイル: BackgroundJobWorker.cs プロジェクト: zredb/abp
        protected override void DoWork()
        {
            using (var scope = ServiceScopeFactory.CreateScope())
            {
                var store = scope.ServiceProvider.GetRequiredService <IBackgroundJobStore>();

                var waitingJobs = store.GetWaitingJobs(WorkerOptions.MaxJobFetchCount);

                if (!waitingJobs.Any())
                {
                    return;
                }

                var jobExecuter = scope.ServiceProvider.GetRequiredService <IBackgroundJobExecuter>();
                var clock       = scope.ServiceProvider.GetRequiredService <IClock>();
                var serializer  = scope.ServiceProvider.GetRequiredService <IBackgroundJobSerializer>();

                foreach (var jobInfo in waitingJobs)
                {
                    jobInfo.TryCount++;
                    jobInfo.LastTryTime = clock.Now;

                    try
                    {
                        var jobConfiguration = JobOptions.GetJob(jobInfo.JobName);
                        var jobArgs          = serializer.Deserialize(jobInfo.JobArgs, jobConfiguration.ArgsType);
                        var context          = new JobExecutionContext(scope.ServiceProvider, jobConfiguration.JobType, jobArgs);

                        try
                        {
                            jobExecuter.Execute(context);

                            store.Delete(jobInfo.Id);
                        }
                        catch (BackgroundJobExecutionException)
                        {
                            var nextTryTime = CalculateNextTryTime(jobInfo, clock);

                            if (nextTryTime.HasValue)
                            {
                                jobInfo.NextTryTime = nextTryTime.Value;
                            }
                            else
                            {
                                jobInfo.IsAbandoned = true;
                            }

                            TryUpdate(store, jobInfo);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException(ex);
                        jobInfo.IsAbandoned = true;
                        TryUpdate(store, jobInfo);
                    }
                }
            }
        }
コード例 #25
0
        protected override void ProcessSession(ScriptSession session)
        {
            if (session.State == RunspaceAvailability.Busy)
            {
                WriteError(typeof(CmdletInvocationException),
                           $"The script session with Id '{session.ID}' cannot execute the script because it is Busy. Use Stop-ScriptSession or wait for the operation to complete.",
                           ErrorIds.ScriptSessionBusy, ErrorCategory.ResourceBusy, session.ID);
                return;
            }
            session.AutoDispose = AutoDispose;
            session.SetItemLocationContext(ContextItem);

            if (ArgumentList != null)
            {
                foreach (string argument in ArgumentList.Keys)
                {
                    session.SetVariable(argument, ArgumentList[argument]);
                }
            }

            var handle     = string.IsNullOrEmpty(JobName) ? ID.NewID.ToString() : JobName;
            var jobOptions = new JobOptions(GetJobId(session.ID, handle), "PowerShell", "shell", this, nameof(RunJob),
                                            new object[] { session, scriptBlock.ToString() })
            {
                AfterLife      = new TimeSpan(0, 0, 1),
                ContextUser    = Identity ?? Context.User,
                EnableSecurity = !DisableSecurity,
                ClientLanguage = Context.ContentLanguage
            };

            if (Interactive)
            {
                var appParams = new Hashtable();
                if (scriptItem != null)
                {
                    appParams.Add("scriptId", scriptItem.ID.ToString());
                    appParams.Add("scriptDb", scriptItem.Database.Name);
                }
                else
                {
                    session.JobScript  = scriptBlock.ToString();
                    session.JobOptions = jobOptions;
                }
                appParams.Add("cfs", "1");
                appParams.Add("sessionKey", session.Key);

                var message = new ShowApplicationMessage("PowerShell/PowerShell Runner", "PowerShell", "", "500", "360",
                                                         false, appParams)
                {
                    Title = " "
                };
                PutMessage(message);
            }
            else
            {
                Sitecore.Jobs.JobManager.Start(jobOptions);
            }
            WriteObject(session);
        }
コード例 #26
0
        public void UpdateAsync()
        {
            var jobCategory = typeof(UpdateLocalDatasourceReferencesService).Name;
            var siteName    = Context.Site == null ? "No Site Context" : Context.Site.Name;
            var jobOptions  = new JobOptions(this.GetJobName(), jobCategory, siteName, this, nameof(this.Update));

            JobManager.Start(jobOptions);
        }
コード例 #27
0
        public async Task OnJob(string job, JobOptions options, Func <Task> callback)
        {
            await UpsertJob(job, options);

            var expression = new Func <object, Task>(o => callback());

            _listeners.TryAdd(job, expression);
        }
コード例 #28
0
        ConnectHandle ConnectFinalizeJobConsumer(IConsumePipeConnector consumePipe, IConsumerSpecification <FinalizeJobConsumer <TJob> > specification,
                                                 JobOptions <TJob> options, Guid jobTypeId, IJobService jobService)
        {
            var consumerFactory = new DelegateConsumerFactory <FinalizeJobConsumer <TJob> >(() => new FinalizeJobConsumer <TJob>(jobService, options, jobTypeId,
                                                                                                                                 TypeMetadataCache <TConsumer> .ShortName));

            return(_finalizeJobConsumerConnector.ConnectConsumer(consumePipe, consumerFactory, specification));
        }
コード例 #29
0
        public Job StartCreateListJob(ListSettings settings)
        {
            _activeJob   = new Job();
            settings.Job = _activeJob;
            var options = new JobOptions("ExperienceGeneratorExmLists-" + _activeJob.Id, "ExperienceGenerator", Context.Site.Name, this, "GenerateList", new object[] { settings });

            Sitecore.Jobs.JobManager.Start(options);
            return(_activeJob);
        }
コード例 #30
0
        private bool IsCoreJobRequest(HttpRequest request, JobOptions options, out PathString subPath)
        {
            if (request.Path.StartsWithSegments(options.ApiUriSegments, StringComparison.OrdinalIgnoreCase, out subPath))
            {
                return(true);
            }

            return(false);
        }
コード例 #31
0
ファイル: LightResize.cs プロジェクト: lajjne/lightresize
        /// <summary>
        /// Resizes from one filename to another
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="destPath"></param>
        /// <param name="options"></param>
        public void Build(string sourcePath, string destPath, JobOptions options)
        {
            if (sourcePath == destPath)
            {
                options = options | JobOptions.BufferEntireSourceStream;
            }

            Build(File.Open(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read), destPath, options);
        }
コード例 #32
0
        /// <summary>
        /// Runs process in current workspace using current user credentials and providing <paramref name="options"/> for running job.
        /// </summary>
        /// <param name="source">User connection.</param>
        /// <param name="processName">Process name.</param>
        /// <param name="misfireInstruction">Trigger policy.</param>
        /// <param name="parameters">Process parameters.</param>
        /// <param name="options">Instance of the <see cref="JobOptions"/> parameters.</param>
        /// <remarks>Quartz job group is the process name concatenated with static suffix.
        /// Job name is auto-generated.</remarks>
        public static void RunProcess(this UserConnection source, string processName, int misfireInstruction,
                                      IDictionary <string, object> parameters, JobOptions options)
        {
            var jobConfig = GetJobConfig(processName, source.Workspace.Name,
                                         source.CurrentUser.Name, parameters);

            jobConfig.JobOptions = options;
            RunScheduleJob(jobConfig, misfireInstruction);
        }
コード例 #33
0
        public string ImportItems(WordPressImportData data)
        {
            var options = new JobOptions("Creating and importing blog", "WeBlog", Context.Site.Name, this, "ImportBlog", new[] { data });

            // Init NVelocity before starting the job, in case something in the job uses it (creates items with a workflow that uses the Extended Email Action)
            Velocity.Init();

            var job = JobManager.Start(options);
            job.Status.Total = 0;
            return job.Handle.ToString();
        }
コード例 #34
0
        public static string Run([NotNull] string jobName, [NotNull] string category, [NotNull] Action action)
        {
            var jobOptions = new JobOptions(jobName, category, Client.Site.Name, new BackgroundJob(action), "RunJob")
            {
                AfterLife = TimeSpan.FromMinutes(1),
                ContextUser = Context.User
            };

            var job = JobManager.Start(jobOptions);

            return job.Handle.ToString();
        }
コード例 #35
0
 protected void RebuildBtn_Click(object sender, EventArgs args)
 {
     foreach (ListItem item in cblIndexes.Items)
     {
         if (item.Selected)
         {
             var options = new JobOptions("RebuildSearchIndex", "index", Sitecore.Client.Site.Name,
                                          new Builder(item.Value), "Rebuild") { AfterLife = TimeSpan.FromMinutes(1.0) };
             JobManager.Start(options);
         }
     }
 }
コード例 #36
0
        private string RebuildIndex(string indexName)
        {
            SearchIndexResolver resolver = new SearchIndexResolver();
            IIndex index = resolver.GetIndex(indexName);
            if (index == null)
            {
                ContentSearchResolver contentSearchResolver = new ContentSearchResolver();
                index = contentSearchResolver.GetIndex(indexName);
                if(index == null)
                    throw new InvalidOperationException("unknown index");
            }

            string jobId = Guid.NewGuid().ToString();

            RebuildIndexJob indexJob = new RebuildIndexJob(index);
            JobOptions option = new JobOptions(jobId, "Index rebuild", Sitecore.Context.Site.Name, indexJob, "Start") { AfterLife = TimeSpan.FromHours(1) };
            JobManager.Start(option);
            return jobId;
        }
コード例 #37
0
      public void Process(object sender, EventArgs args)
      {
         Assert.ArgumentNotNull(sender, "sender");
         Assert.ArgumentNotNull(args, "args");

         Log.Info("Historian.Handler. Starting processing for databases ({0}).".FormatWith(_databases.Count), this);

         foreach (string dbName in _databases)
         {
            if (dbName.IsNullOrEmpty())
            {
               Log.Error("Historian.Handler. Database parameter was invalid. Processing skipped", this);
               continue;
            }

            if (!StringUtil.Join(Factory.GetDatabaseNames(), ",").Contains(dbName))
            {
               Log.Error("Historian.Handler. Database '{0} does not exist. Processing skipped".FormatWith(dbName), this);
               continue;
            }

            var database = Factory.GetDatabase(dbName);
            if (database == null)
            {
               Log.Error("Historian.Handler. Database '{0} does not exist. Processing skipped".FormatWith(dbName), this);
               continue;
            }

            Log.Info("Historian.Handler. Starting processing for database '{0}'...".FormatWith(dbName), this);

            try
            {
               var jobOptions = new JobOptions("Historian.Handler.ProcessDatabase", "", Context.Site.Name, this, "ProcessDatabase", new object[] { database });
               var job = new Job(jobOptions);
               job.Start();
            }
            catch (Exception exception)
            {
               Log.Error("Historian.Handler. Background job ProcessDatabase failed. ", exception);
            }
         }
      }
コード例 #38
0
        public List<Job> QueueReport(IEnumerable<InboundRuleResult> ruleResults, Database database)
        {
            var jobs = new List<Job>();
            var siteName = Context.Site.Name;

            ruleResults
                .AsParallel()
                .ForAll(result =>
            {
                var jobName = string.Format("UrlRewrite::Reporting - Saving rewrite info for item '{0}'", result.ItemId);
                var jobOptions = new JobOptions(jobName, "UrlRewrite", siteName, this, "SaveRewriteReport", new object[] { result, database })
                                                {
                                                    WriteToLog = false
                                                };

                var job = JobManager.Start(jobOptions);

                jobs.Add(job);
            });

            return jobs;
        }
コード例 #39
0
ファイル: WordpressImport.cs プロジェクト: kaytee821/WeBlog
        private void StartImport()
        {
            // Start job for index rebuild
            var options = new JobOptions("Creating and importing blog", "WeBlog", Context.Site.Name, this, "ImportBlog");
            var job = JobManager.Start(options);
            job.Status.Total = 0;
            JobHandle.Value = job.Handle.ToString();

            // Start client pipeline to check progress
            Context.ClientPage.ClientResponse.Timer("CheckStatus", 500);
        }
コード例 #40
0
 /// <summary>
 /// Starts the specified database name.
 /// </summary>
 /// <param name="databaseName">Name of the database.</param>
 /// <param name="filePath">The file path.</param>
 /// <param name="languages">The languages.</param>
 /// <returns>
 /// The job.
 /// </returns>
 public virtual Job Start(string databaseName, string filePath, List<string> languages)
 {
   JobOptions jobOptions = new JobOptions("ImportLanguage", "ImportLanguage", "shell", new ImportLanguageForm.Importer(databaseName, filePath, languages), "Import");
   return JobManager.Start(jobOptions);
 }
コード例 #41
0
ファイル: SpeJobMonitor.cs プロジェクト: sobek85/Console
 public void Start(string name, string category, ThreadStart task, JobOptions options = null)
 {
     Assert.ArgumentNotNullOrEmpty(name, "name");
     Assert.ArgumentNotNullOrEmpty(category, "category");
     Assert.ArgumentNotNull(task, "task");
     var siteName = string.Empty;
     var site = Sitecore.Context.Site;
     if (site != null)
         siteName = site.Name;
     JobHandle = JobManager.Start(new JobOptions(name, category, siteName, new TaskRunner(task), "Run")
     {
         ContextUser = options?.ContextUser ?? Sitecore.Context.User,
         AtomicExecution = false,
         EnableSecurity = options?.EnableSecurity ?? true,
         ClientLanguage = Sitecore.Context.ContentLanguage,
         AfterLife = new TimeSpan(0,0,0,10),
     }).Handle;
     ScheduleCallback();
 }
コード例 #42
0
        protected void ProcessFile()
        {
            JobOptions options = new JobOptions("ProcessFile", "ATCC", "shell", new ImportRunner(), "RunImport", new object[] { FileToImport })
            {
                ContextUser = Sitecore.Context.User,
                ClientLanguage = Sitecore.Context.ContentLanguage,
                AfterLife = TimeSpan.FromSeconds(20),
                Priority = System.Threading.ThreadPriority.Normal
            };

            Job job = JobManager.Start(options);

            JobHandle = job.Handle.ToString();

            Context.ClientPage.ClientResponse.Timer("CheckStatus", 500);
        }
コード例 #43
0
ファイル: LightResize.cs プロジェクト: imazen/lightresize
        /// <summary>
        /// Loads the bitmap from stream, processes, and renders, sending the result Bitmap to the 'consumer' callback for encoding or usage. 
        /// </summary>
        /// <param name="s"></param>
        /// <param name="consumer"></param>
        /// <param name="options"></param>
        protected void Build(Stream s, BitmapConsumer consumer, JobOptions options)
        {
            var leaveSourceStreamOpen = ((options & JobOptions.LeaveSourceStreamOpen) != 0 ||
                                 (options & JobOptions.RewindSourceStream) != 0);

            var bufferSource = ((options & JobOptions.BufferEntireSourceStream) != 0);
            var originalPosition = ((options & JobOptions.RewindSourceStream) != 0) ? s.Position : -1;
            var preserveTemp = ((options & JobOptions.PreserveTargetBitmap) != 0);

            try
            {
                try
                {
                    //Buffer source stream if requested
                    UnderlyingStream = bufferSource ? StreamUtils.CopyToMemoryStream(s,false,0x1000) : s;

                    //Allow early disposal (enables same-file edits)
                    if (bufferSource && !leaveSourceStreamOpen)
                    {
                        s.Dispose();
                        s = null;
                    }
                    //Load bitmap
                    Source = new Bitmap(UnderlyingStream, !IgnoreIccProfile);
                    //Use size
                    OriginalSize = Source.Size;

                    //Do math
                    Layout();
                    //Render to 'Dest'
                    Render();
                }
                finally
                {
                    try
                    {
                        //Dispose loaded bitmap instance
                        if (Source != null) Source.Dispose();
                    }
                    finally
                    {
                        Source = null; //Ensure reference is null
                        try
                        {
                            //Dispose buffer
                            if (UnderlyingStream != null && s != UnderlyingStream) UnderlyingStream.Dispose();
                        }
                        finally
                        {
                            UnderlyingStream = null; //Ensure reference is null
                            //Dispose source stream or restore its position
                            if (!leaveSourceStreamOpen && s != null) s.Dispose();
                            else if (originalPosition > -1 && s != null && s.CanSeek) s.Position = originalPosition;
                        }
                    }
                }
                //Fire callback to write to disk or use Bitmap instance directly
                consumer(Dest,options);
            }
            finally
            {
                //Temporary bitmap must  be disposed
                if (!preserveTemp && Dest != null) {
                    Dest.Dispose();
                    Dest = null;
                }
            }
        }
コード例 #44
0
 public static Job CreateJob(ItemReference[] elements, bool convertToBlob)
 {
     MigrationWorker worker = new MigrationWorker(elements, convertToBlob);
     JobOptions options = new JobOptions("MediaMigration", "MediaMigration", "shell", worker, "ThreadEntry");
     return new Job(options);
 }
 /// <summary>
 /// Starts the job
 /// </summary>
 /// <returns></returns>
 public string StartJob()
 {
     var options = new JobOptions(_JOBNAME, "Sitecore.Modules.Percolate.Jobs", "shell", this, "Run");
     JobManager.Start(options);
     return _JOBNAME;
 }
コード例 #46
0
ファイル: LightResize.cs プロジェクト: imazen/lightresize
        /// <summary>
        /// Reads from Stream s and writes to the given physical path
        /// </summary>
        /// <param name="s"></param>
        /// <param name="destPath"></param>
        /// <param name="options"></param>
        public void Build(Stream s, string destPath, JobOptions options)
        {
            var createParents = ((options & JobOptions.CreateParentDirectory) != 0);
            if (createParents) {
                string dirName = Path.GetDirectoryName(destPath);
                if (!Directory.Exists(dirName)) Directory.CreateDirectory(dirName);
            }

            Build(s,
                  delegate(Bitmap b, JobOptions option) {
                      using (var fs = new FileStream(destPath, FileMode.Create, FileAccess.Write)) {
                          Encode(fs);
                      }

                  }, options);
        }
コード例 #47
0
        protected void StartImport()
        {
            var dataSyncItem = GetDataSyncItem();

            var dataSyncManager = new DataSyncManager();
            LevelLogger logger = Manager.CreateLogger(dataSyncItem);
            OutputHandlerBase exporter = Manager.CreateOutputHandler(dataSyncItem, logger);
            logger.AddKey(Utility.Constants.DataSyncItemId, dataSyncItem.ID.ToString());
            logger.AddData(Utility.Constants.DataSyncItem, dataSyncItem);
            var map = dataSyncManager.InstantiateDataMap(dataSyncItem, ref logger);
            if (map != null)
            {
                var options = new JobOptions("DataSyncWizard", "Job category name", Context.Site.Name,
                                             new DataSyncWizard(), "Run", new object[] {map, map.Logger, exporter});
                var job = JobManager.Start(options);
                job.Options.CustomData = map.Logger;
                JobHandle = job.Handle.ToString();
                SheerResponse.Timer("CheckStatus", 5);
            }
            else
            {
                Active = "LastPage";
                BackButton.Disabled = true;
                if (logger.HasErrorsOrInfos())
                {
                    if (exporter != null)
                    {
                        ResultText.Value = exporter.Export();
                    }
                    else
                    {
                        ResultText.Value = "The Exporter class was null. Therefor the log was not written out.";
                    }
                }
            }
        }
コード例 #48
0
        /// <summary>
        /// Starts Building Indexes
        /// </summary>
        protected void StartRebuilding()
        {
            var str = new ListString();
            var str2 = new ListString(this.IndexMap);
            foreach (string str3 in Context.ClientPage.ClientRequest.Form.Keys)
            {
                if (!string.IsNullOrEmpty(str3) && str3.StartsWith("dk_"))
                {
                    int index = str2.IndexOf(str3);
                    if (index >= 0)
                    {
                        str.Add(str2[index + 1]);
                    }
                }
            }

            Registry.SetString("/Current_User/Rebuild Search Index/Selected", str.ToString());

                var options2 = new JobOptions("RebuildSearchIndex", "index", Client.Site.Name,
                                              new Builder(str.ToString()), "Build")
                {
                    AfterLife = TimeSpan.FromMinutes(1.0),
                    ContextUser = Context.User
                };
                var options = options2;
                var job = JobManager.Start(options);
                Context.ClientPage.ServerProperties["handle"] = job.Handle.ToString();
                Context.ClientPage.ClientResponse.Timer("CheckStatus", 500);
        }
コード例 #49
0
        public object ExecuteCommand(string guid, string command, string stringFormat)
        {
            var serializer = new JavaScriptSerializer();
            var output = new StringBuilder();

            if (!HttpContext.Current.Request.IsAuthenticated &&
                !command.StartsWith("login-user", StringComparison.OrdinalIgnoreCase))
            {
                return serializer.Serialize(
                    new
                        {
                            result = "You need to be authenticated to use the PowerShell console. Please login to Sitecore first.",
                            prompt = "PS >"
                        });
            }

            if (command.StartsWith("recycle-session", StringComparison.OrdinalIgnoreCase))
            {
                RecycleSession(guid);
                return serializer.Serialize(
                    new {result = "Session recycled.", prompt = "PS >"});
            }

            var session = GetScriptSession(guid);
            try
            {
                var handle = ID.NewID.ToString();
                var jobOptions = new JobOptions(GetJobID(guid, handle), "PowerShell", "shell", this, "RunJob",
                                                new object[] {session, command})
                    {
                        AfterLife = new TimeSpan(0, 10, 0),
                        ContextUser = Sitecore.Context.User
                    };
                JobManager.Start(jobOptions);
                Thread.Sleep(WebServiceSettings.CommandWaitMillis);
                return PollCommandOutput(guid, handle, stringFormat);
            }
            catch (Exception ex)
            {
                return
                    serializer.Serialize(
                        new Result
                            {
                                status = StatusError,
                                result = output +
                                         "\r\n[[;#f00;#000]Ooops, something went wrong... Do you need assistance?]\r\n" +
                                         "[[;#f00;#000]Send an email with the stack trace to [email protected] or contact me on Twitter @AdamNaj]\r\n\r\n" +
                                         session.GetExceptionConsoleString(ex) + "\r\n",
                                prompt = string.Format("PS {0}>", session.CurrentLocation)
                            });
            }
        }
コード例 #50
0
        public object ExecuteCommand(string guid, string command, string stringFormat)
        {
            if (!WebServiceSettings.ServiceEnabledClient)
            {
                return string.Empty;
            }
            var serializer = new JavaScriptSerializer();
            var output = new StringBuilder();

            if (!HttpContext.Current.Request.IsAuthenticated &&
                !command.StartsWith("login-user", StringComparison.OrdinalIgnoreCase))
            {
                return serializer.Serialize(
                    new
                    {
                        result =
                            "You need to be authenticated to use the PowerShell console. Please login to Sitecore first.",
                        prompt = "PS >"
                    });
            }

            var session = GetScriptSession(guid);
            session.Interactive = true;
            try
            {
                var handle = ID.NewID.ToString();
                var jobOptions = new JobOptions(GetJobId(guid, handle), "PowerShell", "shell", this, "RunJob",
                    new object[] {session, command})
                {
                    AfterLife = new TimeSpan(0, 0, 20),
                    ContextUser = Sitecore.Context.User,
                    EnableSecurity = true,
                    ClientLanguage = Sitecore.Context.ContentLanguage
                };
                JobManager.Start(jobOptions);
                Thread.Sleep(WebServiceSettings.CommandWaitMillis);
                return PollCommandOutput(guid, handle, stringFormat);
            }
            catch (Exception ex)
            {
                return
                    serializer.Serialize(
                        new Result
                        {
                            status = StatusError,
                            result = output + session.GetExceptionString(ex, ScriptSession.ExceptionStringFormat.Console) + "\r\n" +
                                     "\r\n[[;#f00;#000]Uh oh, looks like the command you ran is invalid or something else went wrong. Is it something we should know about?]\r\n" +
                                     "[[;#f00;#000]Please submit a support ticket here https://git.io/spe with error details, screenshots, and anything else that might help.]\r\n\r\n" +
                                     "[[;#f00;#000]We also have a user guide here http://sitecorepowershell.gitbooks.io/sitecore-powershell-extensions/.]\r\n\r\n",
                            prompt = string.Format("PS {0}>", session.CurrentLocation)
                        });
            }
        }
コード例 #51
0
ファイル: WordpressImport.cs プロジェクト: WeTeam/WeBlog
        private void StartImport()
        {
            // Start job for index rebuild
            var options = new JobOptions("Creating and importing blog", "WeBlog", Context.Site.Name, this, "ImportBlog");

            // Init NVelocity before starting the job, in case something in the job uses it (creates items with a workflow that uses the Extended Email Action)
            Velocity.Init();

            var job = JobManager.Start(options);
            job.Status.Total = 0;
            JobHandle = job.Handle.ToString();

            // Start client pipeline to check progress
            Context.ClientPage.ClientResponse.Timer("CheckStatus", 500);
        }
コード例 #52
0
ファイル: LightResize.cs プロジェクト: imazen/lightresize
        /// <summary>
        /// Resizes from one filename to another
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="destPath"></param>
        /// <param name="options"></param>
        public void Build(string sourcePath, string destPath, JobOptions options)
        {
            if (sourcePath == destPath)
                options = options | JobOptions.BufferEntireSourceStream;

            Build(File.Open(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read), destPath, options);
        }
コード例 #53
0
        /// <summary>
        /// Starts the rebuilding.
        /// </summary>
        protected virtual void StartRebuilding()
        {
            ListString databases = new ListString();
              ListString indexMap = new ListString(this.IndexMap);
              foreach (string formKey in Sitecore.Context.ClientPage.ClientRequest.Form.Keys)
              {
            if (!string.IsNullOrEmpty(formKey) && formKey.StartsWith("dk_"))
            {
              int index = indexMap.IndexOf(formKey);
              if (index >= 0)
              {
            databases.Add(indexMap[index + 1]);
              }
            }
              }

              Registry.SetString("/Current_User/Rebuild Search Index/Selected", databases.ToString());
              JobOptions options = new JobOptions("RebuildSearchIndex", "index", Client.Site.Name, new Builder(databases.ToString()), "Build")
              {
            AfterLife = TimeSpan.FromMinutes(1.0),
            ContextUser = Sitecore.Context.User
              };
              Job job = JobManager.Start(options);
              Sitecore.Context.ClientPage.ServerProperties["handle"] = job.Handle.ToString();
              Sitecore.Context.ClientPage.ClientResponse.Timer("CheckStatus", 500);
        }
コード例 #54
0
ファイル: LightResize.cs プロジェクト: imazen/lightresize
 /// <summary>
 /// Reads from filename, writes to stream
 /// </summary>
 /// <param name="sourcePath"></param>
 /// <param name="target"></param>
 /// <param name="options"></param>
 public void Build(string sourcePath, Stream target, JobOptions options)
 {
     Build(File.Open(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read), target, options);
 }
コード例 #55
0
        private static void StartImportJob(string name, string method, object helper, params object[] args)
        {
            string str = (Context.Site != null) ? Context.Site.Name : Util.GetContentSite().Name;
              JobOptions options = new JobOptions(name, method, str, helper, method, args)
               {
            ContextUser = Context.User
             };
              options.EnableSecurity = false;
              options.AfterLife = (TimeSpan.FromSeconds(3.0));
              options.WriteToLog = true;
              JobHelper.CurrentJob = JobManager.Start(options);

              if (helper is RecipientImporterExt)
              {
            JobHelper.CurrentJob.Options.CustomData = helper;
              }
        }
コード例 #56
0
ファイル: LightResize.cs プロジェクト: imazen/lightresize
        /// <summary>
        /// Resizes from one stream to another. 
        /// 
        /// Warning - ensure that the first stream you open will be safely closed if the second stream fails to open! This means a using() or try/finally clause.
        /// </summary>
        /// <param name="s"></param>
        /// <param name="target"></param>
        /// <param name="options"></param>
        public void Build(Stream s, Stream target, JobOptions options)
        {
            Build(s, delegate(Bitmap b, JobOptions opts)
                         {
                             try
                             {
                                 //Encode from temp bitmap to target stream
                                 Encode(target);
                             }
                             finally
                             {
                                 //Ensure target stream is disposed if requested
                                 if ((opts & JobOptions.LeaveTargetStreamOpen) == 0) target.Dispose();
                             }

                         }, options);
        }
コード例 #57
0
        protected override void ProcessSession(ScriptSession session)
        {
            if (session.State == RunspaceAvailability.Busy)
            {
                WriteError(typeof(CmdletInvocationException),
                    $"The script session with Id '{session.ID}' cannot execute the script because it is Busy. Use Stop-ScriptSession or wait for the operation to complete.",
                    ErrorIds.ScriptSessionBusy, ErrorCategory.ResourceBusy, session.ID);
                return;
            }
            session.AutoDispose = AutoDispose;
            session.SetItemLocationContext(ContextItem);

            if (ArgumentList != null)
            {
                foreach (string argument in ArgumentList.Keys)
                {
                    session.SetVariable(argument, ArgumentList[argument]);
                }
            }

            var handle = string.IsNullOrEmpty(JobName) ? ID.NewID.ToString() : JobName;
            var jobOptions = new JobOptions(GetJobId(session.ID, handle), "PowerShell", "shell", this, "RunJob",
                new object[] { session, scriptBlock.ToString() })
            {
                AfterLife = new TimeSpan(0, 0, 1),
                ContextUser = Identity ?? Context.User,
                EnableSecurity = !DisableSecurity,
                ClientLanguage = Context.ContentLanguage
            };

            if (Interactive)
            {
                var appParams = new Hashtable();
                if (scriptItem != null)
                {
                    appParams.Add("scriptId", scriptItem.ID.ToString());
                    appParams.Add("scriptDb", scriptItem.Database.Name);
                }
                else
                {
                    session.JobScript = scriptBlock.ToString();
                    session.JobOptions = jobOptions;
                }
                appParams.Add("appMode", "1");
                appParams.Add("sessionKey", session.Key);

                var message = new ShowApplicationMessage("PowerShell/PowerShell Runner", "PowerShell", "", "500", "360",
                    false, appParams)
                {Title = " "};
                PutMessage(message);
            }
            else
            {
                Sitecore.Jobs.JobManager.Start(jobOptions);
            }
            WriteObject(session);
        }
コード例 #58
0
        protected void GenerateExportFile()
        {
            ResultFile = Settings.GetSetting(OfflineContentEditorSettings.DownloadFolder, "") + "\\" + "DreamCorps" + System.DateTime.Now.ToLongDateString() + ".csv";
            string path = "/sitecore/content/home/*[@@TemplateID='" + Sitecore.Context.ContentDatabase.GetItem(template.Value).ID.ToString() + "']";

            List<Item> itemList = Sitecore.Context.ContentDatabase.SelectItems(path).ToList();
            List<ID> fieldIds = (from x in FieldsToExport.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)
                                select new ID(x)).ToList();

            JobOptions options = new JobOptions("GenerateExportFile", "ATCC", "shell", new ExportRunner(), "RunExport",
                new object[] {
                    itemList,
                    fieldIds,
                    ResultFile,
                    FileFormat.Csv
                })
            {
                ContextUser = Sitecore.Context.User,
                ClientLanguage = Sitecore.Context.ContentLanguage,
                AfterLife = TimeSpan.FromSeconds(20),
                Priority = System.Threading.ThreadPriority.Normal
            };

            Job job = JobManager.Start(options);

            JobHandle = job.Handle.ToString();

            Context.ClientPage.ClientResponse.Timer("CheckStatus", 500);
        }
コード例 #59
0
        protected void StartImport()
        {
            var userSyncItem = GetUserSyncItem();

            var userSyncManager = new UserSyncManager();
            string errorMessage = String.Empty;
            var map = userSyncManager.InstantiateDataMap(userSyncItem, ref errorMessage);
            if (map != null)
            {
                if (!String.IsNullOrEmpty(DataValue))
                {
                    map.Data = DataValue;
                }
                var options = new JobOptions("FromFileUserSyncWizard", "Job category name", Context.Site.Name, new FromFileUserSyncWizard(), "Run", new object[] { map, map.LogBuilder });
                var job = JobManager.Start(options);
                job.Options.CustomData = map.LogBuilder;
                JobHandle = job.Handle.ToString();
                SheerResponse.Timer("CheckStatus", 5);
            }
            else
            {
                Active = "LastPage";
                BackButton.Disabled = true;
                if (!string.IsNullOrEmpty(errorMessage))
                {
                    ResultText.Value = errorMessage;
                }
            }
        }