public Task GetWork(IJob job)
        {
            Task task;
            try
            {
                task = job.Execute();
            }
            catch (Exception e)
            {
                QuietLog.LogHandledException(e);
                return new Task(() => {}); // returning dummy task so the job scheduler doesn't see errors
            }

            // wrapping the task inside an outer task which will continue with an error handler.
            return CreateWrappingContinuingTask(task, t =>
            {
                if (t.IsCanceled)
                {
                    Debug.WriteLine("Background Task Canceled: " + job.GetType());
                }
                else if (t.IsFaulted)
                {
                    Debug.WriteLine("Background Task Faulted: " + job.GetType());
                    QuietLog.LogHandledException(task.Exception);
                }
                // else happiness
            }, TaskContinuationOptions.ExecuteSynchronously);
        }
        public void SetUp()
        {
            _listaGruppi = new List<SferaAziendeDTO>
            {
                new SferaAziendeDTO {Codice = "AZI01", Gruppo = "GR1", Id = 1},
                new SferaAziendeDTO {Codice = "AZI02", Gruppo = "GR1", Id = 2},
                new SferaAziendeDTO {Codice = "AZI03", Gruppo = "GR2", Id = 3},
                new SferaAziendeDTO {Codice = "AZI04", Gruppo = "GR2", Id = 4},
                new SferaAziendeDTO {Codice = "AZI05", Gruppo = "GR3", Id = 5},
                new SferaAziendeDTO {Codice = "AZI06", Gruppo = "GR3", Id = 6},
                new SferaAziendeDTO {Codice = "AZI07", Gruppo = "GR4", Id = 7},
                new SferaAziendeDTO {Codice = "AZI08", Gruppo = "GR4", Id = 8}
            };

            _aziendaService = MockRepository.GenerateStub<IAziendaService>();
            _aziendaService.Stub(x => x.GetAllGruppi()).Return(_listaGruppi.GroupBy(item => item.Gruppo).ToList());

            _richiestaImportazioneDocumentiBolletteService = MockRepository.GenerateMock<IRichiestaImportazioneDocumentiBolletteService>();
            _importazioneDocumentiBolletteService = MockRepository.GenerateMock<IImportazioneDocumentiBolletteService>();

            _windsorContainer = MockRepository.GenerateStub<IWindsorContainer>();
            _windsorContainer.Stub(x => x.Resolve<IRichiestaImportazioneDocumentiBolletteService>()).Return(_richiestaImportazioneDocumentiBolletteService);
            _windsorContainer.Stub(x => x.Resolve<IImportazioneDocumentiBolletteService>()).Return(_importazioneDocumentiBolletteService);

            _iocContainerService = MockRepository.GenerateStub<IIocContainerService>();
            _iocContainerService.Stub(x => x.GetContainerFromKey(Arg<string>.Is.Anything)).Return(_windsorContainer);

            _utenzaRicezioneDocumentoJob = new UtenzaRicezioneDocumentoJob(_aziendaService, _iocContainerService);
        }
        public void ReturnJob(IJob job)
        {
            if (job == null)
                return;

            _container.Release(job);
        }
        public override void ProcessItem(IJob job, IJobItem item)
        {
            var bitRate = job.Preset.BitRate;
            var sampleRate = job.Preset.SampleRate;
            var tempdir = Path.GetTempPath();
            var tempfile = Path.Combine(tempdir, DateTime.Now.Ticks + "." + job.Preset.Extension);

            var subType = this.GetAudioSubtypeForExtension(job.Preset.Extension);
            var waveFormat = new WaveFormat(sampleRate, 2);

            var mediaType = MediaFoundationEncoder.SelectMediaType(subType, waveFormat, bitRate);

            if (mediaType != null)
            {
                using (var decoder = new MediaFoundationReader(item.LastFile))
                {
                    using (var encoder = new MediaFoundationEncoder(mediaType))
                    {
                        encoder.Encode(tempfile, decoder);
                    }
                }
            }

            item.TemporaryFiles.Add(tempfile);
        }
 private IAsset CreateEncodingJob(IAsset workflow, IAsset video)
 {
     IEncoderSupport myEncodigSupport = new EncoderSupport(_MediaServicesContext);
     // Declare a new job.
     currentJob = _MediaServicesContext.Jobs.Create(myConfig.EncodingJobName);
     // Get a media processor reference, and pass to it the name of the
     // processor to use for the specific task.
     IMediaProcessor processor = myEncodigSupport.GetLatestMediaProcessorByName("Media Encoder Premium Workflow");
     // Create a task with the encoding details, using a string preset.
     ITask task = currentJob.Tasks.AddNew(myConfig.EncodigTaskName, processor, "", TaskOptions.None);
     // Specify the input asset to be encoded.
     task.InputAssets.Add(workflow);
     task.InputAssets.Add(video); // we add one asset
     // Add an output asset to contain the results of the job.
     // This output is specified as AssetCreationOptions.None, which
     // means the output asset is not encrypted.
     task.OutputAssets.AddNew(video.Name + "_mb", AssetCreationOptions.None);
     // Use the following event handler to check job progress.
     // The StateChange method is the same as the one in the previous sample
     currentJob.StateChanged += new EventHandler<JobStateChangedEventArgs>(myEncodigSupport.StateChanged);
     // Launch the job.
     currentJob.Submit();
     //9. Revisa el estado de ejecución del JOB
     Task progressJobTask = currentJob.GetExecutionProgressTask(CancellationToken.None);
     //10. en vez de utilizar  progressJobTask.Wait(); que solo muestra cuando el JOB termina
     //se utiliza el siguiente codigo para mostrar avance en porcentaje, como en el portal
     myEncodigSupport.WaitJobFinish(currentJob.Id);
     return currentJob.OutputMediaAssets.FirstOrDefault();
 }
