Ejemplo n.º 1
0
        public async Task <HttpStatusCode> DeleteJob(string jobId)
        {
            SchedulerClient        schedulerClient = new SchedulerClient(cloudServiceName, jobCollectionName, cloudCredentials);
            AzureOperationResponse jobResponse     = await schedulerClient.Jobs.DeleteAsync(jobId);

            return(jobResponse.StatusCode);
        }
Ejemplo n.º 2
0
        public void Create(Task model)
        {
            SchedulerClient             client = GetClient();
            JobCreateOrUpdateParameters p      = GetParams(model);
            bool errorOccured = false;

            try
            {
                JobCreateOrUpdateResponse result = client.Jobs.CreateOrUpdate(GetJobId(model), p);

                try
                {
                    JobUpdateStateResponse resultState = client.Jobs.UpdateState(GetJobId(model), new JobUpdateStateParameters(model.Active ? JobState.Enabled : JobState.Disabled));
                }
                catch (Hyak.Common.CloudException e)
                {
                    OmniusException.Log(e, OmniusLogSource.Cortex);
                    errorOccured = true;
                }
            }
            catch (Hyak.Common.CloudException e)
            {
                OmniusException.Log(e, OmniusLogSource.Cortex);
                errorOccured = true;
            }
            if (!errorOccured)
            {
                OmniusInfo.Log($"Succesfully created task to open {model.Url} at {model.Start_Date.ToString()}", OmniusLogSource.Cortex);
            }
        }
Ejemplo n.º 3
0
        private List <PSSchedulerJob> GetSchedulerJobs(string cloudService, string jobCollection)
        {
            List <PSSchedulerJob>   lstJobs   = new List <PSSchedulerJob>();
            CloudServiceGetResponse csDetails = csmClient.CloudServices.Get(cloudService);

            foreach (CloudServiceGetResponse.Resource csRes in csDetails.Resources)
            {
                if (csRes.ResourceProviderNamespace.Equals(Constants.SchedulerRPNameProvider, StringComparison.OrdinalIgnoreCase) && csRes.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))
                {
                    SchedulerClient schedClient = new SchedulerClient(csmClient.Credentials, cloudService, jobCollection);
                    JobListResponse jobs        = schedClient.Jobs.List(new JobListParameters
                    {
                        Skip = 0,
                    });
                    foreach (Job job in jobs)
                    {
                        lstJobs.Add(new PSSchedulerJob
                        {
                            JobName           = job.Id,
                            Lastrun           = job.Status == null ? null : job.Status.LastExecutionTime,
                            Nextrun           = job.Status == null ? null : job.Status.NextExecutionTime,
                            Status            = job.State.ToString(),
                            StartTime         = job.StartTime,
                            Recurrence        = job.Recurrence == null ? "" : job.Recurrence.Interval.ToString() + " per " + job.Recurrence.Frequency.ToString(),
                            Failures          = job.Status == null ? default(int?) : job.Status.FailureCount,
                            Faults            = job.Status == null ? default(int?) : job.Status.FaultedCount,
                            Executions        = job.Status == null ? default(int?) : job.Status.ExecutionCount,
                            EndSchedule       = GetEndTime(job),
                            JobCollectionName = jobCollection
                        });
                    }
                }
            }
            return(lstJobs);
        }
Ejemplo n.º 4
0
        public async Task <IList <Job> > GetJobs()
        {
            SchedulerClient schedulerClient = new SchedulerClient(cloudServiceName, jobCollectionName, cloudCredentials);
            JobListResponse jobResponse     = await schedulerClient.Jobs.ListAsync(new JobListParameters());

            return(jobResponse.Jobs);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Updates given Storage Queue Scheduler job
        /// </summary>
        /// <param name="jobRequest">Request values</param>
        /// <param name="status">Status of uodate operation</param>
        /// <returns>Updated Storage Queue Scheduler job</returns>
        public PSJobDetail PatchStorageJob(PSCreateJobParams jobRequest, out string status)
        {
            if (!this.AvailableRegions.Contains(jobRequest.Region, StringComparer.OrdinalIgnoreCase))
            {
                throw new Exception(Resources.SchedulerInvalidLocation);
            }

            SchedulerClient schedulerClient = this.currentSubscription.CreateClient <SchedulerClient>(false, jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName, csmClient.Credentials, schedulerManagementClient.BaseUri);

            //Get Existing job
            Job job = schedulerClient.Jobs.Get(jobRequest.JobName).Job;

            JobCreateOrUpdateParameters jobUpdateParams = PopulateExistingJobParams(job, jobRequest, job.Action.Type);

            JobCreateOrUpdateResponse jobUpdateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobUpdateParams);

            if (!string.IsNullOrEmpty(jobRequest.JobState))
            {
                schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters
                {
                    State = jobRequest.JobState.Equals("Enabled", StringComparison.OrdinalIgnoreCase) ? JobState.Enabled
                        : JobState.Disabled
                });
            }

            status = jobUpdateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobUpdateResponse.StatusCode.ToString();

            return(GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName()));
        }
        public static void GetSchedulerJobHistory(string cloudServiceName, string jobCollectionName, CertificateCloudCredentials credentials)
        {
            try
            {
                var schedulerClient = new SchedulerClient(cloudServiceName, jobCollectionName, credentials);
                foreach (var job in schedulerClient.Jobs.List(
                             new JobListParameters()
                {
                    Top = 100                          /*State = JobState.Enabled*/
                }))
                {
                    Console.WriteLine("GetSchedulerJobHistory :\n" + "Job: {0} - Action: {1} - State: {2} - Status: {3}",
                                      job.Id, job.Action, job.State,
                                      job.Status);

                    foreach (var history in schedulerClient.Jobs.GetHistory(job.Id, new JobGetHistoryParameters()))
                    {
                        Console.WriteLine("GetSchedulerJobHistory : - > {0} - {1}: {2} \n\n", history.StartTime,
                                          history.EndTime, history.Message);
                    }
                }

                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("GetSchedulerJobHistory :\n" + e.Message);
            }
        }
