public void DeleteScheduleLog(int ScheduleLogId)
        {
            ScheduleLog schedulelog = db.ScheduleLog.Find(ScheduleLogId);

            db.ScheduleLog.Remove(schedulelog);
            db.SaveChanges();
        }
 public ScheduleLog Post([FromBody] ScheduleLog ScheduleLog)
 {
     if (ModelState.IsValid)
     {
         ScheduleLog = ScheduleLogs.AddScheduleLog(ScheduleLog);
         logger.Log(LogLevel.Information, this, LogFunction.Create, "Schedule Log Added {ScheduleLog}", ScheduleLog);
     }
     return(ScheduleLog);
 }
 public ScheduleLog Put(int id, [FromBody] ScheduleLog ScheduleLog)
 {
     if (ModelState.IsValid)
     {
         ScheduleLog = ScheduleLogs.UpdateScheduleLog(ScheduleLog);
         logger.Log(LogLevel.Information, this, LogFunction.Update, "Schedule Log Updated {ScheduleLog}", ScheduleLog);
     }
     return(ScheduleLog);
 }
Ejemplo n.º 4
0
        public ScheduleLog ReadLog()
        {
            ScheduleLog q = null;

            if (logger.Count > 0)
            {
                q = logger.Dequeue();
            }
            return(q);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 执行定时操作
        /// </summary>
        /// <param name="info"></param>
        private void ExecuteAction(ScheduleLog info)
        {
            switch (info.Action)
            {
            case ScheduleAction.Update:
                UpdateStore(info);
                break;

            case ScheduleAction.Generate:
                GenerateTask(info);
                break;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 更新店面状态
        /// </summary>
        /// <param name="info"></param>
        private void UpdateStore(ScheduleLog info)
        {
            var storeInfo = StoreBasicInfo.GetStorInfo(info.USCode);

            if (storeInfo == null)
            {
                return;
            }

            try
            {
                if (info.ProjectId.ToLower().Contains("closure"))
                {
                    storeInfo.StoreStatus = "suoya301003";
                    storeInfo.statusName  = "Closed";
                    storeInfo.CloseDate   = info.ExecuteDate;
                    storeInfo.Update();
                }
                else if (info.ProjectId.ToLower().Contains("tpcls"))
                {
                    storeInfo.StoreStatus = "suoya301005";
                    storeInfo.statusName  = "TempClosed";
                    //storeInfo.CloseDate = info.UpdateDate;
                    storeInfo.Update();
                }
                else if (info.ProjectId.ToLower().Contains("reimage"))
                {
                    storeInfo.StoreStatus = "suoya301001";
                    storeInfo.statusName  = "Reimaging";
                    storeInfo.ReImageDate = info.ExecuteDate;
                    storeInfo.Update();
                }
                else if (info.ProjectId.ToLower().Contains("renewal"))
                {
                    storeInfo.StoreStatus = "suoya301002";
                    storeInfo.statusName  = "Renewal";
                    storeInfo.Update();
                }
                info.IsExecuted = true;
                Log.WriteLog(storeInfo.NameZHCN + "(" + info.USCode + ")状态更新成功");
            }
            catch (Exception ex)
            {
                Log.WriteErrorMessage(ex);
                Log.WriteLog(storeInfo.NameZHCN + "(" + info.USCode + ")状态更新失败");
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// 判断是否到了更新Store状态的时间
 /// </summary>
 /// <param name="info"></param>
 /// <param name="today"></param>
 /// <returns></returns>
 private bool CanOperate(ScheduleLog info, DateTime today)
 {
     if (info.ExecuteDate.HasValue)
     {
         //正常处理
         if (info.ExecuteDate.Value.ToString("yyyy-MM-dd") == today.ToString("yyyy-MM-dd"))
         {
             return(true);
         }
         //因异常未处理的数据
         else if (info.ExecuteDate < today)
         {
             return(true);
         }
     }
     return(false);
 }
Ejemplo n.º 8
0
 /// <summary>
 /// 生成任务
 /// </summary>
 /// <param name="info"></param>
 private void GenerateTask(ScheduleLog info)
 {
     if (!string.IsNullOrEmpty(info.Info))
     {
         try
         {
             var task = JsonConvert.DeserializeObject <TaskWork>(info.Info);
             task.Add();
             info.IsExecuted = true;
             Log.WriteLog(info.ProjectId + "创建" + info.FlowCode + "任务成功");
         }
         catch (Exception ex)
         {
             Log.WriteErrorMessage(ex);
             Log.WriteLog(info.ProjectId + "创建" + info.FlowCode + "任务失败");
         }
     }
 }
 public void DoWork()
 {
     try
     {
         _start = DateTime.UtcNow;
         while (!_shouldStop)
         {
             Thread.Sleep(_scheduleThreadWorkIntervalInMsec);
             if (_shouldStop)
             {
                 break;
             }
             _scheduler.ProcessSchedules();
             if (_shouldStop)
             {
                 break;
             }
             if (_scheduleThreadHttpRequestTimeOutMin > 0 && _httpRuntimeUrl.Length > 0)
             {
                 if ((DateTime.UtcNow - _start).Minutes >= _scheduleThreadHttpRequestTimeOutMin)
                 {
                     _start = DateTime.UtcNow;
                     SendHttpRequest(_httpRuntimeUrl);
                 }
             }
             if (_scheduleThreadAnalyticDebugOn)
             {
                 ScheduleLog.Debug("_scheduleThread thread: working...");
             }
         }
         if (_scheduleThreadAnalyticDebugOn)
         {
             ScheduleLog.Debug("_scheduleThread thread: terminating gracefully.");
         }
     }
     catch (Exception ex)
     {
         ScheduleLog.Error("_scheduleThread thread: terminating with expection: [" + ex.Message + "]");
         _scheduleThread = null;
     }
 }
 public static void CheckScheduleThreadStatus(HttpContext httpContext)
 {
     if (_scheduleThreadAnalyticDebugOn)
     {
         ScheduleLog.Debug("Enter CheckScheduleThreadStatus()");
     }
     if (!_scheduleThreadEnabled)
     {
         if (_scheduleThreadAnalyticDebugOn)
         {
             ScheduleLog.Debug("Exit CheckScheduleThreadStatus() !_scheduleThreadEnabled");
         }
         return;
     }
     if (_scheduleThread == null)
     {
         if (_scheduleThreadAnalyticDebugOn)
         {
             ScheduleLog.Debug("CheckScheduleThreadStatus _scheduleThread == null, wait..... to check again");
         }
         Thread.Sleep(20000);
         if (_scheduleThread == null)
         {
             ScheduleLog.Error("CheckScheduleThreadStatus _scheduleThread == null again try to start the thread");
             StartScheduleThread(httpContext);
         }
     }
     else
     {
         if (_scheduleThreadAnalyticDebugOn)
         {
             ScheduleLog.Debug("_scheduleThread is up and running!!!");
         }
     }
     SetHttpRuntimeUrl(httpContext);
     if (_scheduleThreadAnalyticDebugOn)
     {
         ScheduleLog.Debug("Exit CheckScheduleThreadStatus()");
     }
 }
 private void SendHttpRequest(string url)
 {
     try
     {
         if (String.IsNullOrEmpty(url))
         {
             ScheduleLog.Error("SendHttpRequest wrong url ");
             return;
         }
         ScheduleLog.Debug("Start SendHttpRequest to: [" + url + "]");
         WebRequest request = WebRequest.Create(url);
         request.Timeout = 40000;
         WebResponse response = null;
         try
         {
             response = request.GetResponse();
         }
         catch (Exception ex)
         {
             if (_scheduleThreadAnalyticDebugOn)
             {
                 ScheduleLog.Debug("SendHttpRequest() error: [" + ex.Message + "]");
             }
         }
         finally
         {
             if (response != null)
             {
                 response.Close();
                 response.Dispose();
             }
         }
         ScheduleLog.Debug("Finish SendHttpRequest to: [" + url + "]");
     }
     catch (Exception ex)
     {
         ScheduleLog.Error("SendHttpRequest exception: " + ex.Message);
     }
 }
        private static void SetHttpRuntimeUrl(HttpContext httpContext)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_httpRuntimeUrl))
                {
#if NETFRAMEWORK
                    _httpRuntimeUrl = httpContext.Request.Url.GetLeftPart(UriPartial.Authority)
                                      + httpContext.Request.ApplicationPath + "/favicon.ico";
#else
                    _httpRuntimeUrl = Manager.httpRuntimeURL + "/favicon.ico";//$"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.PathBase}/favicon.ico";
#endif
                    if (_scheduleThreadAnalyticDebugOn)
                    {
                        ScheduleLog.Debug("HttpRuntimeUrl() url: [" + _httpRuntimeUrl + "]");
                    }
                }
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 13
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Log.WriteLog("===================================================");
            Log.WriteLog("Start");

            var today = DateTime.Now;

            var logs = ScheduleLog.Search(i => i.IsExecuted == false).ToArray();

            foreach (var log in logs)
            {
                if (CanOperate(log, today))
                {
                    ExecuteAction(log);
                }
            }
            ScheduleLog.Update(logs);

            Log.WriteLog("End");
            Log.WriteLog("===================================================");

            this.Dispose();
        }
 public static void StopScheduleThread()
 {
     try
     {
         if (_scheduleThreadAnalyticDebugOn)
         {
             ScheduleLog.Debug("Enter StopScheduleThread()");
         }
         if (_scheduleThread != null)
         {
             if (_scheduleThreadAnalyticDebugOn)
             {
                 ScheduleLog.Debug("Try to stop the _scheduleThread");
             }
             _scheduleWorker.RequestStop();
             _scheduleThread.Join(20000);
             _scheduleWorker = null;
             _scheduleThread = null;
         }
         else
         {
             if (_scheduleThreadAnalyticDebugOn)
             {
                 ScheduleLog.Debug("_scheduleThread is not running");
             }
         }
         if (_scheduleThreadAnalyticDebugOn)
         {
             ScheduleLog.Debug("Exit StopScheduleThread()");
         }
     }
     catch (Exception ex)
     {
         ScheduleLog.Error("Exit StopScheduleThread() with Exception error: " + ex.Message);
     }
 }
Ejemplo n.º 15
0
        public IHttpActionResult Send(PostClosureMemoModel model)
        {
            var actor = ProjectUsers.GetProjectUser(model.Entity.ProjectId, ProjectUserRoleCode.AssetActor);

            using (TransactionScope tranScope = new TransactionScope())
            {
                Save(model.Entity);
                ClosureTool closureTool        = ClosureTool.FirstOrDefault(ct => ct.ProjectId == model.Entity.ProjectId);
                string      compensationAwards = "";
                string      compensation       = "暂无数据";
                if (closureTool != null && closureTool.Compensation.HasValue)
                {
                    compensationAwards = closureTool.Compensation.Value > 0 ? "Yes" : "No";
                    compensation       = closureTool.Compensation.Value.ToString("N");
                }
                Dictionary <string, string> pdfData = new Dictionary <string, string>();
                pdfData.Add("WorkflowName", "Closure");
                pdfData.Add("ProjectID", model.Entity.ProjectId);
                pdfData.Add("RegionNameENUS", model.Entity.RegionNameENUS);
                pdfData.Add("RegionNameZHCN", model.Entity.RegionNameZHCN);
                pdfData.Add("MarketNameENUS", model.Entity.MarketNameENUS);
                pdfData.Add("MarketNameZHCN", model.Entity.MarketNameZHCN);
                pdfData.Add("ProvinceNameENUS", model.Entity.ProvinceNameENUS);
                pdfData.Add("ProvinceNameZHCN", model.Entity.ProvinceNameZHCN);
                pdfData.Add("CityNameENUS", model.Entity.CityNameENUS);
                pdfData.Add("CityNameZHCN", model.Entity.CityNameZHCN);
                pdfData.Add("StoreNameENUS", model.Entity.StoreNameENUS);
                pdfData.Add("StoreNameZHCN", model.Entity.StoreNameZHCN);
                pdfData.Add("StoreAddressENUS", model.Entity.StoreAddressENUS);
                pdfData.Add("StoreAddressZHCN", model.Entity.StoreAddressZHCN);
                pdfData.Add("USCode", model.Entity.USCode);
                pdfData.Add("OpenDate", model.Entity.OpenDate.Value.ToString("yyyy-MM-dd"));
                pdfData.Add("ClosureDate", model.Entity.ClosureDate.Value.ToString("yyyy-MM-dd"));
                pdfData.Add("ClosureNature", model.Entity.ClosureNature.ToString());
                if (model.Entity.BecauseOfReimaging.HasValue)
                {
                    pdfData.Add("BecauseOfReimaging", model.Entity.BecauseOfReimaging.Value ? "Yes" : "No");
                }
                else
                {
                    pdfData.Add("BecauseOfReimaging", "");
                }

                if (model.Entity.BecauseOfRemodel.HasValue)
                {
                    pdfData.Add("BecauseOfRemodel", model.Entity.BecauseOfRemodel.Value ? "Yes" : "No");
                }
                else
                {
                    pdfData.Add("BecauseOfRemodel", "");
                }

                if (model.Entity.BecauseOfDespute.HasValue)
                {
                    pdfData.Add("BecauseOfDespute", model.Entity.BecauseOfDespute.Value ? "Yes" : "No");
                }
                else
                {
                    pdfData.Add("BecauseOfDespute", "");
                }

                if (model.Entity.BecauseOfRedevelopment.HasValue)
                {
                    pdfData.Add("BecauseOfRedevelopment", model.Entity.BecauseOfRedevelopment.Value ? "Yes" : "No");
                }
                else
                {
                    pdfData.Add("BecauseOfRedevelopment", "");
                }

                if (model.Entity.BecauseOfPlanedClosure.HasValue)
                {
                    pdfData.Add("BecauseOfPlanedClosure", model.Entity.BecauseOfPlanedClosure.Value ? "Yes" : "No");
                }
                else
                {
                    pdfData.Add("BecauseOfPlanedClosure", "");
                }

                if (model.Entity.BecauseOfRebuild.HasValue)
                {
                    pdfData.Add("BecauseOfRebuild", model.Entity.BecauseOfRebuild.Value ? "Yes" : "No");
                }
                else
                {
                    pdfData.Add("BecauseOfRebuild", "");
                }

                pdfData.Add("BecauseOfOthers", model.Entity.BecauseOfOthers);

                if (model.Entity.PermanentCloseOpportunity.HasValue)
                {
                    pdfData.Add("PermanentCloseOpportunity", model.Entity.PermanentCloseOpportunity.Value ? "Yes" : "No");
                }
                else
                {
                    pdfData.Add("PermanentCloseOpportunity", "");
                }

                if (model.Entity.HasRelocationPlan.HasValue)
                {
                    pdfData.Add("HasRelocationPlan", model.Entity.HasRelocationPlan.Value ? "Yes" : "No");
                }
                else
                {
                    pdfData.Add("HasRelocationPlan", "");
                }

                pdfData.Add("PipelineName", model.Entity.PipelineName);
                pdfData.Add("CompensationAwarded", compensationAwards);
                pdfData.Add("Compensation", compensation);
                string pdfPath = HtmlConversionUtility.HtmlConvertToPDF(HtmlTempalteType.ClosureMemo, pdfData, null);
                EmailSendingResultType result;
                //邮件模板中的数据
                Dictionary <string, string> bodyValues = new Dictionary <string, string>();
                //邮件内容中的键值对
                //bodyValues.Add("ApplicantName", ClientCookie.UserNameENUS);//--提交人
                bodyValues.Add("StoreCode", model.Entity.USCode);
                bodyValues.Add("StoreName", model.Entity.StoreNameENUS);
                bodyValues.Add("Actor", actor.RoleNameENUS);            ////--呈递人
                bodyValues.Add("WorkflowName", Constants.Closure_Memo); ////--流程名称
                bodyValues.Add("ProjectName", Constants.Closure);       //项目名称
                var webRootUrl = ConfigurationManager.AppSettings["webHost"];
                var viewPage   = string.Format("{0}Closure/Main#/ClosureMemo/ClosureMemoView?projectId={1}",
                                               webRootUrl, model.Entity.ProjectId);
                bodyValues.Add("FormUrl", viewPage);

                //调用邮件服务发送邮件
                using (EmailServiceClient client = new EmailServiceClient())
                {
                    EmailMessage  message = new EmailMessage();
                    StringBuilder sbTo    = new StringBuilder();
                    Dictionary <string, string> attachments = new Dictionary <string, string>();
                    foreach (Employee emp in model.Receivers)
                    {
                        if (sbTo.Length > 0)
                        {
                            sbTo.Append(";");
                        }
                        if (!string.IsNullOrEmpty(emp.Mail))
                        {
                            sbTo.Append(emp.Mail);
                        }
                    }
                    if (sbTo.Length > 0)
                    {
                        sbTo.Append(";");
                    }
                    message.EmailBodyValues = bodyValues;
                    attachments.Add(pdfPath, model.Entity.USCode + " " + FlowCode.Closure_Memo + ".pdf");
                    message.AttachmentsDict = attachments;
                    message.To           = sbTo.ToString();
                    message.TemplateCode = EmailTemplateCode.GBMemoNotification;
                    result = client.SendNotificationEmail(message);
                }

                if (!result.Successful)
                {
                    return(BadRequest(result.ErrorMessage + " " + pdfPath));
                }

                //store关闭不在这里设置,需要判断project状态和closuredata
                //var store = StoreBasicInfo.GetStorInfo(model.Entity.USCode);
                //store.StoreStatus = "suoya301003";
                //store.statusName = "Closed";
                //store.Update();


                if (model.Entity.ClosureNature == ClosureNatureType.Permanent)
                {
                    //选项为永久关闭并且发送成功后关闭任务
                    McdAMEntities _db  = new McdAMEntities();
                    var           task = _db.TaskWork.FirstOrDefault(e => e.ReceiverAccount == ClientCookie.UserCode && e.Status == 0 && e.SourceCode == FlowCode.Closure && e.TypeCode == FlowCode.Closure_Memo && e.RefID == model.Entity.ProjectId);
                    if (task != null)
                    {
                        task.Status     = TaskWorkStatus.K2ProcessApproved;
                        task.FinishTime = DateTime.Now;
                        task.Url        = SiteInfo.GetProjectViewPageUrl(FlowCode.Closure_Memo, task.RefID);

                        //var enableExecutiveSummary = handler.EnableExecutiveSummary(entity.ProjectId.Value);

                        _db.TaskWork.Attach(task);
                        _db.Entry(task).State = EntityState.Modified;
                        _db.SaveChanges();

                        ProjectInfo.FinishNode(model.Entity.ProjectId, FlowCode.Closure_Memo, NodeCode.Closure_ClosureMemo_Input);
                        ProjectInfo.FinishNode(model.Entity.ProjectId, FlowCode.Closure_Memo, NodeCode.Closure_ClosureMemo_SendMemo, ProjectStatus.Finished);

                        #region Memo完成后,设定计划任务
                        var closureConsInvtChecking = new ClosureConsInvtChecking();
                        closureConsInvtChecking.GenerateConsInvtCheckingTask(model.Entity.ProjectId);

                        if (model.Entity.ClosureDate.HasValue)
                        {
                            ScheduleLog.UpdateStoreStatusSchedule(model.Entity.USCode, model.Entity.ProjectId, model.Entity.ClosureDate.Value, ClientCookie.UserCode);
                        }
                        #endregion
                    }
                    ProjectInfo.CompleteMainIfEnable(model.Entity.ProjectId);
                }
                tranScope.Complete();
                return(Ok());
            }
        }
 public ScheduleLog AddScheduleLog(ScheduleLog ScheduleLog)
 {
     db.ScheduleLog.Add(ScheduleLog);
     db.SaveChanges();
     return(ScheduleLog);
 }
        public static void StartScheduleThread(HttpContext httpContext, IConfiguration configuration = null)
        {
            try
            {
                GetConfigParams(configuration);
                SetHttpRuntimeUrl(httpContext);
                if (_scheduleThreadAnalyticDebugOn)
                {
                    ScheduleLog.Debug($"Enter StartScheduleThread() with User: [{httpContext?.User}], Enabled: [{_scheduleThreadEnabled}], WorkIntervalInMsec: [{_scheduleThreadWorkIntervalInMsec}], HttpRequestTimeOutMin: [{_scheduleThreadHttpRequestTimeOutMin}]"
                                      );
                }
                //_log.DebugFormat("Found {0} Active Schedules.", schedules.Count);
                if (!_scheduleThreadEnabled)
                {
                    if (_scheduleThreadAnalyticDebugOn)
                    {
                        ScheduleLog.Debug("Exit StartScheduleThread() !_scheduleThreadEnabled");
                    }
                    return;
                }
                HttpContext lHttpContext = httpContext ?? Utilities.Web.GetContext();
                if (_scheduleThread != null)
                {
                    if (_scheduleThreadAnalyticDebugOn)
                    {
                        ScheduleLog.Debug("_scheduleThread is already running");
                    }
                    return;
                }
                _scheduleWorker = new ScheduleWorker(Manager);
                _scheduleThread = new Thread(new ThreadStart(() =>
                {
#if NETFRAMEWORK
                    HttpContext.Current = lHttpContext;
                    _scheduleWorker.DoWork();
#else
                    using (var scope = Manager.CreateThreadServiceScope())
                    {
                        ServiceLocator.SetLocatorProvider(scope.ServiceProvider);
                        _scheduleWorker.DoWork();
                    }
#endif
                }));
                _scheduleThread.Start();
                while (!_scheduleThread.IsAlive)
                {
                    if (_scheduleThreadAnalyticDebugOn)
                    {
                        ScheduleLog.Debug("StartScheduleThread !_scheduleThread.IsAlive, wait.....");
                    }
                    Thread.Sleep(100);
                }
                if (_scheduleThreadAnalyticDebugOn)
                {
                    ScheduleLog.Debug("Exit StartScheduleThread()");
                }
            }
            catch (Exception ex)
            {
                ScheduleLog.Error("Exit StartScheduleThread()() with Exception error: " + ex.Message);
            }
        }
 public ScheduleLog UpdateScheduleLog(ScheduleLog ScheduleLog)
 {
     db.Entry(ScheduleLog).State = EntityState.Modified;
     db.SaveChanges();
     return(ScheduleLog);
 }
Ejemplo n.º 19
0
        public IHttpActionResult Send(PostMemo <TempClosureMemo> postData)
        {
            var actor = ProjectUsers.FirstOrDefault(pu => pu.ProjectId == postData.Entity.ProjectId && pu.RoleCode == ProjectUserRoleCode.AssetActor);
            Dictionary <string, string> pdfData = new Dictionary <string, string>();

            if (postData.Entity.ProjectId.ToLower().IndexOf("rebuild") != -1)
            {
                pdfData.Add("WorkflowName", "Rebuild");
                pdfData.Add("ClosureNature", "Temporary");
            }
            else if (postData.Entity.ProjectId.ToLower().IndexOf("majorlease") != -1)
            {
                pdfData.Add("WorkflowName", "MajorLease");
                pdfData.Add("ClosureNature", "Temporary");
            }
            else if (postData.Entity.ProjectId.ToLower().IndexOf("reimage") != -1)
            {
                pdfData.Add("WorkflowName", "Reimage");
                pdfData.Add("ClosureNature", "Temporary");
            }
            else if (postData.Entity.ProjectId.ToLower().IndexOf("renewal") != -1)
            {
                pdfData.Add("WorkflowName", "Renewal");
                pdfData.Add("ClosureNature", "Temporary");
            }
            else
            {
                pdfData.Add("WorkflowName", "TempClosure");
                pdfData.Add("ClosureNature", postData.Entity.ClosureNature.ToString());
            }
            pdfData.Add("ProjectID", postData.Entity.ProjectId);
            pdfData.Add("RegionNameENUS", postData.Entity.RegionNameENUS);
            pdfData.Add("RegionNameZHCN", postData.Entity.RegionNameZHCN);
            pdfData.Add("MarketNameENUS", postData.Entity.MarketNameENUS);
            pdfData.Add("MarketNameZHCN", postData.Entity.MarketNameZHCN);
            pdfData.Add("ProvinceNameENUS", postData.Entity.ProvinceNameENUS);
            pdfData.Add("ProvinceNameZHCN", postData.Entity.ProvinceNameZHCN);
            pdfData.Add("CityNameENUS", postData.Entity.CityNameENUS);
            pdfData.Add("CityNameZHCN", postData.Entity.CityNameZHCN);
            pdfData.Add("StoreNameENUS", postData.Entity.StoreNameENUS);
            pdfData.Add("StoreNameZHCN", postData.Entity.StoreNameZHCN);
            pdfData.Add("StoreAddressENUS", postData.Entity.StoreAddressENUS);
            pdfData.Add("StoreAddressZHCN", postData.Entity.StoreAddressZHCN);
            pdfData.Add("USCode", postData.Entity.USCode);
            pdfData.Add("OpenDate", postData.Entity.OpenDate.HasValue ? postData.Entity.OpenDate.Value.ToString("yyyy-MM-dd") : "");
            pdfData.Add("ClosureDate", postData.Entity.ClosureDate.HasValue ? postData.Entity.ClosureDate.Value.ToString("yyyy-MM-dd") : "");

            pdfData.Add("BecauseOfReimaging", postData.Entity.BecauseOfReimaging ? "Yes" : "No");
            pdfData.Add("BecauseOfRemodel", postData.Entity.BecauseOfRemodel ? "Yes" : "No");
            pdfData.Add("BecauseOfDespute", postData.Entity.BecauseOfDespute ? "Yes" : "No");
            pdfData.Add("BecauseOfRedevelopment", postData.Entity.BecauseOfRedevelopment ? "Yes" : "No");
            pdfData.Add("BecauseOfPlanedClosure", postData.Entity.BecauseOfPlanedClosure ? "Yes" : "No");
            pdfData.Add("BecauseOfRebuild", postData.Entity.BecauseOfRebuild ? "Yes" : "No");
            pdfData.Add("BecauseOfOthers", postData.Entity.BecauseOfOthers);
            pdfData.Add("PermanentCloseOpportunity", postData.Entity.PermanentCloseOpportunity ? "Yes" : "No");
            pdfData.Add("HasRelocationPlan", postData.Entity.HasRelocationPlan ? "Yes" : "No");
            pdfData.Add("PipelineName", postData.Entity.PipelineName);
            pdfData.Add("CompensationAwarded", postData.Entity.CompensationAwarded ? "Yes" : "No");
            pdfData.Add("Compensation", postData.Entity.Compensation.HasValue ? postData.Entity.Compensation.Value.ToString("N") : "");
            string pdfPath = HtmlConversionUtility.HtmlConvertToPDF(HtmlTempalteType.ClosureMemo, pdfData, null);
            EmailSendingResultType result;
            //邮件模板中的数据
            Dictionary <string, string> bodyValues = new Dictionary <string, string>();

            //邮件内容中的键值对
            bodyValues.Add("ApplicantName", ClientCookie.UserNameENUS);//--提交人
            bodyValues.Add("StoreCode", postData.Entity.USCode);
            bodyValues.Add("StoreName", postData.Entity.StoreNameENUS);
            bodyValues.Add("Actor", actor.UserNameENUS);////--呈递人


            string viewPage = string.Format("{0}/TempClosure/Main#/ClosureMemo/Process/View?projectId={1}",
                                            ConfigurationManager.AppSettings["webHost"], postData.Entity.ProjectId);

            if (postData.Entity.ProjectId.ToLower().IndexOf("rebuild") != -1)
            {
                bodyValues.Add("WorkflowName", Constants.TempClosure_Memo); ////--流程名称
                bodyValues.Add("ProjectName", Constants.Rebuild);           //项目名称
                viewPage = string.Format("{0}/Rebuild/Main#/TempClosureMemo/View?projectId={1}",
                                         ConfigurationManager.AppSettings["webHost"], postData.Entity.ProjectId);
            }
            else if (postData.Entity.ProjectId.ToLower().IndexOf("majorlease") != -1)
            {
                bodyValues.Add("WorkflowName", Constants.Closure_Memo); ////--流程名称
                bodyValues.Add("ProjectName", Constants.MajorLease);    //项目名称
                viewPage = string.Format("{0}/MajorLease/Main#/ClosureMemo/View?projectId={1}",
                                         ConfigurationManager.AppSettings["webHost"], postData.Entity.ProjectId);
            }
            else if (postData.Entity.ProjectId.ToLower().IndexOf("reimage") != -1)
            {
                bodyValues.Add("WorkflowName", Constants.TempClosure_Memo); ////--流程名称
                bodyValues.Add("ProjectName", Constants.Reimage);           //项目名称
                viewPage = string.Format("{0}/Reimage/Main#/TempClosureMemo/View?projectId={1}",
                                         ConfigurationManager.AppSettings["webHost"], postData.Entity.ProjectId);
            }
            else if (postData.Entity.ProjectId.ToLower().IndexOf("renewal") != -1)
            {
                bodyValues.Add("WorkflowName", Constants.Closure_Memo); ////--流程名称
                bodyValues.Add("ProjectName", Constants.Renewal);       //项目名称
                viewPage = string.Format("{0}/Renewal/Main#/ClosureMemo/View?projectId={1}",
                                         ConfigurationManager.AppSettings["webHost"], postData.Entity.ProjectId);
            }
            else if (postData.Entity.ProjectId.ToLower().IndexOf("closure") != -1)
            {
                bodyValues.Add("WorkflowName", Constants.Closure_Memo); ////--流程名称
                bodyValues.Add("ProjectName", Constants.Closure);       //项目名称
            }
            else
            {
                bodyValues.Add("WorkflowName", Constants.Closure_Memo); ////--流程名称
                bodyValues.Add("ProjectName", Constants.TempClosure);   //项目名称
            }
            bodyValues.Add("FormUrl", viewPage);

            if (postData.Entity.ProjectId.ToLower().Contains("tpcls"))
            {
                //调用邮件服务发送邮件
                using (EmailServiceClient client = new EmailServiceClient())
                {
                    EmailMessage  message = new EmailMessage();
                    StringBuilder sbTo    = new StringBuilder();
                    StringBuilder sbCC    = new StringBuilder();
                    Dictionary <string, string> attachments = new Dictionary <string, string>();
                    //主送人
                    var actorEmployee = Employee.GetEmployeeByCode(actor.UserAccount);
                    if (actorEmployee != null)
                    {
                        sbTo.Append(actorEmployee.Mail + ";");
                    }
                    var cooList = Employee.GetStoreEmployeesByRole(postData.Entity.USCode, RoleCode.Coordinator);
                    foreach (var coo in cooList)
                    {
                        sbTo.Append(coo.Mail + ";");
                    }
                    var mamList = Employee.GetStoreEmployeesByRole(postData.Entity.USCode, RoleCode.Market_Asset_Mgr);
                    foreach (var mam in mamList)
                    {
                        sbTo.Append(mam.Mail + ";");
                    }
                    var ramList = Employee.GetStoreEmployeesByRole(postData.Entity.USCode, RoleCode.Regional_Asset_Mgr);
                    foreach (var ram in ramList)
                    {
                        sbTo.Append(ram.Mail + ";");
                    }
                    var mcamList = Employee.GetStoreEmployeesByRole(postData.Entity.USCode, RoleCode.MCCL_Asset_Mgr);
                    foreach (var mcam in mcamList)
                    {
                        sbTo.Append(mcam.Mail + ";");
                    }

                    //抄送人
                    if (postData.Receivers != null)
                    {
                        foreach (Employee emp in postData.Receivers)
                        {
                            if (sbCC.Length > 0)
                            {
                                sbCC.Append(";");
                            }
                            if (!string.IsNullOrEmpty(emp.Mail))
                            {
                                sbCC.Append(emp.Mail);
                            }
                        }
                    }
                    if (sbCC.Length > 0)
                    {
                        sbCC.Append(";");
                    }
                    message.EmailBodyValues = bodyValues;
                    attachments.Add(pdfPath, postData.Entity.USCode + " " + Constants.TempClosure_Memo + ".pdf");
                    message.AttachmentsDict = attachments;
                    message.To           = sbTo.ToString();
                    message.CC           = sbCC.ToString();
                    message.TemplateCode = EmailTemplateCode.GBMemoNotification;
                    result = client.SendNotificationEmail(message);
                }
            }
            else
            {
                using (EmailServiceClient client = new EmailServiceClient())
                {
                    EmailMessage  message = new EmailMessage();
                    StringBuilder sbTo    = new StringBuilder();
                    StringBuilder sbCC    = new StringBuilder();
                    Dictionary <string, string> attachments = new Dictionary <string, string>();

                    if (postData.Receivers != null)
                    {
                        foreach (Employee emp in postData.Receivers)
                        {
                            if (sbCC.Length > 0)
                            {
                                sbTo.Append(";");
                            }
                            if (!string.IsNullOrEmpty(emp.Mail))
                            {
                                sbTo.Append(emp.Mail);
                            }
                        }
                    }
                    if (sbCC.Length > 0)
                    {
                        sbCC.Append(";");
                    }
                    message.EmailBodyValues = bodyValues;
                    string strTitle = FlowCode.TempClosure_ClosureMemo;
                    if (postData.Entity.ProjectId.ToLower().IndexOf("rebuild") >= 0)
                    {
                        strTitle = FlowCode.Rebuild_TempClosureMemo;
                    }
                    else if (postData.Entity.ProjectId.ToLower().IndexOf("reimage") >= 0)
                    {
                        strTitle = FlowCode.Reimage_TempClosureMemo;
                    }
                    else if (postData.Entity.ProjectId.ToLower().IndexOf("majorlease") >= 0)
                    {
                        strTitle = "MajorLease_ClosureMemo";
                    }

                    attachments.Add(pdfPath, postData.Entity.USCode + " " + strTitle + ".pdf");
                    message.AttachmentsDict = attachments;
                    message.To           = sbTo.ToString();
                    message.TemplateCode = EmailTemplateCode.GBMemoNotification;
                    result = client.SendNotificationEmail(message);
                }
            }

            if (!result.Successful)
            {
                return(BadRequest(result.ErrorMessage + " " + pdfPath));
            }
            using (TransactionScope tranScope = new TransactionScope())
            {
                postData.Entity.Save();
                ProjectInfo projectInfo = null;
                if (postData.Entity.ProjectId.ToLower().IndexOf("rebuild") >= 0)
                {
                    projectInfo = ProjectInfo.Get(postData.Entity.ProjectId, FlowCode.Rebuild_TempClosureMemo);
                }
                else if (postData.Entity.ProjectId.ToLower().IndexOf("reimage") >= 0)
                {
                    projectInfo = ProjectInfo.Get(postData.Entity.ProjectId, FlowCode.Reimage_TempClosureMemo);
                }
                else if (postData.Entity.ProjectId.ToLower().IndexOf("majorlease") >= 0 ||
                         postData.Entity.ProjectId.ToLower().IndexOf("renewal") >= 0)
                {
                    postData.Entity.Submit();
                }
                else
                {
                    projectInfo = ProjectInfo.Get(postData.Entity.ProjectId, FlowCode.TempClosure_ClosureMemo);
                    var tempClosure = TempClosureInfo.Get(postData.Entity.ProjectId);
                    if (postData.Entity.ClosureDate != null)
                    {
                        tempClosure.ActualTempClosureDate = postData.Entity.ClosureDate.Value;
                    }
                    tempClosure.Update();
                }
                if (projectInfo != null && projectInfo.Status == ProjectStatus.UnFinish)
                {
                    postData.Entity.Submit();

                    if (postData.Entity.ProjectId.ToLower().Contains("tpcls"))
                    {
                        if (postData.Entity.ClosureDate.HasValue)
                        {
                            ScheduleLog.UpdateStoreStatusSchedule(postData.Entity.USCode, postData.Entity.ProjectId, postData.Entity.ClosureDate.Value, ClientCookie.UserCode);
                        }
                    }
                }
                tranScope.Complete();
            }
            return(Ok());
        }
 public async Task <ScheduleLog> UpdateScheduleLogAsync(ScheduleLog schedulelog)
 {
     return(await http.PutJsonAsync <ScheduleLog>(apiurl + "/" + schedulelog.ScheduleLogId.ToString(), schedulelog));
 }
        /// <summary>
        /// 新しい通知スケジュールを作成します
        /// </summary>
        public async Task <IHttpActionResult> Post(ScheduleFormModel data)
        {
            // 送信されたデータが正しいか検証する
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var notifications = new List <Notification>();

            // 送信するペイロードを作成
            if (data.Windows > 0)
            {
                notifications.Add(Payloads.Windows.Create(data.Windows, data.Message));
            }

            if (data.WindowsPhone > 0)
            {
                notifications.Add(Payloads.WindowsPhone.Create(data.WindowsPhone, data.Message));
            }

            if (data.Apple > 0)
            {
                notifications.Add(Payloads.Apple.Create(data.Apple, data.Message));
            }

            if (data.Android > 0)
            {
                notifications.Add(Payloads.Android.Create(data.Android, data.Message));
            }

            // 送信先が 1 つもない場合にはエラー
            if (notifications.Count == 0)
            {
                return(BadRequest("Required Platform select."));
            }

            // 通知ハブへ通知リクエストを非同期で送信
            var tasks = notifications.Select(p => _client.ScheduleNotificationAsync(p, data.ScheduledOn.Value, data.TagExpression));

            // 全ての通知リクエストの完了を待機する
            var results = await Task.WhenAll(tasks);

            foreach (var result in results)
            {
                // スケジュールログを DB に保存
                var scheduleLog = new ScheduleLog
                {
                    NotificationId = result.ScheduledNotificationId,
                    Platform       = result.Payload.GetPlatform(),
                    Message        = data.Message,
                    TagExpression  = data.TagExpression,
                    ScheduledOn    = data.ScheduledOn.Value,
                    CreatedOn      = DateTimeOffset.UtcNow
                };

                _context.ScheduleLogs.Add(scheduleLog);
            }

            await _context.SaveChangesAsync();

            return(Ok());
        }
 public async Task <ScheduleLog> AddScheduleLogAsync(ScheduleLog schedulelog)
 {
     return(await http.PostJsonAsync <ScheduleLog>(apiurl, schedulelog));
 }