Exemple #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JobRunner"/> class.
        /// </summary>
        public JobRunner(IJobConfiguration configuration, Type jobType, JobLockProvider jobLockProvider, JobHistoryProvider jobHistoryProvider, IDependencyResolver dependencyResolver)
        {
            _id = Guid.NewGuid().ToString("N").Substring(0, 10).ToLower();
            _isBusy = new Synchronized<bool>();
            _lastResult = new Synchronized<string>();
            _lastRunStartTime = new Synchronized<DateTime>();
            _lastRunFinishTime = new Synchronized<DateTime>();
            _lastStatus = new Synchronized<JobStatus>();
            _nextRunTime = new Synchronized<DateTime>();
            _status = new Synchronized<JobStatus>();
            _runLock = new object();
            _name = configuration.Name;
            _description = configuration.Description;
            _group = configuration.Group;
            _interval = configuration.Interval;
            _isTimeOfDay = configuration.IsTimeOfDay;
            _keepAlive = configuration.KeepAlive;
            _arguments = configuration.Arguments;

            _jobType = jobType;
            _jobLockProvider = jobLockProvider ?? new DefaultJobLockProvider();
            _dependencyResolver = dependencyResolver ?? new DefaultDependencyResolver();
            _jobHistoryProvider = jobHistoryProvider;

            _instance = null;
            _timer = new Timer(OnTimerCallback);

            if (_jobHistoryProvider != null)
                _jobHistoryProvider.RestoreHistory(this);

            Trace.TraceInformation("Job {0} created on {1}.", Name, Environment.MachineName);
        }
Exemple #7
0
        /// <summary>
        /// Starts this instance.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Job already started.</exception>
        public static void Start()
        {
            if (_job != null)
                throw new InvalidOperationException("Job already started.");

            var evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
            var setup = new AppDomainSetup
            {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                ShadowCopyFiles = "false"
            };

            _appDomain = AppDomain.CreateDomain("eSync-" + Guid.NewGuid(), evidence, setup);
            try
            {
                var assembly = _appDomain.Load(typeof(SyncServiceJob).Assembly.GetName());
                var jobTypeName = typeof(SyncServiceJob).FullName;

                _job = (IJob)_appDomain.CreateInstanceAndUnwrap(assembly.FullName, jobTypeName);
                _job.Start();
            }
            catch
            {
                _job = null;
                AppDomain.Unload(_appDomain);
                _appDomain = null;

                throw;
            }
        }
 public override void ProcessItem(IJob job, IJobItem item)
 {
     foreach (var file in item.TemporaryFiles)
     {
         File.Delete(file);
     }
 }
        public MultipleProcessor(CloudMediaContext context, IJob myJob = null)
        {
            InitializeComponent();
            this.Icon = Bitmaps.Azure_Explorer_ico;
            _context = context;
            _myJob = myJob;
            buttonTaskOptions1.Initialize(_context, true);
            buttonTaskOptions2.Initialize(_context, true);
            buttonTaskOptions3.Initialize(_context, true);
            buttonTaskOptions4.Initialize(_context, true);
            buttonTaskOptions5.Initialize(_context, true);
            buttonTaskOptions1.Click += ButtonTaskOptions_Click;
            buttonTaskOptions2.Click += ButtonTaskOptions_Click;
            buttonTaskOptions3.Click += ButtonTaskOptions_Click;
            buttonTaskOptions4.Click += ButtonTaskOptions_Click;
            buttonTaskOptions5.Click += ButtonTaskOptions_Click;

            if (_myJob != null) // we are in resubmit mode
            {
                textBoxConfiguration1.Text = _myJob.Tasks.FirstOrDefault().GetClearConfiguration();
                radioButtonSingleJobForAllInputAssets.Checked = true;
                panelJobMode.Enabled = false;
                numericUpDownTasks.Enabled = false;
                SelectedAssets = myJob.InputMediaAssets.ToList();
            }

            labelWarningJSON1.Text = labelWarningJSON2.Text = labelWarningJSON3.Text = labelWarningJSON4.Text = labelWarningJSON5.Text = string.Empty;

            init = false;
        }
 public EncodeJobNotification(IJob[] jobsReady, string OriginalAssetName, ILocator[] Locators, string UrlForClientStreaming)
 {
     myJobList = jobsReady;
     myAssetName = OriginalAssetName;
     myLocators = Locators;
     myUrlForClientStreaming = UrlForClientStreaming;
 }