Ejemplo n.º 7
0
        private void OpenProject(object sender, RoutedEventArgs e)
        {
            var openDialog = new OpenFileDialog
            {
                Filter     = "GradRooAte Project (*.grdb)|*.grdb",
                DefaultExt = "grdb",
                Title      = "Open project"
            };
            var ok = openDialog.ShowDialog();

            if (!ok.GetValueOrDefault())
            {
                return;
            }
            var path = openDialog.FileName;

            try
            {
                client = LocalScheduler.Connect(path);
            }
            catch (Exception ex)
            {
                // TODO: Use well formatted errors
                MessageBox.Show($"Could not open database: {ex.Message}");
                return;
            }

            DialogResult = true;
            Close();
        }
Ejemplo n.º 8
0
        private static bool JobAlreadyExists(string jobIdentifier)
        {
            var schedulerClient  = new SchedulerClient(JobsCloudServiceName, JobsCollectionName, Credentials);
            var existingJobs     = schedulerClient.Jobs.List(new JobListParameters());
            var jobAlreadyExists = existingJobs.Jobs.Any(x => x.Id == jobIdentifier);

            return(jobAlreadyExists);
        }
        public PSJobDetail CreateHttpJob(PSCreateJobParams jobRequest, out string status)
        {
            SchedulerClient             schedulerClient = new SchedulerClient(csmClient.Credentials, jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName);
            JobCreateOrUpdateParameters jobCreateParams = new JobCreateOrUpdateParameters
            {
                Action = new JobAction
                {
                    Request = new JobHttpRequest
                    {
                        Uri    = jobRequest.Uri,
                        Method = jobRequest.Method
                    },
                }
            };

            if (jobRequest.Headers != null)
            {
                jobCreateParams.Action.Request.Headers = jobRequest.Headers.ToDictionary();
            }

            if (jobRequest.Method.Equals("PUT", StringComparison.OrdinalIgnoreCase) || jobRequest.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
            {
                jobCreateParams.Action.Request.Body = jobRequest.Body;
            }

            //Populate job error action
            jobCreateParams.Action.ErrorAction = PopulateErrorAction(jobRequest);

            jobCreateParams.StartTime = jobRequest.StartTime ?? default(DateTime?);

            if (jobRequest.Interval != null || jobRequest.ExecutionCount != null || !string.IsNullOrEmpty(jobRequest.Frequency) || jobRequest.EndTime != null)
            {
                jobCreateParams.Recurrence       = new JobRecurrence();
                jobCreateParams.Recurrence.Count = jobRequest.ExecutionCount ?? default(int?);

                if (!string.IsNullOrEmpty(jobRequest.Frequency))
                {
                    jobCreateParams.Recurrence.Frequency = (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency);
                }

                jobCreateParams.Recurrence.Interval = jobRequest.Interval ?? default(int?);

                jobCreateParams.Recurrence.EndTime = jobRequest.EndTime ?? default(DateTime?);
            }

            JobCreateOrUpdateResponse jobCreateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobCreateParams);

            if (!string.IsNullOrEmpty(jobRequest.JobState) && jobRequest.JobState.Equals("DISABLED", StringComparison.OrdinalIgnoreCase))
            {
                schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters {
                    State = JobState.Disabled
                });
            }

            status = jobCreateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobCreateResponse.StatusCode.ToString();

            return(GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName()));
        }
Ejemplo n.º 10
0
 public EventCreationViewModel(long channelId, ObservableCollection <ImportanceDto> importanceScale, SchedulerClient client)
 {
     _client          = client;
     _importanceScale = importanceScale;
     _errors          = new EventErrors();
     _event           = new EventCrDto();
     _event.EventTime = DateTime.Now;
     _event.ChannelId = channelId;
 }
 public ChannelCreationViewModel(ObservableCollection <ChannelInfo> channels, SchedulerClient cl,
                                 IEnumerable <RolePermitions> rolesPermitions, IEnumerable <ImportanceDto> importanceDtos)
 {
     _cl = cl;
     this._rolesPermitions = rolesPermitions;
     this._importanceDtos  = importanceDtos;
     _channelCreationDto   = new ChannelCrDto();
     _channels             = channels;
 }
Ejemplo n.º 12
0
        public void TestMethod()
        {
            const string MachineName = "COMP";
            var          client      = new SchedulerClient <IPingPongService>(10);

            client
            .Setup(c => c.Ping(MachineName, DateTime.Now))
            .Callback(service => Console.WriteLine("Callback: {0} - {1}", MachineName, DateTime.Now));
        }
