public void SetCulture(string newSource)
        {
            try
            {
                ResourceDictionary langOld = Root.Single(p => p.Source.OriginalString.Contains("Strings."));
                if (langOld != null)
                {
                    ResourceDictionary lang = LoadDictionary(newSource);
                    if (lang != null)
                    {
                        Application.Current.Resources.BeginInit();

                        Root.Remove(langOld);
                        Root.Insert(0, lang);

                        Application.Current.Resources.EndInit();

                        LanguageDictionary = lang;
                    }
                }
            }
            catch (Exception e)
            {
                BusinessLogger.Manage(e);
                throw;
            }
        }
Beispiel #2
0
        public async Task <dynamic> AddHistory(AddHistoryRequest addHistoryRequest)
        {
            try
            {
                using (JobContext context = new JobContext(_option))
                {
                    var customerJobHistory = new CustomerJobHistory()
                    {
                        CustomerJobId = addHistoryRequest.CustomerJobId,
                        ProcessStatus = (byte)addHistoryRequest.ProcessStatus,
                        ProcessTime   = addHistoryRequest.ProcessTime
                    };

                    context.CustomerJobHistories.Add(customerJobHistory);
                    var res = await context.SaveChangesAsync();

                    if (res < 1)
                    {
                        var exp = new InvalidOperationException("CustomerJobHistory -> Save Error");
                    }

                    return(Helper.ReturnOk(customerJobHistory.Id));
                }
            }
            catch (Exception ex)
            {
                BusinessLogger.Log(ConstantHelper.JobLog, "AddHistory", exception: ex, extraParams: new Dictionary <string, object>()
                {
                    { "AddHistoryRequest", addHistoryRequest },
                    { "RepositoryName", this.GetType().Name }
                });
                return(Helper.ReturnError(ex));
            }
        }
        private ResourceDictionary LoadDictionary(string source)
        {
            Stream             streamInfo = null;
            ResourceDictionary dictionary = null;

            try
            {
                streamInfo = DistantManager.Instance.GetResource(source);

                if (streamInfo != null)
                {
                    Uri baseUri = DistantManager.Instance.GetUri(source);

                    dictionary = XamlReader.Load(streamInfo) as ResourceDictionary;

                    dictionary.Source = baseUri;
                }
            }
            catch (Exception e)
            {
                BusinessLogger.Manage(e);
                return(null);
            }

            return(dictionary);
        }
Beispiel #4
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 }
                });
            }
        }
        /// <summary>
        /// Gets a string from the common resource file.
        /// </summary>
        /// <param name="key">The key.of the desired string.</param>
        /// <returns>The string corresponding to the key provided.</returns>
        public string GetString(string key)
        {
            try
            {
                string value = LanguageDictionary[key] as string;
                if (value == null || value.Contains("String.Empty"))
                {
                    value = string.Empty;
                }

                return(value);
            }
            catch (Exception e)
            {
                BusinessLogger.Manage(e);
                return(string.Empty);
            }
        }
Beispiel #6
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
            });
        }