Exemple #11
0
        public override StateEnums.Status Initialize(IJob _job)
        {
            job = _job;

            log.InfoFormat(_job.KeyHash, "SmtpMailer initialized.");
            return StateEnums.Status.Success;
        }
Exemple #12
0
        public Point(IJob job, int parentNumber)
        {
            this.job = job;
            this.parentNumber = parentNumber;

            Initialize();
        }
 public ModuleExecutor(IChannel chan, IJob curJob, int pointNum)
 {
     _assemblyFullPath = curJob.FileName;
     _channel = chan;
     _currentJob = curJob;
     _pointNum = pointNum;
 }
		public override StateEnums.Status Initialize ( IJob _job )
		{
			job = _job;
            log.InfoFormat(_job.KeyHash, "GenevaLoadablesXmlValidator initialized.");
			CheckEmptyValue = false;
			return StateEnums.Status.Success;
		}
        public void GiveBack(IJob job)
        {
            if (job == null || !_jobReferences.ContainsKey(job)) return;

            _jobReferences[job].LockFile.Dispose();
            _jobReferences.Remove(job);
        }
        void IProcess.ProcessJob(IJob job)
        {
            var input = JobDataHelper<IStockInput<int,int>>
                .New(job.Definition).ForInputGet(job);

            var output = JobDataHelper<IStockOutput<int>>
                .New(job.Definition).ForOutputSet(job);

            JobExecutionHelper.New()
                .AddHandler(() => MathOpsDefinitions.Add,
                    () =>
                    {
                        output.Set(o => o.Output,
                            input.Get(i => i.FirstInput) + input.Get(i => i.SecondInput));
                    })
                .AddHandler(() => MathOpsDefinitions.Subtract,
                    () =>
                    {
                        output.Set(o => o.Output,
                            input.Get(i => i.FirstInput) - input.Get(i => i.SecondInput));
                    })
                .AddHandler(() => MathOpsDefinitions.Multiply,
                    () =>
                    {
                        output.Set(o => o.Output,
                            input.Get(i => i.FirstInput) * input.Get(i => i.SecondInput));
                    })
                .AddHandler(() => MathOpsDefinitions.Divide,
                    () =>
                    {
                        output.Set(o => o.Output,
                            input.Get(i => i.FirstInput) / input.Get(i => i.SecondInput));
                    })
                .Execute(job.Definition);
        }
Exemple #17
0
        public JobHost(IJob job)
        {
            this.job = job;
            this.timer = new Timer(this.DoAction);

            HostingEnvironment.RegisterObject(this);
        }
 public bool CompleteJob(IJob job)
 {
     if (!_spots.ContainsKey(job)) return false;
     var zoneSpot = _spots[job];
     _zoneAvailability[zoneSpot.Item1][zoneSpot.Item2] = false;
     return true;
 }
        private void ProcessJob(IJob job)
        {
            if (job == null)
            {
                return;
            }

            var progressIncrement = 100.0 / this.stepStateMapper.Count;

            foreach (var jobItem in job.JobItems)
            {
                jobItem.IsBeingProcessed = true;
                while (jobItem.State != JobItemState.Done)
                {
                    var nextStep = this.stepStateMapper.GetStepForState(jobItem.State);
                    nextStep.ProcessItem(job, jobItem);
                    jobItem.State++;
                    jobItem.Progress = progressIncrement + jobItem.Progress;
                    if (this.worker.CancellationPending)
                    {
                        break;
                    }
                }

                jobItem.IsBeingProcessed = false;

                if (this.worker.CancellationPending)
                {
                    break;
                }
            }

            this.processingFinishedCallback?.Invoke(job);
        }
 private static string AddPriorityJobBeforeDependentJob(string orderedJobs, IJob job)
 {
     int jobIndex = orderedJobs.IndexOf(job.Name);
     string prefix = orderedJobs.Substring(0, jobIndex);
     string suffix = orderedJobs.Substring(jobIndex);
     return prefix + job.Dependency + suffix;
 }
        public JobViewModel(IJob job)
        {
            this.id = job.id;
            this.title = job.title;
            this.description = job.description;
            this.date_posted = job.date_posted;
            this.group = job.group;
            this.groupDesc = StringHelpers.UppercaseFirst(job.groupDesc);
            this.specialization = job.specialization;
            this.specializationDesc = StringHelpers.UppercaseFirst(job.specializationDesc);
            this.workbase = job.workbase;
            this.workbaseDesc = StringHelpers.UppercaseFirst(job.workbaseDesc);
            this.entryLevel = job.entryLevel;
            this.hot = job.hot;
            this.sequence = job.sequence;

            if (!string.IsNullOrEmpty(job.metaDescription))
            {
                this.metaDescription = job.metaDescription;
            }

            if (!string.IsNullOrEmpty(job.metaTags))
            {
                this.metaTags = job.metaTags;
            }
        }