Ejemplo n.º 13
0
        public SchedulerClient CreateSchedulerClient(UserCr user)
        {
            var client = new SchedulerClient();

            client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
            client.ClientCredentials.UserName.UserName = user.Nickname;
            client.ClientCredentials.UserName.Password = user.Password;
            return(client);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Creates a Storage Queue Scheduler job
        /// </summary>
        /// <param name="jobRequest">Request values</param>
        /// <param name="status">Status of create action</param>
        /// <returns>Created Storage Queue Scheduler job</returns>
        public PSJobDetail CreateStorageJob(PSCreateJobParams jobRequest, out string status)
        {
            if (!this.AvailableRegions.Contains(jobRequest.Region, StringComparer.OrdinalIgnoreCase))
            {
                throw new Exception(Resources.SchedulerInvalidLocation);
            }

            SchedulerClient schedulerClient = this.currentSubscription.CreateClient <SchedulerClient>(false, jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName, csmClient.Credentials, schedulerManagementClient.BaseUri);

            JobCreateOrUpdateParameters jobCreateParams = new JobCreateOrUpdateParameters
            {
                Action = new JobAction
                {
                    Type         = JobActionType.StorageQueue,
                    QueueMessage = new JobQueueMessage
                    {
                        Message            = jobRequest.Body ?? string.Empty,
                        StorageAccountName = jobRequest.StorageAccount,
                        QueueName          = jobRequest.QueueName,
                        SasToken           = jobRequest.SasToken
                    },
                }
            };

            //Populate job error action
            jobCreateParams.Action.ErrorAction = PopulateErrorAction(jobRequest);

            jobCreateParams.StartTime = jobRequest.StartTime ?? default(DateTime?);

            if (jobRequest.Interval != null || jobRequest.ExecutionCount != null || !string.IsNullOrEmpty(jobRequest.Frequency) || jobRequest.EndTime != null)
            {
                jobCreateParams.Recurrence       = new JobRecurrence();
                jobCreateParams.Recurrence.Count = jobRequest.ExecutionCount ?? default(int?);

                if (!string.IsNullOrEmpty(jobRequest.Frequency))
                {
                    jobCreateParams.Recurrence.Frequency = (JobRecurrenceFrequency)Enum.Parse(typeof(JobRecurrenceFrequency), jobRequest.Frequency);
                }

                jobCreateParams.Recurrence.Interval = jobRequest.Interval ?? default(int?);

                jobCreateParams.Recurrence.EndTime = jobRequest.EndTime ?? default(DateTime?);
            }

            JobCreateOrUpdateResponse jobCreateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobCreateParams);

            if (!string.IsNullOrEmpty(jobRequest.JobState) && jobRequest.JobState.Equals("DISABLED", StringComparison.OrdinalIgnoreCase))
            {
                schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters {
                    State = JobState.Disabled
                });
            }

            status = jobCreateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobCreateResponse.StatusCode.ToString();

            return(GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName()));
        }
Ejemplo n.º 15
0
        public void Delete(string taskName)
        {
            SchedulerClient client = GetClient();

            try
            {
                var response = client.Jobs.Delete(GetJobIdFromUrl(taskName));
            }
            catch (Hyak.Common.CloudException) { }
        }
        public static void CreateQueueBasedSchedulerJob(string cloudServiceName, string jobCollectionName, CertificateCloudCredentials credentials)
        {
            try
            {
                var storageAccount =
                    new CloudStorageAccount(
                        new StorageCredentials(ConnectionStringConstants.STORAGEACCOUNTNAME,
                                               ConnectionStringConstants.STORAGEKEYNAME), true);
                var queueClient = storageAccount.CreateCloudQueueClient();
                var queue       = queueClient.GetQueueReference(ConnectionStringConstants.STORAGEQUEUENAME);
                queue.CreateIfNotExists();

                var perm   = new QueuePermissions();
                var policy = new SharedAccessQueuePolicy
                {
                    SharedAccessExpiryTime = DateTime.MaxValue,
                    Permissions            = SharedAccessQueuePermissions.Add
                };
                perm.SharedAccessPolicies.Add("jobcoll001policy", policy);

                queue.SetPermissions(perm);
                var sas = queue.GetSharedAccessSignature(new SharedAccessQueuePolicy(), "jobcoll001policy");

                var schedulerClient = new SchedulerClient(cloudServiceName, jobCollectionName, credentials);
                var result          = schedulerClient.Jobs.Create(new JobCreateParameters()
                {
                    Action = new JobAction()
                    {
                        Type         = JobActionType.StorageQueue,
                        QueueMessage = new JobQueueMessage()
                        {
                            Message            = "hello there!",
                            QueueName          = ConnectionStringConstants.STORAGEQUEUENAME,
                            SasToken           = sas,
                            StorageAccountName = ConnectionStringConstants.STORAGEACCOUNTNAME
                        }
                    },
                    StartTime  = DateTime.UtcNow,
                    Recurrence = new JobRecurrence()
                    {
                        Frequency = JobRecurrenceFrequency.Minute,
                        Interval  = 1,
                        Count     = 5
                    }
                });

                Console.WriteLine("CreateQueueBasedSchedulerJob :\n" + result.RequestId);
                Console.WriteLine("CreateQueueBasedSchedulerJob :\n" + result.StatusCode);
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("CreateQueueBasedSchedulerJob :\n" + e.Message);
            }
        }
        public ScheduledAutoTestApi(string subscriptionId, X509Certificate2 managementCertificate, IQueue queue, string jobCollectionName, string storageAccountName, string sasToken, int minutesToKeepInCache)
        {
            var credentials = new CertificateCloudCredentials(subscriptionId, managementCertificate);

            _schedulerClient      = new SchedulerClient(CloudService, jobCollectionName, credentials);
            _queue                = queue;
            _storageAccountName   = storageAccountName;
            _sasToken             = sasToken;
            _minutesToKeepInCache = minutesToKeepInCache;
            _needRefresh          = false;
        }
Ejemplo n.º 18
0
        public void Delete(Task model)
        {
            SchedulerClient client = GetClient();
            string          jobId  = GetJobId(model);

            try
            {
                var response = client.Jobs.Delete(jobId);
            }
            catch (Hyak.Common.CloudException) { }
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            // todo@onuar: öylesine bir proxy denemesi yaptım. host çalışıyor mu diye baktım.
            // var proxy = new PingProxyClient("http://localhost:8090");
            // proxy.Ping("denem", DateTime.Now);

            var schedulerClient = new SchedulerClient <IPingService>(10);

            schedulerClient
            .Setup(service => service.Ping("SCHParam", DateTime.Now))
            .Callback(o => Console.WriteLine("Callback: {0}", DateTime.Now));

            Console.ReadLine();
        }