Beispiel #7
0
        private async Task <int> InsertSendDataItem(string conStr, SendDataItem sendDataDetail)
        {
            try
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                using (SqlConnection connection = new SqlConnection(conStr))
                {
                    if (connection.State == System.Data.ConnectionState.Closed)
                    {
                        connection.Open();
                    }

                    #region commandStr
                    var insertCommand = @"

INSERT INTO [dbo].[PLG_SENDDATA_ITEMS]
           ([SCHED_NAME]
           ,[JOB_NAME]
           ,[JOB_GROUP]
           ,[TRIGGER_NAME]
           ,[TRIGGER_GROUP]
           ,[TYPE]
           ,[FROM]
           ,[RECIPIENTLIST]
           ,[CC]
           ,[BCC]
           ,[REPLYTO]
           ,[BODY]
           ,[SENTDATE]
           ,[ERRORMSG]
           ,[ACTIVE]
           ,[CREATEDDATE])
     VALUES
           (@SCHED_NAME
           ,@JOB_NAME
           ,@JOB_GROUP
           ,@TRIGGER_NAME
           ,@TRIGGER_GROUP
           ,@TYPE
           ,@FROM
           ,@RECIPIENTLIST
           ,@CC
           ,@BCC
           ,@REPLYTO
           ,@BODY
           ,@SENTDATE
           ,@ERRORMSG
           ,1
           ,@CREATEDDATE)

";
                    #endregion

                    #region Execute Command
                    using (SqlCommand command = new SqlCommand(insertCommand, connection))
                    {
                        command.Parameters.AddWithValue("@SCHED_NAME", sendDataDetail.ScheduleName);
                        command.Parameters.AddWithValue("@JOB_NAME", sendDataDetail.JobName);
                        command.Parameters.AddWithValue("@JOB_GROUP", sendDataDetail.JobGroup);
                        command.Parameters.AddWithValue("@TRIGGER_NAME", sendDataDetail.TriggerName);
                        command.Parameters.AddWithValue("@TRIGGER_GROUP", sendDataDetail.TriggerGroup);
                        command.Parameters.AddWithValue("@TYPE", sendDataDetail.Type);
                        command.Parameters.AddWithValue("@FROM", sendDataDetail.From);
                        command.Parameters.AddWithValue("@RECIPIENTLIST", sendDataDetail.Recipient);
                        command.Parameters.AddWithValue("@CC", sendDataDetail.Cc);
                        command.Parameters.AddWithValue("@BCC", sendDataDetail.Bcc);
                        command.Parameters.AddWithValue("@BODY", sendDataDetail.Body);

                        if (string.IsNullOrEmpty(sendDataDetail.ReplyTo) == false)
                        {
                            command.Parameters.AddWithValue("@REPLYTO", sendDataDetail.ReplyTo);
                        }
                        else
                        {
                            command.Parameters.AddWithValue("@REPLYTO", DBNull.Value);
                        }

                        if (sendDataDetail.SentDate.HasValue)
                        {
                            command.Parameters.AddWithValue("@SENTDATE", sendDataDetail.SentDate);
                        }
                        else
                        {
                            command.Parameters.AddWithValue("@SENTDATE", DBNull.Value);
                        }

                        if (string.IsNullOrEmpty(sendDataDetail.ErrorMsg) == false)
                        {
                            command.Parameters.AddWithValue("@ERRORMSG", sendDataDetail.ErrorMsg);
                        }
                        else
                        {
                            command.Parameters.AddWithValue("@ERRORMSG", DBNull.Value);
                        }

                        command.Parameters.AddWithValue("@CREATEDDATE", sendDataDetail.CreatedDate);

                        var res = await command.ExecuteNonQueryAsync();

                        stopwatch.Stop();

                        if (res < 1)
                        {
                            LoggerService.GetLogger(ConstantHelper.JobLog).Log(new LogItem()
                            {
                                LoggerName        = ConstantHelper.JobLog,
                                Title             = "InsertSendDataItem Executed",
                                Message           = "InsertSendDataItem Executed",
                                LogItemProperties = new List <LogItemProperty>()
                                {
                                    new LogItemProperty("ServiceName", ConstantHelper.JobLog),
                                    new LogItemProperty("ActionName", "InsertSendDataItem"),
                                    new LogItemProperty("FormData", sendDataDetail),
                                    new LogItemProperty("ElapsedTimeAssn", stopwatch.Elapsed.TotalSeconds),
                                },
                                Exception = new ArgumentException("Insert Failed !"),
                                LogLevel  = LogLevel.Error
                            });
                        }
                        else
                        {
                            LoggerService.GetLogger(ConstantHelper.JobLog).Log(new LogItem()
                            {
                                LoggerName        = ConstantHelper.JobLog,
                                Title             = "InsertSendDataItem Executed",
                                Message           = "InsertSendDataItem Executed",
                                LogItemProperties = new List <LogItemProperty>()
                                {
                                    new LogItemProperty("ServiceName", ConstantHelper.JobLog),
                                    new LogItemProperty("ActionName", "InsertSendDataItem"),
                                    new LogItemProperty("ElapsedTimeAssn", stopwatch.Elapsed.TotalSeconds),
                                },
                                LogLevel = LogLevel.Trace
                            });
                        }

                        return(res);
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                BusinessLogger.Log(ConstantHelper.JobLog, "InsertSendDataItem", exception: ex, extraParams: new Dictionary <string, object>()
                {
                    { "FormData", sendDataDetail },
                    { "JobName", this.Name },
                    { "JobGuid", this.Guid }
                });
                return(-1);
            }
        }
        public static List <SendDataMailAccount> GetMailAccounts(string serviceName, string sqlConStr)
        {
            List <SendDataMailAccount> sendDataMailAccountList = new List <SendDataMailAccount>();

            try
            {
                using (SqlConnection connectionQueryData = new SqlConnection(sqlConStr))
                {
                    if (connectionQueryData.State == System.Data.ConnectionState.Closed)
                    {
                        connectionQueryData.Open();
                    }

                    #region Execute Command
                    var selectQuery = @"

SELECT [MAILACCOUNTID]
      ,[MAILACCOUNTTITLE]
      ,[MAILSERVERNAME]
      ,[MAILACCOUNTNAME]
      ,[MAILACCOUNTPASSWORD]
      ,[MAILPOP3PORT]
      ,[MAILSMTPPORT]
      ,[FROMMAILADDRESS]
  FROM [dbo].[JMS_SENDDATA_MAILACCOUNT]
WHERE ACTIVE = 1 AND ISDEFAULT = 1
";


                    using (SqlCommand command = new SqlCommand(selectQuery, connectionQueryData))
                    {
                        DataTable dataTable = new DataTable();

                        // create data adapter
                        SqlDataAdapter da = new SqlDataAdapter(command);
                        // this will query your database and return the result to your datatable
                        da.Fill(dataTable);

                        for (int i = 0; i < dataTable.Rows.Count; i++)
                        {
                            var id          = Int32.Parse(dataTable.Rows[i]["MAILACCOUNTID"].ToString());
                            var title       = dataTable.Rows[i]["MAILACCOUNTTITLE"]?.ToString();
                            var serverName  = dataTable.Rows[i]["MAILSERVERNAME"]?.ToString();
                            var accountName = dataTable.Rows[i]["MAILACCOUNTNAME"]?.ToString();
                            var accountPass = dataTable.Rows[i]["MAILACCOUNTPASSWORD"]?.ToString();
                            var pop3Port    = Int32.Parse(dataTable.Rows[i]["MAILPOP3PORT"].ToString());
                            var smptpPort   = Int32.Parse(dataTable.Rows[i]["MAILSMTPPORT"].ToString());
                            var fromAddress = dataTable.Rows[i]["FROMMAILADDRESS"]?.ToString();

                            var sendDataMailAccount = new SendDataMailAccount()
                            {
                                AccountId       = id,
                                AccountName     = accountName,
                                AccountPass     = accountPass,
                                Active          = 1,
                                FromMailAddress = fromAddress,
                                MailPop3Port    = pop3Port,
                                MailSmtpPort    = smptpPort,
                                ServerName      = serverName,
                                Title           = title
                            };

                            sendDataMailAccountList.Add(sendDataMailAccount);
                        }
                    }
                    #endregion

                    try
                    {
                        connectionQueryData.Close();
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                BusinessLogger.Log(serviceName, "GetMailAccounts", exception: ex);
            }

            return(sendDataMailAccountList);
        }
        public async Task <dynamic> AssignJob(AssignJobRequest assignJobRequest)
        {
            var transaction = await _jobContext.Database.BeginTransactionAsync();

            try
            {
                var customerId = _jobContext.Customers.Where(x => x.CustomerCode == assignJobRequest.CustomerCode).Select(x => x.Id).FirstOrDefault();
                if (customerId < 1)
                {
                    throw new InvalidOperationException($"CustomerCode:{assignJobRequest.CustomerCode} bulunamadı !");
                }

                var jobId = _jobContext.Jobs.Where(x => x.Code == assignJobRequest.JobCode).Select(x => x.Id).FirstOrDefault();
                if (jobId < 1)
                {
                    throw new InvalidOperationException($"JobCode:{assignJobRequest.JobCode} bulunamadı !");
                }

                var customerJob = new CustomerJob()
                {
                    CustomerId  = customerId,
                    JobId       = jobId,
                    Cron        = assignJobRequest.CronExp,
                    StartDate   = assignJobRequest.StartDate,
                    EndDate     = assignJobRequest.EndDate,
                    Active      = 1,
                    CreatedBy   = 1, //TODO ?
                    CreatedTime = DateTime.Now
                };

                _jobContext.CustomerJob.Add(customerJob);
                var res = await _jobContext.SaveChangesAsync();

                if (res < 1)
                {
                    var exp = new InvalidOperationException("CustomerJob -> Save Error");
                }

                if (assignJobRequest.JobParameters?.Count > 0)
                {
                    foreach (var jobItem in assignJobRequest.JobParameters)
                    {
                        var customerJobParam = new CustomerJobParameter()
                        {
                            CustomerJobId = customerJob.Id,
                            ParamSource   = jobItem.ParamSource,
                            ParamKey      = jobItem.ParamKey,
                            ParamValue    = jobItem.ParamValue,
                            Active        = 1,
                            CreatedBy     = 1, //TODO ?
                            CreatedTime   = DateTime.Now
                        };

                        _jobContext.CustomerJobParameter.Add(customerJobParam);
                    }
                }


                if (assignJobRequest.JobSubscriberItems?.Count > 0)
                {
                    foreach (var jobSubsItem in assignJobRequest.JobSubscriberItems)
                    {
                        var customerJobSubsc = new CustomerJobSubscriber()
                        {
                            CustomerJobId  = customerJob.Id,
                            Subscriber     = jobSubsItem.Subscriber,
                            SubscriberType = jobSubsItem.SubscriberType,
                            Description    = jobSubsItem.Description,
                            Active         = 1,
                            CreatedBy      = 1, //TODO ?
                            CreatedTime    = DateTime.Now
                        };

                        _jobContext.CustomerJobSubscribers.Add(customerJobSubsc);
                    }
                }

                if (assignJobRequest.JobParameters?.Count > 0 || assignJobRequest.JobSubscriberItems?.Count > 0)
                {
                    res = await _jobContext.SaveChangesAsync();

                    if (res < 1)
                    {
                        var exp = new InvalidOperationException("CustomerJobParameter -> Save Error");
                    }
                }

                await transaction.CommitAsync();

                return(Helper.ReturnOk(customerJob.Id));
            }
            catch (Exception ex)
            {
                try
                {
                    await transaction.RollbackAsync();
                }
                catch (Exception)
                {
                }

                BusinessLogger.Log(ConstantHelper.JobLog, "AddHistory", exception: ex, extraParams: new Dictionary <string, object>()
                {
                    { "AssignJobRequest", assignJobRequest },
                    { "RepositoryName", this.GetType().Name }
                });

                return(Helper.ReturnError(ex));
            }
        }