Exemple #22
0
 /// <summary>
 /// Updates mutable properties from the data of the specified IJob.
 /// </summary>
 /// <param name="job"></param>
 public void UpdateFrom(IJob job)
 {
     Id = job.Id;
     Status = job.Status;
     Executable = job.Executable;
     Arguments = job.Arguments;
 }
Exemple #23
0
        protected override void OnSubJobDone(IJob job)
        {
            this.RemoveSubJob(job);

            if (this.SubJobs.Count == 0)
                SetStatus(JobStatus.Done);
        }
Exemple #24
0
        public JobScheduler(IJob job, LoggerService loggerService)
        {
            _job = job;
            _loggerService = loggerService;

            _timer.Interval = job.RunningInterval;
            _timer.AutoReset = false;
        }
 public static bool IsTimedOut(this IWorkItem workItem, IJob job)
 {
     if (job == null)
     {
         throw new ArgumentNullException("job");
     }
     return workItem != null && job.Timeout != TimeSpan.MaxValue && workItem.Started.Add(job.Timeout) < DateTime.UtcNow;
 }
Exemple #26
0
        public JobContext AddJob(IJob job, string jobName = null)
        {
            var context = new JobContext(this, job) { Name = jobName };
            context.UtcCreation = DateTime.UtcNow;
            InsertJobContext(context);

            return context;
        }
Exemple #27
0
        public override StateEnums.Status Initialize(IJob _job)
        {
            job = _job;
            wpRequest = new WebpageRequest();

            log.InfoFormat(_job.KeyHash, "HTMLScraper initialized.");
            return StateEnums.Status.Success;
        }
	    /// <summary>
	    /// Allows the job factory to destroy/cleanup the job if needed. 
	    /// No-op when using SimpleJobFactory.
	    /// </summary>
	    public virtual void ReturnJob(IJob job)
	    {
	        var disposable = job as IDisposable;
	        if (disposable != null)
	        {
	            disposable.Dispose();
	        }
	    }
 internal JobExecutionContext(IScheduler scheduler, IJob job, ITrigger trigger, DateTimeOffset time, CancellationToken cancellationToken)
 {
     _scheduler = scheduler;
     _job = job;
     _trigger = trigger;
     _time = time;
     _cancellationToken = cancellationToken;
 }
        public override void ProcessItem(IJob job, IJobItem item)
        {
            var sourceFile = new FileInfo(item.SourceFile);

            var sourceName = this.GetSourceName(sourceFile);

            item.DestinationFile = this.CreateDestinationFilePath(sourceName, job);
        }