Ejemplo n.º 20
0
        public string List()
        {
            SchedulerClient client = GetClient();
            JobListResponse result = client.Jobs.List(new JobListParameters());

            string o = "<ul>";

            foreach (Job j in result)
            {
                o += "<li>" + j.Id + "</li>";
            }
            o += "</ul>";

            return(o);
        }
Ejemplo n.º 21
0
        private static void CreateJob <TJob>(TJob job)
            where TJob : AzureJob
        {
            if (JobAlreadyExists(job.Identifier))
            {
                return;
            }

            var schedulerClient   = new SchedulerClient(JobsCloudServiceName, JobsCollectionName, Credentials);
            var jobCreationResult = schedulerClient.Jobs.CreateOrUpdate(job.Identifier, job.GenerateAzureJobParameters());

            if (jobCreationResult.StatusCode != HttpStatusCode.OK)
            {
                Logger.Error(new JobSchedulerException(jobCreationResult));
            }
        }
Ejemplo n.º 22
0
        public static int RunCleanerBatch(SchedulerClient schedulerClient = null)
        {
            var batchConfig = FilecuumCleanerConfig.GetConfig(false);

            var logger = Common.GetLogger();

            // check if the job exsists
            if (batchConfig == null || batchConfig.FilecuumCleanerJobs == null)
            {
                logger.Info(
                    String.Format(
                        "No cleanerjobs found in config file. This could be an issue when the site has just restarted. Next run should go better."));

                return(-1);
            }

            logger.Info(String.Format("Starting batch: {0} jobs enabled", batchConfig.FilecuumCleanerJobs.Count(job => job.Enabled == true)));

            int totalCnt = 0;

            foreach (var cleanerJob in batchConfig.FilecuumCleanerJobs)
            {
                if (schedulerClient != null)
                {
                    schedulerClient.Progressing();
                }

                int cnt = 0;
                // check if this job is allowed to start
                // is it enabled?
                if (!cleanerJob.Enabled)
                {
                    logger.Info(String.Format("Job: {0} is currently disabled.", cleanerJob.Name));
                    continue;
                }

                // we're allowed to start
                logger.Info(String.Format("Starting job: {0}", cleanerJob.Name));
                cnt = RunCleanerJob(cleanerJob.Id);
                logger.Info(String.Format("Finished job: {0}. files deleted {1}", cleanerJob.Name, cnt));
                totalCnt += cnt;
            }

            logger.Info(String.Format("Finished batch. Files deleted: {0}.", totalCnt));

            return(totalCnt);
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            Logger logger = new Logger("AddTasks", "AddTasks");

            logger.V("Staring app");
            logger.I("Values " + string.Join(" ", args));

            SCHElement element = null;

            try
            {
                element = ShellParser.Parse(args, SCHEnvironment.LibDir);
                logger.I("Parse has been ended");
            } catch (Exception e)
            {
                logger.E("Parsing error");
                logger.E(e.ToString());

                Error(e.ToString());
                return;
            }

            using (SchedulerClient client = new SchedulerClient())
            {
                if (!client.Connect())
                {
                    Error("Unable to connect to server!");

                    logger.E("Unable to connect to server!");
                    logger.E(client.ExMsg);

                    Error(client.ExMsg);
                    return;
                }

                if (!client.SendElement(element))
                {
                    logger.E("Unable to send data");
                    logger.E(client.ExMsg);

                    Error("Unable to send data!");
                    Error(client.ExMsg);
                    return;
                }
                logger.I("OK!");
            }
        }
        public bool DeleteJob(string jobCollection, string jobName, string region = "")
        {
            if (!string.IsNullOrEmpty(region))
            {
                if (!this.AvailableRegions.Contains(region, StringComparer.OrdinalIgnoreCase))
                {
                    throw new Exception(Resources.SchedulerInvalidLocation);
                }

                SchedulerClient schedClient = this.currentSubscription.CreateClient <SchedulerClient>(false, region.ToCloudServiceName(), jobCollection, csmClient.Credentials, schedulerManagementClient.BaseUri);

                OperationResponse response = schedClient.Jobs.Delete(jobName);
                return(response.StatusCode == System.Net.HttpStatusCode.OK ? true : false);
            }
            else if (string.IsNullOrEmpty(region))
            {
                CloudServiceListResponse csList = csmClient.CloudServices.List();
                foreach (CloudServiceListResponse.CloudService cs in csList.CloudServices)
                {
                    foreach (CloudServiceGetResponse.Resource csRes in csmClient.CloudServices.Get(cs.Name).Resources)
                    {
                        if (csRes.Type.Contains(Constants.JobCollectionResource))
                        {
                            JobCollectionGetResponse jcGetResponse = schedulerManagementClient.JobCollections.Get(cs.Name, csRes.Name);
                            if (jcGetResponse.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))
                            {
                                foreach (PSSchedulerJob job in GetSchedulerJobs(cs.Name, jobCollection))
                                {
                                    if (job.JobName.Equals(jobName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        SchedulerClient schedClient = this.currentSubscription.CreateClient <SchedulerClient>(false, cs.Name, jobCollection, csmClient.Credentials, schedulerManagementClient.BaseUri);

                                        OperationResponse response = schedClient.Jobs.Delete(jobName);
                                        return(response.StatusCode == System.Net.HttpStatusCode.OK ? true : false);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(false);
        }
Ejemplo n.º 25
0
        public async Task <bool> SaveHistory(int reservationId, ReservationHistoryCommand cmd)
        {
            double chargeMultiplier = 1.00 - (cmd.ForgivenPercentage / 100.0);

            using (var sc = new SchedulerClient())
            {
                var model = new ReservationHistoryUpdate()
                {
                    ClientID         = cmd.ClientID,
                    ReservationID    = reservationId,
                    AccountID        = cmd.AccountID,
                    ChargeMultiplier = chargeMultiplier,
                    Notes            = cmd.Notes,
                    EmailClient      = cmd.EmailClient
                };

                bool result = await sc.UpdateHistory(model);

                return(result);
            }
        }
Ejemplo n.º 26
0
        public async Task <HttpStatusCode> ScheduleQueueTypeJobAsync(string accountName, string queueName, string sasToken,
                                                                     string payload, string jobId)
        {
            SchedulerClient schedulerClient = new SchedulerClient(cloudServiceName, jobCollectionName, cloudCredentials);
            var             jobAction       = new JobAction()
            {
                Type         = JobActionType.StorageQueue,
                QueueMessage = new JobQueueMessage
                {
                    StorageAccountName = accountName,
                    QueueName          = queueName,
                    SasToken           = sasToken,
                    Message            = payload
                }
            };
            var jobCreateOrUpdateParameters             = new JobCreateOrUpdateParameters(jobAction);
            JobCreateOrUpdateResponse jobCreateResponse =
                await schedulerClient.Jobs.CreateOrUpdateAsync(jobId, jobCreateOrUpdateParameters).ConfigureAwait(false);

            return(jobCreateResponse.StatusCode);
        }
        public static void CreateHttpActionBasedJob(string cloudServiceName, string jobCollectionName, CertificateCloudCredentials credentials)
        {
            try
            {
                var schedulerClient = new SchedulerClient(cloudServiceName, jobCollectionName, credentials);
                var result5         = schedulerClient.Jobs.Create(new JobCreateParameters()
                {
                    Action = new JobAction()
                    {
                        Type    = JobActionType.Http,
                        Request = new JobHttpRequest()
                        {
                            Body    = "fetchApprenticeshipFeed=sfaarmshcedulertest&command=fetchdata",
                            Headers = new Dictionary <string, string>()
                            {
                                { "Content-Type", "application/x-www-form-urlencoded" },
                                { "x-something", "value123" }
                            },
                            Method = "POST",
                            Uri    = new Uri("http://postcatcher.in/catchers/527af9acfe325802000001cb")
                        }
                    },
                    StartTime  = DateTime.UtcNow,
                    Recurrence = new JobRecurrence()
                    {
                        Frequency = JobRecurrenceFrequency.Minute,
                        Interval  = 1,
                        Count     = 5
                    }
                });

                Console.WriteLine("CreateHttpActionBasedJob :\n" + result5.RequestId);
                Console.WriteLine("CreateHttpActionBasedJob :\n" + result5.StatusCode);
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("CreateHttpActionBasedJob :\n" + e.Message);
            }
        }
Ejemplo n.º 28
0
        public async Task <Job> GetJob(string jobId)
        {
            SchedulerClient schedulerClient = new SchedulerClient(cloudServiceName, jobCollectionName, cloudCredentials);
            Job             job             = null;

            try
            {
                JobGetResponse jobResponse = await schedulerClient.Jobs.GetAsync(jobId);

                job = jobResponse.Job;
            }
            catch (Exception exception)
            {
                CloudException cloudException = exception as CloudException;
                if (cloudException != null && cloudException.Response.StatusCode != HttpStatusCode.NotFound)
                {
                    throw;
                }
            }

            return(job);
        }
        /// <summary>
        /// Create a Job
        /// </summary>
        /// <param name="cloudServiceName"></param>
        /// <param name="jobCollectionName"></param>
        /// <param name="startTime"></param>
        /// <returns></returns>
        public async Task <JobCreateOrUpdateResponse> CreateOneTimeHttpJobAsync(string cloudServiceName, string jobCollectionName, string jobName, DateTime startTime, object bodyParameters, Dictionary <string, string> headers, string method, string scheduleManagerEndpoint)
        {
            var schedulerClient = new SchedulerClient(cloudServiceName, jobCollectionName, CertificateCloudCredentials);


            var jobCreateParameters = new JobCreateOrUpdateParameters()
            {
                Action = new JobAction()
                {
                    Type    = JobActionType.Http,
                    Request = new JobHttpRequest()
                    {
                        Body    = JsonConvert.SerializeObject(bodyParameters),
                        Headers = headers,
                        Method  = method,
                        Uri     = new Uri(scheduleManagerEndpoint + "/api/archives")
                        ,
                        Authentication = new AADOAuthAuthentication()
                        {
                            Tenant   = ServiceConfiguration.AADTenant,
                            Audience = ServiceConfiguration.AADAudience,
                            ClientId = ServiceConfiguration.AADClientId,
                            Secret   = ServiceConfiguration.AADSecret,
                            Type     = HttpAuthenticationType.ActiveDirectoryOAuth
                        }
                    },
                    RetryPolicy = new RetryPolicy()
                    {
                        RetryCount    = 2,
                        RetryInterval = TimeSpan.FromMinutes(1),
                        RetryType     = RetryType.Fixed
                    }
                },
                StartTime = startTime
            };

            return(await schedulerClient.Jobs.CreateOrUpdateAsync(jobName, jobCreateParameters));
        }
        public PSJobDetail PatchHttpJob(PSCreateJobParams jobRequest, out string status)
        {
            SchedulerClient schedulerClient = new SchedulerClient(csmClient.Credentials, jobRequest.Region.ToCloudServiceName(), jobRequest.JobCollectionName);

            //Get Existing job
            Job job = schedulerClient.Jobs.Get(jobRequest.JobName).Job;

            JobCreateOrUpdateParameters jobUpdateParams = PopulateExistingJobParams(job, jobRequest, job.Action.Type);

            JobCreateOrUpdateResponse jobUpdateResponse = schedulerClient.Jobs.CreateOrUpdate(jobRequest.JobName, jobUpdateParams);

            if (!string.IsNullOrEmpty(jobRequest.JobState))
            {
                schedulerClient.Jobs.UpdateState(jobRequest.JobName, new JobUpdateStateParameters {
                    State = jobRequest.JobState.Equals("Enabled", StringComparison.OrdinalIgnoreCase) ? JobState.Enabled
                : JobState.Disabled
                });
            }

            status = jobUpdateResponse.StatusCode.ToString().Equals("OK") ? "Job has been updated" : jobUpdateResponse.StatusCode.ToString();

            return(GetJobDetail(jobRequest.JobCollectionName, jobRequest.JobName, jobRequest.Region.ToCloudServiceName()));
        }
Ejemplo n.º 31
0
            public static void WorkStarted( ref SchedulerClient objSchedulerClient )
            {
                bool ActiveThreadCountIncremented = false;
                try
                {
                    objSchedulerClient.ScheduleHistoryItem.ThreadID = Thread.CurrentThread.GetHashCode();

                    ///''''''''''''''''''''''''''''''''''''''''''''''''
                    //Put the object in the ScheduleInProgress collection
                    //and remove it from the ScheduleQueue
                    ///''''''''''''''''''''''''''''''''''''''''''''''''
                    RemoveFromScheduleQueue( objSchedulerClient.ScheduleHistoryItem );
                    AddToScheduleInProgress( objSchedulerClient.ScheduleHistoryItem );

                    ///''''''''''''''''''''''''''''''''''''''''''''''''
                    //A SchedulerClient is notifying us that their
                    //process has started.  Increase our ActiveThreadCount
                    ///''''''''''''''''''''''''''''''''''''''''''''''''
                    Interlocked.Increment( ref ActiveThreadCount );
                    ActiveThreadCountIncremented = true;

                    ///''''''''''''''''''''''''''''''''''''''''''''''''
                    //Update the schedule item
                    //object property to note the start time.
                    ///''''''''''''''''''''''''''''''''''''''''''''''''
                    objSchedulerClient.ScheduleHistoryItem.StartDate = DateTime.Now;
                    AddScheduleHistory( objSchedulerClient.ScheduleHistoryItem );

                    if( objSchedulerClient.ScheduleHistoryItem.RetainHistoryNum > 0 )
                    {
                        ///''''''''''''''''''''''''''''''''''''''''''''''''
                        //Write out the log entry for this event
                        ///''''''''''''''''''''''''''''''''''''''''''''''''
                        EventLogController objEventLog = new EventLogController();
                        LogInfo objEventLogInfo = new LogInfo();
                        objEventLogInfo.AddProperty( "THREAD ID", Thread.CurrentThread.GetHashCode().ToString() );
                        objEventLogInfo.AddProperty( "TYPE", objSchedulerClient.GetType().FullName );
                        objEventLogInfo.AddProperty( "SOURCE", objSchedulerClient.ScheduleHistoryItem.ScheduleSource.ToString() );
                        objEventLogInfo.AddProperty( "ACTIVE THREADS", ActiveThreadCount.ToString() );
                        objEventLogInfo.AddProperty( "FREE THREADS", FreeThreads.ToString() );
                        objEventLogInfo.AddProperty( "READER TIMEOUTS", ReaderTimeouts.ToString() );
                        objEventLogInfo.AddProperty( "WRITER TIMEOUTS", WriterTimeouts.ToString() );
                        objEventLogInfo.AddProperty( "IN PROGRESS", GetScheduleInProgressCount().ToString() );
                        objEventLogInfo.AddProperty( "IN QUEUE", GetScheduleQueueCount().ToString() );
                        objEventLogInfo.LogTypeKey = "SCHEDULER_EVENT_STARTED";
                        objEventLog.AddLog( objEventLogInfo );
                    }
                }
                catch( Exception exc )
                {
                    //Decrement the ActiveThreadCount because
                    //otherwise the number of active threads
                    //will appear to be climbing when in fact
                    //no tasks are being executed.
                    if( ActiveThreadCountIncremented )
                    {
                        Interlocked.Decrement( ref ActiveThreadCount );
                    }
                    Exceptions.Exceptions.ProcessSchedulerException( exc );
                }
            }
Ejemplo n.º 32
0
            public static void WorkCompleted(SchedulerClient schedulerClient)
            {
                try
                {
                    ScheduleHistoryItem scheduleHistoryItem = schedulerClient.ScheduleHistoryItem;

                    //Remove the object in the ScheduleInProgress collection
                    RemoveFromScheduleInProgress(scheduleHistoryItem);

                    //A SchedulerClient is notifying us that their
                    //process has completed.  Decrease our ActiveThreadCount
                    Interlocked.Decrement(ref _activeThreadCount);

                    //Update the schedule item object property
                    //to note the end time and next start
                    scheduleHistoryItem.EndDate = DateTime.Now;

                    if (scheduleHistoryItem.ScheduleSource == ScheduleSource.STARTED_FROM_EVENT)
                    {
                        scheduleHistoryItem.NextStart = Null.NullDate;
                    }
                    else
                    {
                        if (scheduleHistoryItem.CatchUpEnabled)
                        {
                            switch (scheduleHistoryItem.TimeLapseMeasurement)
                            {
                                case "s":
                                    scheduleHistoryItem.NextStart = scheduleHistoryItem.NextStart.AddSeconds(scheduleHistoryItem.TimeLapse);
                                    break;
                                case "m":
                                    scheduleHistoryItem.NextStart = scheduleHistoryItem.NextStart.AddMinutes(scheduleHistoryItem.TimeLapse);
                                    break;
                                case "h":
                                    scheduleHistoryItem.NextStart = scheduleHistoryItem.NextStart.AddHours(scheduleHistoryItem.TimeLapse);
                                    break;
                                case "d":
                                    scheduleHistoryItem.NextStart = scheduleHistoryItem.NextStart.AddDays(scheduleHistoryItem.TimeLapse);
                                    break;
                            }
                        }
                        else
                        {
                            switch (scheduleHistoryItem.TimeLapseMeasurement)
                            {
                                case "s":
                                    scheduleHistoryItem.NextStart = scheduleHistoryItem.StartDate.AddSeconds(scheduleHistoryItem.TimeLapse);
                                    break;
                                case "m":
                                    scheduleHistoryItem.NextStart = scheduleHistoryItem.StartDate.AddMinutes(scheduleHistoryItem.TimeLapse);
                                    break;
                                case "h":
                                    scheduleHistoryItem.NextStart = scheduleHistoryItem.StartDate.AddHours(scheduleHistoryItem.TimeLapse);
                                    break;
                                case "d":
                                    scheduleHistoryItem.NextStart = scheduleHistoryItem.StartDate.AddDays(scheduleHistoryItem.TimeLapse);
                                    break;
                            }
                        }
                    }

                    //Update the ScheduleHistory in the database
                    UpdateScheduleHistory(scheduleHistoryItem);
                    var eventLogInfo = new LogInfo();

                    if (scheduleHistoryItem.NextStart != Null.NullDate)
                    {
                        //Put the object back into the ScheduleQueue
                        //collection with the new NextStart date.
                        scheduleHistoryItem.StartDate = Null.NullDate;
                        scheduleHistoryItem.EndDate = Null.NullDate;
                        scheduleHistoryItem.LogNotes = "";
                        scheduleHistoryItem.ProcessGroup = -1;
                        AddToScheduleQueue(scheduleHistoryItem);
                    }


                    if (schedulerClient.ScheduleHistoryItem.RetainHistoryNum > 0)
                    {
                        //Write out the log entry for this event
                        var objEventLog = new EventLogController();

                        eventLogInfo.AddProperty("TYPE", schedulerClient.GetType().FullName);
                        eventLogInfo.AddProperty("THREAD ID", Thread.CurrentThread.GetHashCode().ToString());
                        eventLogInfo.AddProperty("NEXT START", Convert.ToString(scheduleHistoryItem.NextStart));
                        eventLogInfo.AddProperty("SOURCE", schedulerClient.ScheduleHistoryItem.ScheduleSource.ToString());
                        eventLogInfo.AddProperty("ACTIVE THREADS", _activeThreadCount.ToString());
                        eventLogInfo.AddProperty("FREE THREADS", FreeThreads.ToString());
                        eventLogInfo.AddProperty("READER TIMEOUTS", _readerTimeouts.ToString());
                        eventLogInfo.AddProperty("WRITER TIMEOUTS", _writerTimeouts.ToString());
                        eventLogInfo.AddProperty("IN PROGRESS", GetScheduleInProgressCount().ToString());
                        eventLogInfo.AddProperty("IN QUEUE", GetScheduleQueueCount().ToString());
                        eventLogInfo.LogTypeKey = "SCHEDULER_EVENT_COMPLETED";
                        objEventLog.AddLog(eventLogInfo);
                    }
                }
                catch (Exception exc)
                {
                    Exceptions.Exceptions.ProcessSchedulerException(exc);
                }
            }
Ejemplo n.º 33
0
            public static void WorkErrored( ref SchedulerClient objSchedulerClient, ref Exception objException )
            {
                try
                {
                    ScheduleHistoryItem objScheduleHistoryItem;
                    objScheduleHistoryItem = objSchedulerClient.ScheduleHistoryItem;
                    ///'''''''''''''''''''''''''''''''''''''''''''''''
                    //Remove the object in the ScheduleInProgress collection
                    ///'''''''''''''''''''''''''''''''''''''''''''''''
                    RemoveFromScheduleInProgress( objScheduleHistoryItem );

                    ///''''''''''''''''''''''''''''''''''''''''''''''''
                    //A SchedulerClient is notifying us that their
                    //process has errored.  Decrease our ActiveThreadCount
                    ///''''''''''''''''''''''''''''''''''''''''''''''''
                    Interlocked.Decrement( ref ActiveThreadCount );

                    Exceptions.Exceptions.ProcessSchedulerException( objException );

                    ///'''''''''''''''''''''''''''''''''''''''''''''''
                    //Update the schedule item object property
                    //to note the end time and next start
                    ///'''''''''''''''''''''''''''''''''''''''''''''''
                    objScheduleHistoryItem.EndDate = DateTime.Now;
                    if( objScheduleHistoryItem.ScheduleSource == ScheduleSource.STARTED_FROM_EVENT )
                    {
                        objScheduleHistoryItem.NextStart = Null.NullDate;
                    }
                    else if( objScheduleHistoryItem.RetryTimeLapse != Null.NullInteger )
                    {
                        switch( objScheduleHistoryItem.RetryTimeLapseMeasurement )
                        {
                            case "s":

                                objScheduleHistoryItem.NextStart = objScheduleHistoryItem.StartDate.AddSeconds( objScheduleHistoryItem.RetryTimeLapse );
                                break;
                            case "m":

                                objScheduleHistoryItem.NextStart = objScheduleHistoryItem.StartDate.AddMinutes( objScheduleHistoryItem.RetryTimeLapse );
                                break;
                            case "h":

                                objScheduleHistoryItem.NextStart = objScheduleHistoryItem.StartDate.AddHours( objScheduleHistoryItem.RetryTimeLapse );
                                break;
                            case "d":

                                objScheduleHistoryItem.NextStart = objScheduleHistoryItem.StartDate.AddDays( objScheduleHistoryItem.RetryTimeLapse );
                                break;
                        }
                    }
                    ///''''''''''''''''''''''''''''''''''''''''''''''''
                    //Update the ScheduleHistory in the database
                    ///''''''''''''''''''''''''''''''''''''''''''''''''
                    UpdateScheduleHistory( objScheduleHistoryItem );

                    if( objScheduleHistoryItem.NextStart != Null.NullDate && objScheduleHistoryItem.RetryTimeLapse != Null.NullInteger )
                    {
                        ///''''''''''''''''''''''''''''''''''''''''''''''''
                        //Put the object back into the ScheduleQueue
                        //collection with the new NextStart date.
                        ///''''''''''''''''''''''''''''''''''''''''''''''''
                        objScheduleHistoryItem.StartDate = Null.NullDate;
                        objScheduleHistoryItem.EndDate = Null.NullDate;
                        objScheduleHistoryItem.LogNotes = "";
                        objScheduleHistoryItem.ProcessGroup = - 1;
                        AddToScheduleQueue( objScheduleHistoryItem );
                    }

                    if( objSchedulerClient.ScheduleHistoryItem.RetainHistoryNum > 0 )
                    {
                        ///''''''''''''''''''''''''''''''''''''''''''''''''
                        //Write out the log entry for this event
                        ///''''''''''''''''''''''''''''''''''''''''''''''''
                        EventLogController objEventLog = new EventLogController();
                        LogInfo objEventLogInfo = new LogInfo();
                        objEventLogInfo.AddProperty( "THREAD ID", Thread.CurrentThread.GetHashCode().ToString() );
                        objEventLogInfo.AddProperty( "TYPE", objSchedulerClient.GetType().FullName );
                        if( objException != null )
                        {
                            objEventLogInfo.AddProperty( "EXCEPTION", objException.Message );
                        }
                        objEventLogInfo.AddProperty( "RESCHEDULED FOR", Convert.ToString( objScheduleHistoryItem.NextStart ) );
                        objEventLogInfo.AddProperty( "SOURCE", objSchedulerClient.ScheduleHistoryItem.ScheduleSource.ToString() );
                        objEventLogInfo.AddProperty( "ACTIVE THREADS", ActiveThreadCount.ToString() );
                        objEventLogInfo.AddProperty( "FREE THREADS", FreeThreads.ToString() );
                        objEventLogInfo.AddProperty( "READER TIMEOUTS", ReaderTimeouts.ToString() );
                        objEventLogInfo.AddProperty( "WRITER TIMEOUTS", WriterTimeouts.ToString() );
                        objEventLogInfo.AddProperty( "IN PROGRESS", GetScheduleInProgressCount().ToString() );
                        objEventLogInfo.AddProperty( "IN QUEUE", GetScheduleQueueCount().ToString() );
                        objEventLogInfo.LogTypeKey = "SCHEDULER_EVENT_FAILURE";
                        objEventLog.AddLog( objEventLogInfo );
                    }
                }
                catch( Exception exc )
                {
                    Exceptions.Exceptions.ProcessSchedulerException( exc );
                }
            }
Ejemplo n.º 34
0
 public static void WorkProgressing( ref SchedulerClient objSchedulerClient )
 {
     try
     {
         ///''''''''''''''''''''''''''''''''''''''''''''''''
         //A SchedulerClient is notifying us that their
         //process is in progress.  Informational only.
         ///''''''''''''''''''''''''''''''''''''''''''''''''
         if( objSchedulerClient.ScheduleHistoryItem.RetainHistoryNum > 0 )
         {
             ///''''''''''''''''''''''''''''''''''''''''''''''''
             //Write out the log entry for this event
             ///''''''''''''''''''''''''''''''''''''''''''''''''
             EventLogController objEventLog = new EventLogController();
             LogInfo objEventLogInfo = new LogInfo();
             objEventLogInfo.AddProperty( "THREAD ID", Thread.CurrentThread.GetHashCode().ToString() );
             objEventLogInfo.AddProperty( "TYPE", objSchedulerClient.GetType().FullName );
             objEventLogInfo.AddProperty( "SOURCE", objSchedulerClient.ScheduleHistoryItem.ScheduleSource.ToString() );
             objEventLogInfo.AddProperty( "ACTIVE THREADS", ActiveThreadCount.ToString() );
             objEventLogInfo.AddProperty( "FREE THREADS", FreeThreads.ToString() );
             objEventLogInfo.AddProperty( "READER TIMEOUTS", ReaderTimeouts.ToString() );
             objEventLogInfo.AddProperty( "WRITER TIMEOUTS", WriterTimeouts.ToString() );
             objEventLogInfo.AddProperty( "IN PROGRESS", GetScheduleInProgressCount().ToString() );
             objEventLogInfo.AddProperty( "IN QUEUE", GetScheduleQueueCount().ToString() );
             objEventLogInfo.LogTypeKey = "SCHEDULER_EVENT_PROGRESSING";
             objEventLog.AddLog( objEventLogInfo );
         }
     }
     catch( Exception exc )
     {
         Exceptions.Exceptions.ProcessSchedulerException( exc );
     }
 }