Exemple #1
0
        //public JobExecuter(IServiceProvider provider)
        //{
        //    _provider = provider;
        //}
        /// <summary>
        /// Job'ı çalıştıran method.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            // Create a new scope
            try
            {
                using (var scope = _provider.CreateScope())
                {
                    // Resolve the Scoped service
                    _customerJobHistoryRepository = scope.ServiceProvider.GetRequiredService <ICustomerJobHistoryRepository>();

                    JobDataMap dataMap = context.MergedJobDataMap;

                    //var SchedulerJob = (ISchedulerJob)dataMap.Get("SchedulerJob");
                    var SchedulerJobName = dataMap.GetString(ConstantHelper.SchedulerJobHelper.SchedulerJobDataMapHelper.SchedulerJobNameKey);
                    var root             = dataMap.GetString(ConstantHelper.SchedulerJobHelper.SchedulerJobDataMapHelper.SchedulerJobPathRootKey);
                    var jobParameters    = new List <AssignJobParameterItem>();

                    if (dataMap.ContainsKey(ConstantHelper.SchedulerJobHelper.SchedulerJobDataMapHelper.SchedulerJobParametersKey))
                    {
                        var prmString = dataMap.Get(ConstantHelper.SchedulerJobHelper.SchedulerJobDataMapHelper.SchedulerJobParametersKey).ToString();

                        jobParameters = JsonConvert.DeserializeObject <List <AssignJobParameterItem> >(prmString);
                    }

                    var jobSubscribers = new List <AssignJobSubscriberItem>();

                    if (dataMap.ContainsKey(ConstantHelper.SchedulerJobHelper.SchedulerJobDataMapHelper.SchedulerJobSubscribersKey))
                    {
                        var prmString = dataMap.Get(ConstantHelper.SchedulerJobHelper.SchedulerJobDataMapHelper.SchedulerJobSubscribersKey).ToString();

                        jobSubscribers = JsonConvert.DeserializeObject <List <AssignJobSubscriberItem> >(prmString);
                    }

                    string pluginFolder = Path.Combine(root, "JobPlugins");

                    string[] filePaths = Directory.GetFiles(pluginFolder, $"{SchedulerJobName}.dll");

                    var jobAssembly = Assembly.LoadFile(filePaths[0]);

                    var jobType = jobAssembly.GetTypes().Where(x => x.GetInterface(nameof(ISchedulerJob)) != null).FirstOrDefault();

                    var SchedulerJob = (ISchedulerJob)Activator.CreateInstance(jobType);

                    await SchedulerJob.ExecuteJobAsync(context, scope.ServiceProvider, jobParameters, jobSubscribers);
                }
            }
            catch (Exception ex)
            {
                BusinessLogger.Log(ConstantHelper.JobLog, "JobExecuter->Execute", exception: ex, extraParams: new Dictionary <string, object>()
                {
                    { "JobDataMap", context.MergedJobDataMap }
                });
            }
        }