Exemple #31
0
 public static long Schedule(JobProcessor loop, IJob job, TimeSpan timeSpan)
 {
     return(Scheduler.Schedule(loop, job, DateTime.UtcNow + timeSpan));
 }
 public static void PublishJob(Agent agent, IJob job, long duration, M_ResourceCapabilityProvider capabilityProvider)
 {
     PublishJob(agent, job, duration, capabilityProvider, String.Empty);
 }
        public static async Task <object> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log)



        //public static async Task<object> Run(HttpRequestMessage req, TraceWriter log, Microsoft.Azure.WebJobs.ExecutionContext execContext)
        {
            log.Info($"Webhook was triggered!");

            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            log.Info(jsonContent);

            if (data.jobId == null)
            {
                // used to test the function
                //data.jobId = "nb:jid:UUID:acf38b8a-aef9-4789-9f0f-f69bf6ccb8e5";
                return(req.CreateResponse(HttpStatusCode.BadRequest, new
                {
                    error = "Please pass the job ID in the input object (JobId)"
                }));
            }
            MediaServicesCredentials amsCredentials = new MediaServicesCredentials();

            log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}");

            IJob          job             = null;
            string        startTime       = "";
            string        endTime         = "";
            StringBuilder sberror         = new StringBuilder();
            string        runningDuration = "";
            bool          isRunning       = true;
            bool          isSuccessful    = true;
            bool          extendedInfo    = false;

            if (data.extendedInfo != null && ((bool)data.extendedInfo) == true)
            {
                extendedInfo = true;
            }

            try
            {
                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
                                                                                       new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
                                                                                       AzureEnvironments.AzureCloudEnvironment);

                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);

                _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);

                // Get the job
                string jobid = (string)data.jobId;
                job = _context.Jobs.Where(j => j.Id == jobid).FirstOrDefault();

                if (job == null)
                {
                    log.Info($"Job not found {jobid}");

                    return(req.CreateResponse(HttpStatusCode.InternalServerError, new
                    {
                        error = "Job not found"
                    }));
                }

                if (data.noWait != null && (bool)data.noWait)
                {
                    // No wait
                }
                else
                {
                    for (int i = 1; i <= 3; i++) // let's wait 3 times 5 seconds (15 seconds)
                    {
                        log.Info($"Job {job.Id} status is {job.State}");

                        if (job.State == JobState.Finished || job.State == JobState.Canceled || job.State == JobState.Error)
                        {
                            break;
                        }

                        log.Info("Waiting 5 s...");
                        System.Threading.Thread.Sleep(5 * 1000);
                        job = _context.Jobs.Where(j => j.Id == job.Id).FirstOrDefault();
                    }
                }


                if (job.State == JobState.Error || job.State == JobState.Canceled)
                {
                    foreach (var taskenum in job.Tasks)
                    {
                        foreach (var details in taskenum.ErrorDetails)
                        {
                            sberror.AppendLine(taskenum.Name + " : " + details.Message);
                        }
                    }
                }

                if (job.StartTime != null)
                {
                    startTime = ((DateTime)job.StartTime).ToString("o");
                }

                if (job.EndTime != null)
                {
                    endTime = ((DateTime)job.EndTime).ToString("o");
                }

                if (job.RunningDuration != null)
                {
                    runningDuration = job.RunningDuration.ToString();
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : "");
                log.Info($"ERROR: Exception {message}");
                return(req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message }));
            }

            isRunning    = !(job.State == JobState.Finished || job.State == JobState.Canceled || job.State == JobState.Error);
            isSuccessful = (job.State == JobState.Finished);

            log.Info("isSuccessful " + isSuccessful.ToString());

            if (extendedInfo && (job.State == JobState.Finished || job.State == JobState.Canceled || job.State == JobState.Error))
            {
                dynamic stats = new JObject();
                stats.mediaUnitNumber     = _context.EncodingReservedUnits.FirstOrDefault().CurrentReservedUnits;
                stats.mediaUnitSize       = JobHelpers.ReturnMediaReservedUnitName(_context.EncodingReservedUnits.FirstOrDefault().ReservedUnitType);;
                stats.otherJobsProcessing = _context.Jobs.Where(j => j.State == JobState.Processing).Count();
                stats.otherJobsScheduled  = _context.Jobs.Where(j => j.State == JobState.Scheduled).Count();
                stats.otherJobsQueue      = _context.Jobs.Where(j => j.State == JobState.Queued).Count();
                stats.amsRESTAPIEndpoint  = amsCredentials.AmsRestApiEndpoint;

                return(req.CreateResponse(HttpStatusCode.OK, new
                {
                    jobState = job.State,
                    errorText = sberror.ToString(),
                    startTime = startTime,
                    endTime = endTime,
                    runningDuration = runningDuration,
                    extendedInfo = stats.ToString(),
                    isRunning = isRunning.ToString(),
                    isSuccessful = isSuccessful.ToString(),
                    progress = job.GetOverallProgress()
                }));
            }
            else
            {
                return(req.CreateResponse(HttpStatusCode.OK, new
                {
                    jobState = job.State,
                    errorText = sberror.ToString(),
                    startTime = startTime,
                    endTime = endTime,
                    runningDuration = runningDuration,
                    isRunning = isRunning.ToString(),
                    isSuccessful = isSuccessful.ToString(),
                    progress = job.GetOverallProgress()
                }));
            }
        }
Exemple #34
0
 internal Occurrence(IJob job, DateTime startTime)
 {
     Job       = job;
     StartTime = startTime;
 }
Exemple #35
0
 public JobPair(JobProcessor jobProcessor, IJob job)
 {
     this.JobProcessor = jobProcessor;
     this.Job          = job;
 }
Exemple #36
0
 public Task <IJobId> ScheduleNowAsync(IJob job, CancellationToken cancellationToken)
 {
     return(ScheduleAsync(job, (c, d, j) => _backgroundJobClient.Enqueue <IJobRunner>(r => r.Execute(d.Name, d.Version, j))));
 }
Exemple #37
0
 public Task <IJobId> ScheduleAsync(IJob job, DateTimeOffset runAt, CancellationToken cancellationToken)
 {
     return(ScheduleAsync(job, (c, d, j) => _backgroundJobClient.Schedule <IJobRunner>(r => r.Execute(d.Name, d.Version, j), runAt)));
 }
Exemple #38
0
        /// <summary>
        /// Creates a video encoding task.
        /// </summary>
        /// <param name="asset">Asset to encode.</param>
        /// <param name="fileName">Video file name.</param>
        /// <param name="job">IJob entity.</param>
        /// <param name="configuration">Encoding configuration preset.</param>
        /// <returns>Newly created video "encode" asset.</returns>
        protected virtual IAsset CreateVideoEncodingTask(IAsset asset, string fileName, IJob job, string assetType, string configuration)
        {
            IMediaProcessor encoder = GetLatestMediaEncoderProcessor();

            ITask task = job.Tasks.AddNew(
                String.Format("{0} encoding task", configuration),
                encoder,
                configuration,
                TaskOptions.None);

            task.InputAssets.Add(asset);
            return(task.OutputAssets.AddNew(String.Format("video{0} - {1}", assetType, fileName), AssetCreationOptions.None));
        }
Exemple #39
0
 public void OnJobStart(IJob job)
 {
     m_scheduledJobs.MarkJobStarted(m_scheduledJobs.GetJobByUid(job.Uid));
 }
 public JobEventRequestContainer(IJob job, int Effects, bool IsCompleteEvent = false)
 {
     J        = job;
     E        = Effects;
     Complete = IsCompleteEvent;
 }
Exemple #41
0
 internal Occurrence(IJob job, IEnumerable <ISchedule> schedules, DateTime startTime)
 {
     Job       = job;
     Schedules = schedules;
     StartTime = startTime;
 }