Exemple #2
0
        public async Task ExecuteJobAsync(IJobExecutionContext context, IServiceProvider serviceProvider, List <AssignJobParameterItem> jobParameterItems, List <AssignJobSubscriberItem> jobSubscriberItems)
        {
            var customerJobIdPrm = jobParameterItems?.Where(x => x.ParamKey == ConstantHelper.SchedulerJobHelper.CustomerJobIdKey).FirstOrDefault();

            Int32.TryParse(customerJobIdPrm.ParamValue, out int customerJobId);

            ICustomerJobHistoryRepository customerJobHistoryRepository = serviceProvider.GetRequiredService <ICustomerJobHistoryRepository>();
            await customerJobHistoryRepository.AddHistory(new AddHistoryRequest()
            {
                CustomerJobId = customerJobId,
                ProcessStatus = SelfHosting.Common.JobScheduler.ProcessStatusTypes.Executing,
                ProcessTime   = DateTimeOffset.Now
            });

            try
            {
                if (jobSubscriberItems?.Count < 1)
                {
                    throw new ArgumentException("JobSubscriberItems required !");
                }

                #region Send Email

                var masterObjIdPrm = jobParameterItems?.Where(x => x.ParamKey == ConstantHelper.SchedulerJobHelper.MasterObjectIdKey).FirstOrDefault();

                var masterObjTypePrm = jobParameterItems?.Where(x => x.ParamKey == ConstantHelper.SchedulerJobHelper.MasterObjectTypeKey).FirstOrDefault();

                var templateContent = jobParameterItems?.Where(x => x.ParamKey == ConstantHelper.SchedulerJobHelper.TemplateKey).FirstOrDefault()?.ParamValue;

                var subjectData = jobParameterItems?.Where(x => x.ParamKey == ConstantHelper.SchedulerJobHelper.SubjectKey).FirstOrDefault()?.ParamValue;

                AppCacheNoSqlRepository appCacheNoSqlRepository = serviceProvider.GetRequiredService <AppCacheNoSqlRepository>();
                var cacheManager = new ApplicationCacheManager(appCacheNoSqlRepository, ConstantHelper.JobCache.JobCachePrefix);

                cacheManager.AddOrUpdateItem(ConstantHelper.JobCache.GetMasterObjectUrl(masterObjTypePrm.ParamValue), "http://localhost:51500/PMSApi/issue");

                var url = cacheManager.GetValue <string>(ConstantHelper.JobCache.GetMasterObjectUrl(masterObjTypePrm.ParamValue));

                //TODO?Master object servislerini getir
                var apiUrl   = "http://localhost:51500/PMSApi/issue";
                var endPoint = "getbyid";

                var client = new RestClient(apiUrl);

                var request = new RestRequest(endPoint, Method.GET);
                request.AddHeader("parameters", "{'id':" + masterObjIdPrm.ParamValue + "}");

                var tcs = new TaskCompletionSource <IRestResponse>();

                ///Client'ım endpointini tetikliyoruz.
                client.ExecuteAsync(request, response =>
                {
                    tcs.SetResult(response);
                });

                var restResponse = await tcs.Task;

                var template    = Handlebars.Compile(templateContent);
                var dataContent = tcs.Task.Result.Content;

                var dataFromRemote = JObject.Parse(dataContent);

                var resultJson = dataFromRemote.SelectToken("Result").ToString();

                var remoteDataExp = JsonConvert.DeserializeObject <ExpandoObject>(resultJson);

                var data = new
                {
                    Model = remoteDataExp
                };

                var body = template(data);

                #region Subject Compile
                try
                {
                    var subjectTemplate = Handlebars.Compile(subjectData);

                    subjectData = subjectTemplate(new { });
                }
                catch (Exception ex)
                {
                }
                #endregion

                var scheduleName = context.Scheduler.SchedulerName;
                var jobName      = context.JobDetail.Key.Name;
                var jobGroup     = context.JobDetail.Key.Group;

                var trgName  = context.Trigger.Key.Name;
                var trgGroup = context.Trigger.Key.Group;

                var sendDataItem = new SendDataItem()
                {
                    JobGroup     = jobGroup,
                    JobName      = jobName,
                    ScheduleName = scheduleName,
                    TriggerGroup = trgGroup,
                    TriggerName  = trgName,
                    Type         = 1, //TODO:Static - Email/Sms
                    CreatedDate  = DateTimeOffset.Now,
                    Active       = 1
                };

                var subject     = subjectData;
                var bodyContent = body;
                var recipients  = new List <string>();

                foreach (var item in jobSubscriberItems.Where(x => x.SubscriberType == (byte)JobSubscriberType.Assigned))
                {
                    recipients.Add(item.Subscriber);
                }

                sendDataItem.Cc = jobSubscriberItems.Where(x => x.SubscriberType == (byte)JobSubscriberType.Related).Select(x => x.Subscriber).Aggregate((x, y) => x + ";" + y);

                SendDataBy(serviceProvider, sendDataItem, subject, bodyContent, recipients);

                #endregion
            }
            catch (Exception ex)
            {
                BusinessLogger.Log(ConstantHelper.JobLog, "ExecuteJobAsync", exception: ex, extraParams: new Dictionary <string, object>()
                {
                    { "JobParameterItems", jobParameterItems },
                    { "JobName", this.Name },
                    { "JobGuid", this.Guid }
                });
            }

            await customerJobHistoryRepository.AddHistory(new AddHistoryRequest()
            {
                CustomerJobId = 1,
                ProcessStatus = SelfHosting.Common.JobScheduler.ProcessStatusTypes.Executed,
                ProcessTime   = DateTimeOffset.Now
            });
        }