Exemple #42
0
        public JobOutcome Execute(IJobProcessorServices context, IJob job)
        {
            var wsm = context.Connection.WebServiceManager;

            #region Property Definitions
            var propDefs                  = wsm.PropertyService.GetPropertyDefinitionsByEntityClassId("FILE");
            var propDefInternalId         = propDefs.Single(n => n.DispName == "Internal ID");
            var propDefProvider           = propDefs.Single(n => n.DispName == "Provider");
            var propDefOriginalCreateDate = propDefs.Single(n => n.DispName == "Original Create Date");
            #endregion

            #region Search Conditions
            var srchCondInternalId = new SrchCond
            {
                PropDefId = propDefInternalId.Id,
                PropTyp   = PropertySearchType.SingleProperty,
                SrchOper  = 4, // Is empty
                SrchRule  = SearchRuleType.Must
            };

            var srchCondInternalProvider = new SrchCond
            {
                PropDefId = propDefProvider.Id,
                PropTyp   = PropertySearchType.SingleProperty,
                SrchOper  = 3, // Is exactly (or equals)
                SrchRule  = SearchRuleType.Must,
                SrchTxt   = "Inventor"
            };

            var srchCondDateTime = new SrchCond
            {
                PropDefId = propDefOriginalCreateDate.Id,
                PropTyp   = PropertySearchType.SingleProperty,
                SrchOper  = 7, // Greater than or equal to
                SrchRule  = SearchRuleType.Must,
                SrchTxt   = DateTime.Now.AddDays(-15).ToUniversalTime().ToString(
                    "MM/dd/yyyy HH:mm:ss")
            };
            #endregion

            string     bookmark = null;
            SrchStatus status   = null;
            var        files    = new List <File>();
            while (status == null || files.Count < status.TotalHits)
            {
                var results = wsm.DocumentService.FindFilesBySearchConditions(
                    new[] { srchCondInternalId, srchCondInternalProvider, srchCondDateTime },
                    null,
                    null,
                    false,
                    true,
                    ref bookmark,
                    out status);

                if (results != null)
                {
                    files.AddRange(results);
                }
                else
                {
                    break;
                }
            }

            foreach (var file in files)
            {
                var localFilePath = string.Format(@"C:\temp\{0}", file.Name);
                try
                {
                    #region Download file
                    var fileSize    = file.FileSize;
                    var maxPartSize = wsm.FilestoreService.GetMaximumPartSize();
                    var ticket      = wsm.DocumentService.GetDownloadTicketsByMasterIds(
                        new[] { file.MasterId })[0];
                    byte[] bytes;

                    using (var stream = new System.IO.MemoryStream())
                    {
                        var startByte = 0;
                        while (startByte < fileSize)
                        {
                            var endByte = startByte + maxPartSize;
                            if (endByte > fileSize)
                            {
                                endByte = fileSize;
                            }

                            using (var filePart = wsm.FilestoreService.DownloadFilePart(
                                       ticket.Bytes, startByte, endByte, true))
                            {
                                byte[] buffer = StreamToByteArray(filePart);
                                stream.Write(buffer, 0, buffer.Length);
                                startByte += buffer.Length;
                            }
                        }

                        bytes = new byte[stream.Length];
                        stream.Seek(0, System.IO.SeekOrigin.Begin);
                        stream.Read(bytes, 0, (int)stream.Length);

                        stream.Close();
                    }

                    System.IO.File.WriteAllBytes(localFilePath, bytes);
                    #endregion

                    #region Get InternalName
                    var internalId = Apprentice.GetInternalId(localFilePath);
                    #endregion

                    #region Update properties
                    var util = Autodesk.Connectivity.Explorer.ExtensibilityTools.ExplorerLoader.
                               LoadExplorerUtil(
                        wsm.WebServiceCredentials.ServerIdentities.DataServer,
                        wsm.WebServiceCredentials.VaultName,
                        context.Connection.UserID,
                        context.Connection.Ticket);

                    var properties = new Dictionary <PropDef, object>
                    {
                        { propDefInternalId, internalId }
                    };
                    util.UpdateFileProperties(file, properties);
                    #endregion
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    #region Delete local file
                    if (System.IO.File.Exists(localFilePath))
                    {
                        try
                        {
                            System.IO.File.Delete(localFilePath);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                    #endregion
                }
            }

            return(JobOutcome.Success);
        }
Exemple #43
0
 public static long Schedule(JobProcessor loop, IJob job, int milliSecond)
 {
     return(Scheduler.Schedule(loop, job, DateTime.UtcNow.AddTicks((long)milliSecond * 10000L)));
 }
Exemple #44
0
        public DateTime?GetLastJobStarted(IJob job)
        {
            var jobEntity = m_scheduledJobs.GetJobByUid(job.Uid);

            return(jobEntity?.LastStartDt);
        }
Exemple #45
0
 private void OnSchedulerJobUnscheduled(IJob job)
 {
     RemoveJob(job as IMetadataLookupJob);
 }
Exemple #46
0
 public void OnJobSucceeded(IJob job)
 {
     m_scheduledJobs.MarkJobSucceeded(m_scheduledJobs.GetJobByUid(job.Uid));
 }
 public void ReturnJob(IJob job)
 {
     (job as IDisposable)?.Dispose();
 }
Exemple #48
0
 internal Occurrence(IJob job, ISchedule schedule, DateTime startTime)
     : this(job, new List <ISchedule> {
     schedule
 }, startTime)
 {
 }
Exemple #49
0
 public void OnJobFailed(IJob job, Exception ex)
 {
     m_scheduledJobs.MarkJobFailed(m_scheduledJobs.GetJobByUid(job.Uid));
 }
        /// <summary>
        /// Create a JobExecutionContext with the given context data.
        /// </summary>
        public JobExecutionContextImpl(IScheduler scheduler, TriggerFiredBundle firedBundle, IJob job)
        {
            this.scheduler       = scheduler;
            trigger              = firedBundle.Trigger;
            Calendar             = firedBundle.Calendar;
            jobDetail            = firedBundle.JobDetail;
            jobInstance          = job;
            Recovering           = firedBundle.Recovering;
            FireTimeUtc          = firedBundle.FireTimeUtc;
            ScheduledFireTimeUtc = firedBundle.ScheduledFireTimeUtc;
            PreviousFireTimeUtc  = firedBundle.PrevFireTimeUtc;
            NextFireTimeUtc      = firedBundle.NextFireTimeUtc;

            jobDataMap = new JobDataMap(jobDetail.JobDataMap.Count + trigger.JobDataMap.Count);
            jobDataMap.PutAll(jobDetail.JobDataMap);
            jobDataMap.PutAll(trigger.JobDataMap);
            cancellationTokenSource = new CancellationTokenSource();
            cancellationToken       = cancellationTokenSource.Token;
        }
Exemple #51
0
 public void ReturnJob(IJob job)
 {
     _resolutionRoot.Release(job);
 }
Exemple #52
0
 public Task <IJobId> ScheduleAsync(IJob job, TimeSpan delay, CancellationToken cancellationToken)
 {
     return(ScheduleAsync(job, (c, d, j) => _backgroundJobClient.Schedule <IJobRunner>(r => r.Execute(d.Name, d.Version, j), delay)));
 }
Exemple #53
0
 public async Task Enqueue(IJob job)
 {
     await _writer.WriteAsync(job);
 }
Exemple #54
0
 /// <summary>
 /// initial task
 /// </summary>
 /// <param name="job"></param>
 /// <param name="interval">millisecond</param>
 /// <param name="option"></param>
 public IntervalTask(IJob job, int interval, TaskOption option) : base(job, option)
 {
     _option   = option;
     _interval = interval;
 }
Exemple #55
0
        /// <summary>
        /// Creates locators for all job assets.
        /// </summary>
        /// <param name="fileName">Original file name.</param>
        /// <param name="asset">Original video asset.</param>
        /// <param name="job">IJob entity.</param>
        /// <returns>WAMSJobLocators entity containing original and encoded video locators.</returns>
        protected virtual WAMSJobLocatorsModel CreateWAMSJobLocators(string fileName, IAsset asset, IJob job)
        {
            var wamsAssets = GetWAMSTaskAssets(job);

            // Add additional locators to this model if needed
            return(new WAMSJobLocatorsModel()
            {
                OriginalVideo = CreateLocator(asset, fileName),
                EncodedVideoSmall = CreateVideoLocator(wamsAssets.EncodedVideoSmall),
                EncodedVideoMedium = CreateVideoLocator(wamsAssets.EncodedVideoMedium)
            });
        }
Exemple #56
0
 public ICompleteJobCommandStep1 NewCompleteJobCommand(IJob activatedJob)
 {
     return(new CompleteJobCommand(gatewayClient, asyncRetryStrategy, activatedJob.Key));
 }
        public void ReturnJob(IJob job)
        {
            var disposableJob = job as IDisposable;

            disposableJob?.Dispose();
        }
Exemple #58
0
 public void ReturnJob(IJob job)
 {
 }
        /// <summary>
        /// Run the Content Moderator job on the designated Asset from local file or blob storage
        /// </summary>
        /// <param name="asset"></param>
        static void RunContentModeratorJob(IAsset asset)
        {
            // Grab the presets
            string configuration = File.ReadAllText(CONTENT_MODERATOR_PRESET_FILE);

            // grab instance of Azure Media Content Moderator MP
            IMediaProcessor mp = _context.MediaProcessors.GetLatestMediaProcessorByName(MEDIA_PROCESSOR);

            // create Job with Content Moderator task
            IJob job = _context.Jobs.Create(String.Format("Content Moderator {0}",
                                                          asset.AssetFiles.First() + "_" + Guid.NewGuid()));

            ITask contentModeratorTask = job.Tasks.AddNew("Adult and racy classifier task",
                                                          mp, configuration,
                                                          TaskOptions.None);

            contentModeratorTask.InputAssets.Add(asset);
            contentModeratorTask.OutputAssets.AddNew("Adult and racy classifier output",
                                                     AssetCreationOptions.None);

            job.Submit();


            // Create progress printing and querying tasks
            Task progressPrintTask = new Task(() =>
            {
                IJob jobQuery = null;
                do
                {
                    var progressContext = _context;
                    jobQuery            = progressContext.Jobs
                                          .Where(j => j.Id == job.Id)
                                          .First();
                    Console.WriteLine(string.Format("{0}\t{1}",
                                                    DateTime.Now,
                                                    jobQuery.State));
                    Thread.Sleep(10000);
                }while (jobQuery.State != JobState.Finished &&
                        jobQuery.State != JobState.Error &&
                        jobQuery.State != JobState.Canceled);
            });

            progressPrintTask.Start();


            Task progressJobTask = job.GetExecutionProgressTask(
                CancellationToken.None);

            progressJobTask.Wait();

            // If job state is Error, the event handling
            // method for job progress should log errors.  Here we check
            // for error state and exit if needed.
            if (job.State == JobState.Error)
            {
                ErrorDetail error = job.Tasks.First().ErrorDetails.First();
                Console.WriteLine(string.Format("Error: {0}. {1}",
                                                error.Code,
                                                error.Message));
            }

            DownloadAsset(job.OutputMediaAssets.First(), OUTPUT_FOLDER);
        }
Exemple #60
0
        /// <summary>
        /// Creates video encoding tasks for an asset and adds newly created video assets to taskAssets entity.
        /// </summary>
        /// <param name="asset">Original video asset to process.</param>
        /// <param name="fileName">Blob file name.</param>
        /// <param name="job">IJob entity.</param>
        /// <returns>Largest IAsset entity.</returns>
        protected virtual IAsset CreateVideoEncodingTasks(IAsset asset, string fileName, IJob job)
        {
            // Add additional encoding tasks here if needed
            var assetMedium = CreateVideoEncodingTask(asset, fileName, job, _assetSizeMedium, _encodingPresetMedium);
            var assetSmall  = CreateVideoEncodingTask(assetMedium, fileName, job, _assetSizeSmall, _encodingPresetSmall);

            return(assetMedium);
        }