Exemplo n.º 1
0
		public override void SetUp()
		{
			base.SetUp();

			mockJobStore = Mocks.CreateMock<IJobStore>();
			mockJobRunner = Mocks.CreateMock<IJobRunner>();
			mockLogger = Mocks.CreateMock<ILogger>();
			mockTrigger = Mocks.PartialMock<Trigger>();
			scheduler = new DefaultScheduler(mockJobStore, mockJobRunner);

			dummyJobData = new JobData();
			dummyJobSpec = new JobSpec("foo", "bar", "key", mockTrigger);
			dummyJobDetails = new JobDetails(dummyJobSpec, DateTime.UtcNow);

			isWoken = false;

			// Ensure the scheduler is initialized.
			mockJobStore.RegisterScheduler(scheduler.Guid, scheduler.Name);
			Mocks.Replay(mockJobStore);
			scheduler.Initialize();
			Mocks.Verify(mockJobStore);
			Mocks.BackToRecord(mockJobStore);

			mockJobStore.UnregisterScheduler(scheduler.Guid);

			// Create a separate uninitialized scheduler for certain tests.
			uninitializedScheduler = new DefaultScheduler(mockJobStore, mockJobRunner);
		}
Exemplo n.º 2
0
        public override void SetUp()
        {
            base.SetUp();

            scheduler = Mocks.CreateMock<IScheduler>();
            logger = Mocks.CreateMock<ILogger>();
            jobSpec = new JobSpec("abc", "some job", "with.this.key", PeriodicTrigger.CreateDailyTrigger(DateTime.UtcNow));
            jobData = new JobData();
            Mocks.ReplayAll();
        }
Exemplo n.º 3
0
        public static void AreEqual(JobData expected, JobData actual)
        {
            if (expected == null)
            {
                Assert.IsNull(actual);
                return;
            }

            Assert.IsNotNull(actual);
            CollectionAssert.AreEqual(expected.State, actual.State);
        }
Exemplo n.º 4
0
		public override void SetUp()
		{
			base.SetUp();

			dummyJobSpec = new JobSpec("job", "test", "dummy", PeriodicTrigger.CreateOneShotTrigger(DateTime.UtcNow));
			dummyJobData = new JobData();
			dummyJobData.State["key"] = "value";

			jobStore = CreateJobStore();
			jobStore.RegisterScheduler(SchedulerGuid, SchedulerName);
		}
        protected override void InternalProcess(User user, Group @group, JobData jobData)
        {
            GroupEnumerate groupEnumerate = new GroupEnumerate(@group.Id.Value);

            foreach (Group g in groupEnumerate)
            {
                var lookups = g.ExtendedAttributes.ToLookup(attribute => attribute.Key, val => (IExtendedAttribute)val);

                string setting = lookups.GetString("DefaultDigestSetting", "unset");

                if ("daily".Equals(setting))
                {
                    PublicApi.Users.RunAsUser(user.Id.Value, () =>
                    {
                        EmailDigestSubscription subscription = PublicApi.EmailDigestSubscriptions.GetByGroup(@group.Id.Value);
                        if (subscription != null)
                        {
                            PublicApi.EmailDigestSubscriptions.Update(subscription.Id.Value, 1);
                        }
                        else
                        {
                            PublicApi.EmailDigestSubscriptions.Create("group", @group.Id.Value, 1);
                        }
                    });
                }
                else if ("weekly".Equals(setting))
                {
                    PublicApi.Users.RunAsUser(user.Id.Value, () =>
                    {
                        EmailDigestSubscription subscription = PublicApi.EmailDigestSubscriptions.GetByGroup(@group.Id.Value);
                        if (subscription != null)
                        {
                            PublicApi.EmailDigestSubscriptions.Update(subscription.Id.Value, 7);
                        }
                        else
                        {
                            PublicApi.EmailDigestSubscriptions.Create("group", @group.Id.Value, 7);
                        }
                    });
                }
                else if("off".Equals(setting))
                {
                    PublicApi.Users.RunAsUser(user.Id.Value, () =>
                    {
                        EmailDigestSubscription subscription = PublicApi.EmailDigestSubscriptions.GetByGroup(@group.Id.Value);
                        if (subscription != null)
                        {
                            PublicApi.EmailDigestSubscriptions.Delete(subscription.Id.Value);
                        }
                    });
                }
            }
        }
Exemplo n.º 6
0
		/// <summary>
		/// Creates a job execution context.
		/// </summary>
		/// <param name="scheduler">The scheduler that is managing the job</param>
		/// <param name="logger">The logger to use for logging job progress</param>
		/// <param name="jobSpec">The job's specification</param>
		/// <param name="jobData">The job state data, or null if none</param>
		/// <exception cref="ArgumentNullException">Thrown if <paramref name="scheduler"/>,
		/// <paramref name="logger"/> or <paramref name="jobSpec"/> is null</exception>
		public JobExecutionContext(IScheduler scheduler, ILogger logger, JobSpec jobSpec, JobData jobData)
		{
			if (scheduler == null)
				throw new ArgumentNullException("scheduler");
			if (logger == null)
				throw new ArgumentNullException("logger");
			if (jobSpec == null)
				throw new ArgumentNullException("jobSpec");

			this.scheduler = scheduler;
			this.logger = logger;
			this.jobSpec = jobSpec;
			this.jobData = jobData;
		}
        protected override void InternalProcess(User user, Group @group, JobData jobData)
        {
            int? blogId = jobData.Data.ContainsKey("BlogId") ? int.Parse(jobData.Data["BlogId"]) : default(int?);

            BlogEnumerate blogEnumerate = new BlogEnumerate(@group.Id.Value, blogId);

            foreach (Blog blog in blogEnumerate)
            {
                var lookups = blog.ExtendedAttributes.ToLookup(attribute => attribute.Key, val => (IExtendedAttribute)val);

                string setting = lookups.GetString("DefaultSubscriptionSetting", "unset");

                SetSubscriptionStatus(blog.ApplicationId, PublicApi.Blogs.ApplicationTypeId, setting, user.Id.Value);
            }
        }
Exemplo n.º 8
0
        public void ClonePerformsADeepCopy(bool useGenericClonable)
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            JobData jobData = new JobData(dict);

            JobData clone = useGenericClonable
                                ? jobData.Clone()
                                :
                                    (JobData) ((ICloneable) jobData).Clone();

            Assert.AreNotSame(jobData, clone);
            Assert.AreNotSame(dict, clone.State);

            JobAssert.AreEqual(jobData, clone);
        }
        protected override void InternalProcess(User user, Group @group, JobData jobData)
        {
            int? forumId = jobData.Data.ContainsKey("ForumId") ? int.Parse(jobData.Data["ForumId"]) : default(int?);

            ForumEnumerate forumEnumerate = new ForumEnumerate(@group.Id.Value, forumId);

            foreach (Forum forum in forumEnumerate)
            {
                var lookups = forum.ExtendedAttributes.ToLookup(attribute => attribute.Key, val => (IExtendedAttribute)val);

                string setting = lookups.GetString("DefaultSubscriptionSetting", "unset");

                SetSubscriptionStatus(forum.ApplicationId, PublicApi.Forums.ApplicationTypeId, setting, user.Id.Value);
            }
        }
        public void Process(JobData jobData)
        {
            GroupId = jobData.Data.ContainsKey("GroupId") ? int.Parse(jobData.Data["GroupId"]) : default(int?);
            UserName = jobData.Data.ContainsKey("UserName") ? jobData.Data["UserName"] : null;

            var userEnumerator = new UserEnumerate(UserName, GroupId);

            var groupEnumerate = new GroupEnumerate(GroupId);

            foreach (User user in userEnumerator)
            {
                foreach (Group group in groupEnumerate)
                {
                    InternalProcess(user, group, jobData);
                }
            }
        }
 public void Execute(JobData jobData)
 {
     List<ISubscriptionUpdateProcessor> processors = SubscriptionUpdatProcessingFactory.GetProcessors(jobData);
     foreach (ISubscriptionUpdateProcessor p in processors)
     {
         try
         {
             p.Process(jobData);
         }
         catch (Exception e) 
         { 
             StringBuilder msg = new StringBuilder(p.Name);
             msg.Append(" threw Exception ");
             msg.Append(e.ToString());
             new CSException(CSExceptionType.UnknownError, msg.ToString()).Log();
         }
     }
 }
 /// <summary>
 /// This is the real function that should be implemented to perform the job in a STA
 /// thread, once at a time, etc.
 /// </summary>
 /// <param name="job"></param>
 /// <returns></returns>
 protected abstract String OnRunJob(JobData job);
Exemplo n.º 13
0
 public Job(SJob data)
 {
     _Data = new JobData(data);
 }
Exemplo n.º 14
0
 static SearchController()
 {
     jobData = JobData.GetInstance();
 }
Exemplo n.º 15
0
        /// <summary>
        /// 傳入 JobData 物件,從 JobData 指定的 NameSpace & ClassName 到 Assembly 中取得並回傳 MethodInfo.
        /// </summary>
        /// <param name="Job">JobData 物件</param>
        public static Tuple <MethodInfo, object, LogAttributeData <WriteLogAttribute>, LogAttributeData <WriteExceptionLogAttribute>, LogAttributeData <ErrorLevelAttribute> > GetExecuteJobMethod(JobData Job)
        {
            MethodInfo result         = null;
            object     jobClassObject = null;
            LogAttributeData <WriteLogAttribute>          writeLogAttr   = new LogAttributeData <WriteLogAttribute>();
            LogAttributeData <WriteExceptionLogAttribute> writeExAttr    = new LogAttributeData <WriteExceptionLogAttribute>();
            LogAttributeData <ErrorLevelAttribute>        errorLevelAttr = new LogAttributeData <ErrorLevelAttribute>();

            string appPath = string.Empty;

            string nameSapce = string.Empty;

            try
            {
                Assembly ExecuteAssembly = Assembly.GetExecutingAssembly();
                appPath = Path.GetDirectoryName(ExecuteAssembly.Location);

                dllPath = string.Format("{0}.dll", Job.DLLName);

                // 判斷上傳的實體路徑下是否有此文件,沒有提示錯誤信息
                if (!System.IO.File.Exists(Path.Combine(appPath, dllPath)))
                {
                    throw new JobDLLNotFoundException(string.Format("The {0} DLL is not exist!", dllPath))
                          {
                              Datetime   = DateTime.Now,
                              MethodInfo = string.Format("DLLPath={0}, DLLName={1}, NameSpace={2}, ClassName={3}", dllPath, Job.DLLName, Job.NameSpace, Job.ClassName)
                          };
                }
                else
                {
                    //要讀取的 DLL 路徑.
                    string   assPath       = Path.Combine(appPath, dllPath);
                    string   dllConfigPath = string.Format("{0}.config", assPath);
                    Assembly ass           = null;

                    //先判斷是否有這個 DLL 的 dll.config
                    if (File.Exists(dllConfigPath))
                    {
                        var resultValue = GetCustomConfig(assPath, dllConfigPath, "connectionStrings");
                        ass = resultValue.Item1;
                    }
                    else
                    {
                        //載入指定路徑中的 Assembly.
                        ass = Assembly.LoadFile(assPath);
                    }

                    if (ass != null)
                    {
                        Type magicType   = ass.GetType(string.Format(".", Job.NameSpace, Job.ClassName));
                        var  resultValue = Common(ass, Job);
                        result         = resultValue.Item1;
                        jobClassObject = resultValue.Item2;
                        writeLogAttr   = resultValue.Item3;
                        writeExAttr    = resultValue.Item4;
                        errorLevelAttr = resultValue.Item5;
                    }
                    else
                    {
                        throw new JobDLLNotFoundException(string.Format("The {0} DLL is not exist!", dllPath))
                              {
                                  Datetime   = DateTime.Now,
                                  MethodInfo = string.Format("DLLPath={0}, DLLName={1}, NameSpace={2}, ClassName={3}", dllPath, Job.DLLName, Job.NameSpace, Job.ClassName)
                              };
                    }
                }
            }
            catch (Exception ex)
            {
                throw new JobDLLNotFoundException(ex.Message)
                      {
                          Datetime   = DateTime.Now,
                          MethodInfo = string.Format("DLLPath={0}, DLLName={1}, NameSpace={2}, ClassName={3}", dllPath, Job.DLLName, Job.NameSpace, Job.ClassName)
                      };
            }

            return(Tuple.Create(result, jobClassObject, writeLogAttr, writeExAttr, errorLevelAttr));
        }
Exemplo n.º 16
0
 public void ConstructorWithDictionarySetsProperties()
 {
     Dictionary<string, object> dict = new Dictionary<string, object>();
     JobData jobData = new JobData(dict);
     Assert.AreSame(dict, jobData.State);
 }
 public static List<ISubscriptionUpdateProcessor> GetProcessors(JobData jobData)
 {
     List<ISubscriptionUpdateProcessor> retval = PluginManager.Get<ISubscriptionUpdateProcessor>().Where(p => p.CanProcess(jobData)).ToList();
     return retval;
 }
        public void GetExecutionProgressTask()
        {
            _mediaContext.Jobs.Create("Name");
             var remoteJob = _mediaContext.Jobs.First();
             ((JobData)remoteJob).State = (int)JobState.Canceled;

             var data = new JobData { Id = "1" };
             bool stateChanged = false;
             data.StateChanged += (object sender, JobStateChangedEventArgs e) => stateChanged = true;

             data.SetMediaContext(_mediaContext);

             Task t = data.GetExecutionProgressTask(CancellationToken.None);

             Thread.Sleep(1000);

             data.Id = remoteJob.Id;

             t.Wait();

             Assert.IsTrue(stateChanged);
        }
Exemplo n.º 19
0
    public static void DownloadUnit(UnitParam unit, JobData[] jobs = null)
    {
        // ISSUE: object of a compiler-generated type is created
        // ISSUE: variable of a compiler-generated type
        DownloadUtility.\u003CDownloadUnit\u003Ec__AnonStorey1ED unitCAnonStorey1Ed = new DownloadUtility.\u003CDownloadUnit\u003Ec__AnonStorey1ED();
        // ISSUE: reference to a compiler-generated field
        unitCAnonStorey1Ed.unit = unit;
        // ISSUE: reference to a compiler-generated field
        if (unitCAnonStorey1Ed.unit == null)
        {
            return;
        }
        // ISSUE: reference to a compiler-generated field
        CharacterDB.Character character = CharacterDB.FindCharacter(unitCAnonStorey1Ed.unit.model);
        if (character == null)
        {
            return;
        }
        GameManager instance = MonoSingleton <GameManager> .Instance;

        // ISSUE: reference to a compiler-generated field
        if (unitCAnonStorey1Ed.unit.jobsets != null)
        {
            // ISSUE: reference to a compiler-generated field
            for (int index = 0; index < unitCAnonStorey1Ed.unit.jobsets.Length; ++index)
            {
                // ISSUE: reference to a compiler-generated field
                for (JobSetParam jobSetParam = instance.GetJobSetParam((string)unitCAnonStorey1Ed.unit.jobsets[index]); jobSetParam != null; jobSetParam = string.IsNullOrEmpty(jobSetParam.jobchange) ? (JobSetParam)null : instance.GetJobSetParam(jobSetParam.jobchange))
                {
                    JobParam jobParam = instance.GetJobParam(jobSetParam.job);
                    // ISSUE: reference to a compiler-generated field
                    SkillParam skillParam = string.IsNullOrEmpty(jobParam.atkskill[0]) ? instance.MasterParam.GetSkillParam(jobParam.atkskill[(int)unitCAnonStorey1Ed.unit.element]) : instance.MasterParam.GetSkillParam(jobParam.atkskill[0]);
                    if (skillParam != null)
                    {
                        SkillSequence sequence = SkillSequence.FindSequence(skillParam.motion);
                        if (sequence != null && !string.IsNullOrEmpty(sequence.SkillAnimation.Name) && index < character.Jobs.Count)
                        {
                            DownloadUtility.PrepareUnitAnimation(character.Jobs[index], sequence.SkillAnimation.Name, false, (JobParam)null);
                        }
                    }
                    DownloadUtility.DownloadJobEquipment(jobParam);
                    ArtifactParam artifactParam = MonoSingleton <GameManager> .GetInstanceDirect().MasterParam.GetArtifactParam(jobParam.artifact);

                    if (artifactParam != null)
                    {
                        DownloadUtility.DownloadArtifact(artifactParam);
                    }
                    int artifactSlotIndex = JobData.GetArtifactSlotIndex(ArtifactTypes.Arms);
                    if (jobs != null)
                    {
                        foreach (JobData job in jobs)
                        {
                            if (job != null)
                            {
                                // ISSUE: object of a compiler-generated type is created
                                // ISSUE: variable of a compiler-generated type
                                DownloadUtility.\u003CDownloadUnit\u003Ec__AnonStorey1EC unitCAnonStorey1Ec = new DownloadUtility.\u003CDownloadUnit\u003Ec__AnonStorey1EC();
                                List <ArtifactData> artifacts = MonoSingleton <GameManager> .GetInstanceDirect().Player.Artifacts;

                                // ISSUE: reference to a compiler-generated field
                                unitCAnonStorey1Ec.uniqId = job.Artifacts[artifactSlotIndex];
                                // ISSUE: reference to a compiler-generated method
                                ArtifactData artifactData = artifacts.Find(new Predicate <ArtifactData>(unitCAnonStorey1Ec.\u003C\u003Em__1B4));
                                if (artifactData != null)
                                {
                                    DownloadUtility.DownloadArtifact(artifactData.ArtifactParam);
                                }
                            }
                        }
                    }
                    else
                    {
                        DownloadUtility.DownloadArtifact(instance.MasterParam.GetArtifactParam(jobParam.artifact));
                    }
                    // ISSUE: reference to a compiler-generated field
                    AssetManager.PrepareAssets(AssetPath.UnitImage(unitCAnonStorey1Ed.unit, jobSetParam.job));
                    // ISSUE: reference to a compiler-generated field
                    AssetManager.PrepareAssets(AssetPath.UnitImage2(unitCAnonStorey1Ed.unit, jobSetParam.job));
                    // ISSUE: reference to a compiler-generated field
                    AssetManager.PrepareAssets(AssetPath.UnitIconSmall(unitCAnonStorey1Ed.unit, jobSetParam.job));
                    // ISSUE: reference to a compiler-generated field
                    AssetManager.PrepareAssets(AssetPath.UnitIconMedium(unitCAnonStorey1Ed.unit, jobSetParam.job));
                    // ISSUE: reference to a compiler-generated field
                    AssetManager.PrepareAssets(AssetPath.UnitEyeImage(unitCAnonStorey1Ed.unit, jobSetParam.job));
                }
            }
            // ISSUE: reference to a compiler-generated field
            JobSetParam[] changeJobSetParam = instance.GetClassChangeJobSetParam(unitCAnonStorey1Ed.unit.iname);
            if (changeJobSetParam != null && changeJobSetParam.Length > 0)
            {
                for (int index = 0; index < changeJobSetParam.Length; ++index)
                {
                    JobSetParam jobSetParam = changeJobSetParam[index];
                    if (jobSetParam != null)
                    {
                        JobParam      jobParam      = instance.GetJobParam(jobSetParam.job);
                        ArtifactParam artifactParam = MonoSingleton <GameManager> .GetInstanceDirect().MasterParam.GetArtifactParam(jobParam.artifact);

                        if (artifactParam != null)
                        {
                            DownloadUtility.DownloadArtifact(artifactParam);
                        }
                        // ISSUE: reference to a compiler-generated field
                        SkillParam skillParam = string.IsNullOrEmpty(jobParam.atkskill[0]) ? instance.MasterParam.GetSkillParam(jobParam.atkskill[(int)unitCAnonStorey1Ed.unit.element]) : instance.MasterParam.GetSkillParam(jobParam.atkskill[0]);
                        if (skillParam != null)
                        {
                            SkillSequence sequence = SkillSequence.FindSequence(skillParam.motion);
                            if (sequence != null && !string.IsNullOrEmpty(sequence.SkillAnimation.Name))
                            {
                                DownloadUtility.PrepareUnitAnimation(character.Jobs[index], sequence.SkillAnimation.Name, false, (JobParam)null);
                            }
                        }
                    }
                }
            }
        }
        for (int index = 0; index < character.Jobs.Count; ++index)
        {
            CharacterDB.Job job = character.Jobs[index];
            DownloadUtility.PrepareUnitModels(job);
            DownloadUtility.PrepareUnitAnimation(job, "unit_info_idle0", true, (JobParam)null);
            DownloadUtility.PrepareUnitAnimation(job, "unit_info_act0", true, (JobParam)null);
        }
        // ISSUE: reference to a compiler-generated field
        AssetManager.PrepareAssets("CHM/Home_" + unitCAnonStorey1Ed.unit.model + "_walk0");
        // ISSUE: reference to a compiler-generated field
        if (unitCAnonStorey1Ed.unit.skins != null)
        {
            List <ArtifactParam> artifacts = MonoSingleton <GameManager> .GetInstanceDirect().MasterParam.Artifacts;

            // ISSUE: object of a compiler-generated type is created
            // ISSUE: variable of a compiler-generated type
            DownloadUtility.\u003CDownloadUnit\u003Ec__AnonStorey1EE unitCAnonStorey1Ee = new DownloadUtility.\u003CDownloadUnit\u003Ec__AnonStorey1EE();
            // ISSUE: reference to a compiler-generated field
            unitCAnonStorey1Ee.\u003C\u003Ef__ref\u0024493 = unitCAnonStorey1Ed;
            // ISSUE: reference to a compiler-generated field
            // ISSUE: reference to a compiler-generated field
            // ISSUE: reference to a compiler-generated field
            // ISSUE: reference to a compiler-generated field
            for (unitCAnonStorey1Ee.i = 0; unitCAnonStorey1Ee.i < unitCAnonStorey1Ed.unit.skins.Length; ++unitCAnonStorey1Ee.i)
            {
                // ISSUE: reference to a compiler-generated method
                ArtifactParam skin = artifacts.Find(new Predicate <ArtifactParam>(unitCAnonStorey1Ee.\u003C\u003Em__1B5));
                if (skin != null)
                {
                    // ISSUE: reference to a compiler-generated field
                    AssetManager.PrepareAssets(AssetPath.UnitSkinImage(unitCAnonStorey1Ed.unit, skin, (string)null));
                    // ISSUE: reference to a compiler-generated field
                    AssetManager.PrepareAssets(AssetPath.UnitSkinImage2(unitCAnonStorey1Ed.unit, skin, (string)null));
                    // ISSUE: reference to a compiler-generated field
                    AssetManager.PrepareAssets(AssetPath.UnitSkinIconSmall(unitCAnonStorey1Ed.unit, skin, (string)null));
                    // ISSUE: reference to a compiler-generated field
                    AssetManager.PrepareAssets(AssetPath.UnitSkinIconMedium(unitCAnonStorey1Ed.unit, skin, (string)null));
                    // ISSUE: reference to a compiler-generated field
                    AssetManager.PrepareAssets(AssetPath.UnitSkinEyeImage(unitCAnonStorey1Ed.unit, skin, (string)null));
                }
            }
        }
        // ISSUE: reference to a compiler-generated field
        DownloadUtility.PrepareUnitVoice(unitCAnonStorey1Ed.unit);
    }
        /// <summary>
        /// 讀取資料到畫面上
        /// </summary>
        private void ReadJob2Screen(string JobId)
        {
            try
            {
                txtJobId.Text = JobId;

                JobData job = frmScheduleJobUI.Jobs.JobDatas.AsEnumerable().Where(c => c.JobId == JobId).FirstOrDefault();
                if (job != null)
                {
                    txtJobName.Text   = job.JobName;
                    labDLLName.Text   = job.DLLName;
                    labClassName.Text = job.ClassName;
                    txtNameSpace.Text = job.NameSpace;

                    switch (job.UsePeriodType)
                    {
                    case PeriodType.BY_DAILY:
                        if (!string.IsNullOrEmpty(job.ExecuteTime) && job.ExecuteTime != "00:00")     //為時間區隔的反覆性週期工作
                        {
                            if (!TimePattern.Match(job.ExecuteTime).Success)
                            {
                                numHourHH.Focus();
                                throw new Exception("每 HH:ss 反覆執行中的 (小時:分鐘) 設定不正確。");
                            }
                            //屬於每日,且週期性的固定在 HH:ss 中反覆執行.
                            rbHHss.Enabled = true;
                            SetHHssByJobTime(job.ExecuteTime, numHourHH, numMinuteHH);
                            cbEnableTime.Checked = job.Enabled;
                        }
                        else
                        {
                            //屬於每天執行的排程
                            rbDay.Checked = true;
                            if (!TimePattern.Match(job.StartTime).Success)
                            {
                                numHourDay.Focus();
                                throw new Exception("(天) 排程中的 (小時:分鐘) 設定不正確。");
                            }
                            SetHHssByJobTime(job.StartTime, numHourDay, numMinuteDay);
                            cbPeriodDay.Checked = job.IsPeriodJob == PeriodJob.IS_PERIOD;
                            cbEnableDay.Checked = job.Enabled;
                        }
                        break;

                    case PeriodType.BY_WEEKLY:
                        rbWeek.Checked = true;
                        cbExecWeek.SelectedIndex
                            = cbExecWeek.Items.IndexOf(cbExecWeek.Items.OfType <ListItem>()
                                                       .Where(c => c.ValueMember == job.ExceuteWeek.ToString()).FirstOrDefault());

                        SetHHssByJobTime(job.StartTime, numHourWeek, numMinuteWeek);
                        cbPeriodWeek.Checked = job.IsPeriodJob == PeriodJob.IS_PERIOD;
                        cbEnableWeek.Checked = job.Enabled;
                        break;

                    case PeriodType.BY_MONTHLY:
                        rbMonth.Checked = true;
                        cbExecDay.SelectedIndex
                            = cbExecDay.Items.IndexOf(cbExecDay.Items.OfType <ListItem>()
                                                      .Where(c => c.ValueMember == job.ExecuteDay.ToString()).FirstOrDefault());

                        SetHHssByJobTime(job.StartTime, numHourMonth, numMinuteMonth);
                        cbPeriodMonth.Checked = job.IsPeriodJob == PeriodJob.IS_PERIOD;
                        cbEnableMonth.Checked = job.Enabled;
                        break;
                    }
                    txtEMailAddress.Text = job.EMailAddress;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("顯示排程工作資料時,發生錯誤!詳細訊息:{0}", ex.Message), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 /// <summary>
 /// 從 UI 上的資料,重新指定 DLL DLLName, NameSpace, ClassName 等相關資訊.
 /// </summary>
 /// <param name="job"></param>
 private void UpdateJobDLLInfo(JobData job)
 {
     job.DLLName   = labDLLName.Text;
     job.ClassName = labClassName.Text;
     job.NameSpace = txtNameSpace.Text;
 }
Exemplo n.º 22
0
 // TODO #1 - Create a Results action method to process
 // search request and display results
 public IActionResult Results(string searchType, string searchTerm)
 {
     ViewBag.jobs    = JobData.FindByColumnAndValue(searchType, searchTerm);
     ViewBag.columns = ListController.columnChoices;
     return(View("Index"));
 }
        /// <summary>
        /// 使用 Thread 產生一個新的 Schedule Job 執行個體.
        /// <param name="job">Schedule Job 排程相關資料</param>
        /// </summary>
        public void StartNewScheduleJob(JobData job)
        {
            #region NLog 相關物件
            Logger logger    = NLogHelper.GetFileLogConfig(LogLevel.Info);
            Logger loggerErr = NLogHelper.GetErrorFileLogConfig(LogLevel.Error);
            #endregion

            LogAttributeData <WriteLogAttribute>          writeLogAttr   = null; //建立 傳遞 WriteLogAttribute 的容器
            LogAttributeData <WriteExceptionLogAttribute> writeExAttr    = null; //建立 傳遞 WriteExceptionLogAttribute 的容器
            LogAttributeData <ErrorLevelAttribute>        errorLevelAttr = null; //建立 傳遞 ErrorLevelAttribute 的容器

            try
            {
                var resultValue = LoadAssemblyHelper.GetExecuteJobMethod(job);
                _jobMethod         = resultValue.Item1; // Job DLL Instance of Method.
                _targetJobInstance = resultValue.Item2; // Job DLL Instance.
                writeLogAttr       = resultValue.Item3;
                writeExAttr        = resultValue.Item4;
                errorLevelAttr     = resultValue.Item5;
            }
            catch (JobDLLNotFoundException dex) {
                NLogHelper.LoggerExWriter(loggerErr, job.JobName, job.DLLName, string.Format("[{0}]", job.JobName), dex.Message);
            }
            catch (JobMethodNotFoundException mex) {
                NLogHelper.LoggerExWriter(loggerErr, job.JobName, job.DLLName, string.Format("[{0}]", job.JobName), mex.Message);
            }
            catch (IActionNotImplementException aex) {
                NLogHelper.LoggerExWriter(loggerErr, job.JobName, job.DLLName, string.Format("[{0}]", job.JobName), aex.Message);
            }
            catch (Exception ex) {
                NLogHelper.LoggerExWriter(loggerErr, job.JobName, job.DLLName, string.Format("[{0}]", job.JobName), ex.Message);
            }

            try
            {
                //設定此工作目前執中.
                RunningTable.SetJobStatus(job.JobId, JobStatus.Running);
                //重設 Thread 事件狀態.
                _EventStopThread.Reset();
                //m_EventThreadStopped.Reset();

                //產生一個新的 WorkThreadFunction 的 Thread 執行個體.
                ThreadPool.QueueUserWorkItem((state) =>
                {
                    //紀錄 LOG 工作開始
                    logger = NLogHelper.GetFileLogConfig(LogLevel.Info);
                    NLogHelper.LoggerWriter(logger, job.JobName, job.DLLName, string.Format("[{0}]", job.JobName), "[JobStart]", "[JobStart]");
                    //工作開始
                    Thread_Exec_Reault result = WorkerThreadFunction(_jobMethod, _targetJobInstance, job, false, writeLogAttr, writeExAttr, errorLevelAttr, logger, loggerErr);
                    //如果前一個 WorkerThreadFunction 的執行是失敗的,就進行 ReTry 機制
                    if (result == Thread_Exec_Reault.FAIL)
                    {
                        int ReTrySec = 5000; //若未設定 config,則預設每 5 秒鐘進行 ReTry 機制
                        if (ConfigurationManager.AppSettings["ReTrySec"] != null)
                        {
                            try
                            {
                                ReTrySec = int.Parse(ConfigurationManager.AppSettings["ReTrySec"]) * 1000;
                            }
                            catch
                            {
                                loggerErr = NLogHelper.GetErrorFileLogConfig(LogLevel.Error);
                                NLogHelper.LoggerExWriter(loggerErr, job.JobName, job.DLLName, "[ScheduleJob]", "app.config in the ReTrySec parameter setting is incorrect!");
                            }
                        }

                        if (job.ReTry > 0)
                        {
                            //Thread t = new Thread((state) => { WorkerThreadFunctionReTry(iReTry, _jobMethod, _targetJobInstance, job); });
                            //t.Start();
                            // 進行 ReTry 機制.
                            // *** 變數說明 ***
                            // iReTry:要進行 ReTry 的次數
                            // ExecCount:ReRey 的次數.
                            // ReTrySec:ReRey 的秒數.
                            int iReTry = job.ReTry;
                            Task.Factory.StartNew(() =>
                            {
                                int ExecCount = 1;
                                do
                                {
                                    Logger loggerRecord = NLogHelper.GetFileLogConfig(LogLevel.Info);
                                    NLogHelper.LoggerWriter(loggerRecord, job.JobName, job.DLLName, string.Format("[{0}]", job.JobName), "[ReTry]", string.Format("Execute repeat steps {0}.....", ExecCount));
                                    Thread_Exec_Reault ReTryResult = WorkerThreadFunction(_jobMethod, _targetJobInstance, job, true, writeLogAttr, writeExAttr, errorLevelAttr, logger, loggerErr);
                                    if (ReTryResult == Thread_Exec_Reault.SUCCESS)
                                    {
                                        break; //若執行成功,隨即跳出迴圈 與 Currenthread.
                                    }
                                    Thread.Sleep(ReTrySec);
                                    iReTry--;
                                    ExecCount++;
                                } while (iReTry > 0);
                            }
                                                  );
                        }
                    }
                }, job);
                //設定最後執行時間.
                RunningJobs.SetLastExecuteDateTime(job);
            }
            catch (Exception ex)
            {
                //logger = NLogHelper.GetErrorFileLogConfig(LogLevel.Error);
                NLogHelper.LoggerExWriter(loggerErr, job.JobName, job.DLLName, string.Format("[{0}]", job.JobName), ex.Message);
            }
            finally
            {
                //等待執行序收到結束信號
                _EventStopThread.WaitOne();
                //設定服務為閒置狀態
                RunningTable.SetJobStatus(job.JobId, JobStatus.Idle);
            }
        }
Exemplo n.º 24
0
 //TODO #1 - Create a Results action method to process
 // search request and display results
 public IActionResult Results(string column, string value)
 {
     ViewBag.columnAndData = JobData.FindByColumnAndValue(column, value);
     ViewBag.columns       = ListController.columnChoices;
     return(View());
 }
 public override bool CanProcess(JobData jobData)
 {
     return(jobData.Data.ContainsKey("processGroups"));
 }
Exemplo n.º 26
0
    /// <summary>
    /// TODO: the data struction ! HtmlNodeCollection should be Collection of UserDataRow s
    /// Inserts to database.
    /// </summary>
    /// <param name="job">JobData which is needed to be stored in database</param>
    /// <param name="nodes">html nodes which contains user contributions </param>
    /// <param name="jobnum">Jobnum.</param>
    void insertToDatabase(JobData job, HtmlNodeCollection nodes, int jobnum)
    {
        if (!job.hasReward ()) {
            return;
        }

        //SQL preparation
        MySqlConnection con = null;

        string conCmd =
            "server=" + SERVER + ";" +
            "database=" + DATABASE + ";" +
            "userid=" + USERID + ";" +
            "port=" + PORT + ";" +
            "password="******"insert into " + "crowdworks" + " values (" +  "2"+ ",  \""+ "shoshotest" + "\" , "+ "19910722" + ");";
                string selCmd = new UserDataRow (n, jobnum).getSQLString (TASKTABLE);
                 Debug.Log (selCmd);
                MySqlCommand cmd = new MySqlCommand (selCmd, con);

                cmd.ExecuteNonQuery ();

            } catch (NullReferenceException e) {
                Debug.Log (e.ToString ());
            }
        }

        if (job.list.ToArray ().Length >= 1) {

            try {
                foreach(var n in job.list){
                    string selCmd = n.getSQLString (EXTRATABLE,jobnum);
                    MySqlCommand cmd = new MySqlCommand (selCmd, con);

                    cmd.ExecuteNonQuery ();

                }
            } catch (NullReferenceException e) {
                Debug.Log (e.ToString ());
            }

        }
        //SQL end
        con.Close ();
        con.Dispose ();
    }
 public override bool CanProcess(JobData jobData)
 {
     return jobData.Data.ContainsKey("processBlogs");
 }
Exemplo n.º 28
0
    public static void DownloadUnit(Unit unit, bool dlStatusEffects = false)
    {
        UnitParam     unitParam    = unit.UnitParam;
        JobParam      job          = unit.Job == null ? (JobParam)null : unit.Job.Param;
        ArtifactParam selectedSkin = unit.UnitData.GetSelectedSkin(-1);

        CharacterDB.Job characterData = DownloadUtility.GetCharacterData(unitParam, job, selectedSkin);
        if (characterData == null)
        {
            return;
        }
        DownloadUtility.PrepareUnitAssets(characterData, job);
        if (unit.Job != null)
        {
            DownloadUtility.PrepareJobAssets(unit.Job.Param);
        }
        string jobName = unit.UnitData.CurrentJob == null ? string.Empty : unit.UnitData.CurrentJob.JobID;

        AssetManager.PrepareAssets(AssetPath.UnitSkinIconSmall(unitParam, selectedSkin, jobName));
        AssetManager.PrepareAssets(AssetPath.UnitSkinIconMedium(unitParam, selectedSkin, jobName));
        AssetManager.PrepareAssets(AssetPath.UnitSkinEyeImage(unitParam, selectedSkin, jobName));
        SkillData attackSkill = unit.GetAttackSkill();

        if (attackSkill != null)
        {
            DownloadUtility.PrepareSkillAssets(characterData, attackSkill.SkillParam);
        }
        for (int index = unit.BattleSkills.Count - 1; index >= 0; --index)
        {
            DownloadUtility.PrepareSkillAssets(characterData, unit.BattleSkills[index].SkillParam);
        }
        for (int index = unit.BattleAbilitys.Count - 1; index >= 0; --index)
        {
            AbilityData battleAbility = unit.BattleAbilitys[index];
            if (battleAbility != null && battleAbility.Param != null)
            {
                AssetManager.PrepareAssets(AssetPath.AbilityIcon(battleAbility.Param));
            }
        }
        if (unit != null)
        {
            DownloadUtility.PrepareUnitVoice(unit.UnitParam);
        }
        if (dlStatusEffects)
        {
            for (int index = 0; index < BadStatusEffects.Effects.Count; ++index)
            {
                if (!string.IsNullOrEmpty(BadStatusEffects.Effects[index].AnimationName))
                {
                    DownloadUtility.PrepareUnitAnimation(characterData, BadStatusEffects.Effects[index].AnimationName, false, (JobParam)null);
                }
            }
        }
        JobData[] jobs = unit.UnitData.Jobs;
        int       artifactSlotIndex = JobData.GetArtifactSlotIndex(ArtifactTypes.Arms);

        if (jobs != null)
        {
            List <ArtifactParam> artifacts = MonoSingleton <GameManager> .GetInstanceDirect().MasterParam.Artifacts;

            foreach (JobData jobData in jobs)
            {
                if (jobData != null)
                {
                    // ISSUE: object of a compiler-generated type is created
                    // ISSUE: reference to a compiler-generated method
                    ArtifactParam artifalct = artifacts.Find(new Predicate <ArtifactParam>(new DownloadUtility.\u003CDownloadUnit\u003Ec__AnonStorey1F2()
                    {
                        uniqId = (string)null, uniqId = jobData.ArtifactDatas[artifactSlotIndex] == null ? jobData.Param.artifact : jobData.ArtifactDatas[artifactSlotIndex].ArtifactParam.iname
                    }.\u003C\u003Em__1B8));
                    if (artifalct != null)
                    {
                        DownloadUtility.DownloadArtifact(artifalct);
                    }
                }
            }
        }
        else
        {
            if (unit.Job == null)
            {
                return;
            }
            DownloadUtility.DownloadArtifact(MonoSingleton <GameManager> .GetInstanceDirect().MasterParam.GetArtifactParam(unit.Job.Param.artifact));
        }
    }
        public void TestJobUpdateRetry()
        {
            var dataContextMock = new Mock<IMediaDataServiceContext>();

             int exceptionCount = 2;

             var job = new JobData { Name = "testData", Id = "id:someid" };
             var fakeResponse = new TestMediaDataServiceResponse { AsyncState = job };
             var fakeException = new WebException("test", WebExceptionStatus.ConnectionClosed);

             dataContextMock.Setup((ctxt) => ctxt.AttachTo("Jobs", job));
             dataContextMock.Setup((ctxt) => ctxt.DeleteObject(job));

             dataContextMock.Setup((ctxt) => ctxt
                 .SaveChangesAsync(job))
                 .Returns(() => Task.Factory.StartNew<IMediaDataServiceResponse>(() =>
                 {
                     if (--exceptionCount > 0) throw fakeException;
                     return fakeResponse;
                 }));

             _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object);

             job.SetMediaContext(_mediaContext);

             job.Update();

             Assert.AreEqual(0, exceptionCount);
        }
Exemplo n.º 30
0
 internal JobContext(IJobManager jobManager, JobData jobData, IJob jobInstance)
 {
     JobManager  = jobManager;
     JobData     = jobData;
     JobInstance = jobInstance;
 }
Exemplo n.º 31
0
        public void SchedulerExecutesJobsAndHandlesSuccessFailureOrException(
            bool jobSucceeds, bool jobThrows, bool savingCompletedJobThrows)
        {
            JobData newJobData = new JobData();

            ExecuteDelegate execute = delegate(JobExecutionContext context)
            {
                Assert.IsNotNull(context);
                Assert.AreSame(scheduler, context.Scheduler);
                Assert.IsNotNull(context.Logger);
                Assert.IsNotNull(context.JobSpec);

                context.JobData = newJobData;

                if (jobThrows)
                    throw new Exception("Oh no!");

                return jobSucceeds;
            };

            PrepareJobForExecution(execute.BeginInvoke, execute.EndInvoke);

            /* Note: We used to drop back into ScheduleJob again immediately after a job completed.
             *       That's a cheap optimization but it makes it more difficult to ensure that
             *       the scheduler will shut down cleanly since it could just keep re-executing the job.
            TriggerScheduleCondition expectedCondition = jobSucceeds ? TriggerScheduleCondition.JobSucceeded : TriggerScheduleCondition.JobFailed;
            Expect.Call(mockTrigger.Schedule(expectedCondition, DateTime.UtcNow))
                .Constraints(Is.Equal(expectedCondition), Is.Anything())
                .Return(TriggerScheduleAction.Stop);
            Expect.Call(mockTrigger.NextFireTime).Return(null);
            Expect.Call(mockTrigger.NextMisfireThreshold).Return(null);
             */

            mockJobStore.SaveJobDetails(null);
            LastCall.IgnoreArguments().Do((SaveJobDetailsDelegate) delegate(JobDetails completedJobDetails)
            {
                Assert.IsNotNull(completedJobDetails);
                Assert.AreEqual(dummyJobSpec.Name, completedJobDetails.JobSpec.Name);

                Assert.IsNotNull(completedJobDetails.LastJobExecutionDetails);
                Assert.AreEqual(scheduler.Guid, completedJobDetails.LastJobExecutionDetails.SchedulerGuid);
                Assert.GreaterOrEqual(completedJobDetails.LastJobExecutionDetails.StartTimeUtc,
                                      completedJobDetails.CreationTimeUtc);
                Assert.IsNotNull(completedJobDetails.LastJobExecutionDetails.EndTimeUtc);
                Assert.GreaterOrEqual(completedJobDetails.LastJobExecutionDetails.EndTimeUtc.Value.Ticks, completedJobDetails.LastJobExecutionDetails.StartTimeUtc.Ticks);
                Assert.AreEqual(jobSucceeds, completedJobDetails.LastJobExecutionDetails.Succeeded);

                if (!jobThrows)
                    JobAssert.AreEqual(newJobData, completedJobDetails.JobSpec.JobData);
                else
                    Assert.IsNull(completedJobDetails.JobSpec.JobData);

                Wake();
            });

            Mocks.ReplayAll();

            RunSchedulerUntilWake();
        }
        protected override String OnRunJob(JobData job)
        {
            Application app             = null;
            Workbook    wkb             = null;
            var         sourceFile      = job.SourceFile;
            var         destinationFile = job.DestinationFile;

            try
            {
                app = new Application();
                app.ScreenUpdating         = false;
                app.DisplayStatusBar       = false;
                app.EnableEvents           = false;
                app.DisplayAlerts          = false;
                app.DisplayClipboardWindow = false;

                //app.Visible = true;
                Logger.DebugFormat("Opening {0} in office", sourceFile);
                wkb = app.Workbooks.Open(sourceFile, Password: GetPassword(Path.GetFileName(sourceFile)));

                Logger.DebugFormat("Exporting {0} in pdf", sourceFile);
                HashSet <String> workbookWithPrintableAreaSet = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                foreach (Name name in wkb.Names)
                {
                    if (name.Name.IndexOf("print_area", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        var splitted     = name.Name.Split('!');
                        var workbookName = splitted[0].Trim('\"', '\'', ' ');
                        workbookWithPrintableAreaSet.Add(workbookName);
                    }
                }

                Boolean   printAreaIsValid = false;
                Worksheet worksheetToPrint = (wkb.ActiveSheet as Worksheet);
                var       activeSheetName  = worksheetToPrint?.Name as String;
                if (!String.IsNullOrEmpty(activeSheetName) && workbookWithPrintableAreaSet.Contains(activeSheetName))
                {
                    printAreaIsValid = true; //current selected worksheet has a print area set
                }
                else
                {
                    //ok we need to find if any of the worksheet has a valid print area
                    foreach (var workbookName in workbookWithPrintableAreaSet)
                    {
                        var worksheet = wkb.Sheets
                                        .OfType <Worksheet>()
                                        .FirstOrDefault(s => s.Name?.Equals(workbookName, StringComparison.OrdinalIgnoreCase) == true);
                        if (worksheet != null)
                        {
                            worksheetToPrint = worksheet;
                            printAreaIsValid = true; //current selected worksheet has a print area set
                            break;
                        }
                    }
                }

                //ok check if the current workbook has a print area defined

                if (printAreaIsValid)
                {
                    //we have a printable area, we already selected the active sheet, we
                    //can now print everything, but pay attention, we want to print only
                    //one worksheet, not all of them.
                    worksheetToPrint.ExportAsFixedFormat(
                        XlFixedFormatType.xlTypePDF,
                        destinationFile,
                        XlFixedFormatQuality.xlQualityStandard, //object quality
                        true,                                   //include doc property
                        false,                                  //ignore print areas
                        Type.Missing,                           //from
                        Type.Missing,                           //to
                        false,                                  //false //open after publish
                        Type.Missing                            //null // fixedFormatExternalClass ....
                        );
                }
                else
                {
                    //There is no printable area, to avoid chaos we will print
                    //only the first page of the active sheet.
                    worksheetToPrint.ExportAsFixedFormat(
                        XlFixedFormatType.xlTypePDF,
                        destinationFile,
                        XlFixedFormatQuality.xlQualityStandard, //object quality
                        true,                                   //include doc property
                        false,                                  //ignore print areas
                        1,                                      //from
                        1,                                      //to
                        false                                   //open after publish
                              //null // fixedFormatExternalClass ....
                        );
                }

                Logger.DebugFormat("Closing excel", sourceFile);
                Close(wkb);
                wkb = null;
                Logger.DebugFormat("Quitting excel", sourceFile);
                Close(app);
                app = null;
                return(String.Empty);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat(ex, "Error converting {0} - {1}", sourceFile, ex.Message);

                if (wkb != null)
                {
                    Close(wkb);
                }
                if (app != null)
                {
                    this.Close(app);
                }
                return($"Error converting {sourceFile} - {ex.Message}");
            }
        }
        public async Task <IActionResult> Upload(IFormFile file) //IFormFile file, IFormCollection files
        {
            var uploadFolderPath = Path.Combine(host.WebRootPath, "uploads");

            if (Directory.Exists(uploadFolderPath))
            {
                Directory.CreateDirectory(uploadFolderPath);
            }

            var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            var filePath = Path.Combine(uploadFolderPath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            // Process the uploaded file
            //Read the contents of CSV file.
            string csvData = System.IO.File.ReadAllText(filePath);

            // Process JobData
            #region ProcessJobData

            //Execute a loop over the rows.
            foreach (string row in csvData.Split('\n'))
            {
                if (!string.IsNullOrEmpty(row))
                {
                    // get branchId
                    var sn             = row.Split(',')[0];
                    var name           = row.Split(',')[1];
                    var pan            = row.Split(',')[2];
                    var brCode         = row.Split(',')[3];
                    var brName         = row.Split(',')[4];
                    var customerName   = row.Split(',')[5];
                    var customerNumber = row.Split(',')[6];
                    var accNumber      = row.Split(',')[7];
                    var fName          = row.Split(',')[8];

                    JobData jobData = new JobData()
                    {
                        SN              = sn,
                        Name            = name,
                        Pan             = pan,
                        BranchCode      = brCode,
                        BranchName      = brName,
                        CustodianName   = customerName,
                        CustodianNumber = customerNumber,
                        AccountNumber   = accNumber,
                        FileName        = fName,
                        JobId           = file.FileName
                    };

                    context.Jobdatas.Add(jobData);
                }
            }

            await context.SaveChangesAsync();

            #endregion

            //Process the JobManifest Data
            #region ProcessJobManifest

            JobManifest jobManifest = new JobManifest()
            {
                WayBillNumber = fileName,
                //TrackingNumber = Guid.NewGuid().ToString(),
                JobId = file.FileName
            };

            context.JobManifests.Add(jobManifest);
            await context.SaveChangesAsync();

            // get distinct BranchCode
            var selectedBranchCode = context.Jobdatas.Select(b => b.BranchCode).Distinct();

            // Iterate thru the branchCode
            foreach (string branch in selectedBranchCode)
            {
                //get the count
                var branchData   = context.Jobdatas.Where(b => b.BranchCode == branch);
                var clientBranch = context.ClientBranches.SingleOrDefault(c => c.BranchCode == branch);
                var dataCount    = branchData.Count();

                if (clientBranch != null)
                {
                    //Create Branch Manifest
                    JobManifestBranch branchManifest = new JobManifestBranch()
                    {
                        DataQuantity   = dataCount,
                        JobManifestId  = jobManifest.Id,
                        ClientBranchId = clientBranch.Id,
                        JobId          = file.FileName
                    };

                    context.JobManifestBranches.Add(branchManifest);
                    await context.SaveChangesAsync();


                    // Create the Branch Logs
                    foreach (var data in branchData)
                    {
                        JobManifestLog manifestLog = new JobManifestLog()
                        {
                            SN              = data.SN,
                            Name            = data.Name,
                            Pan             = data.Pan,
                            BranchCode      = data.BranchCode,
                            BranchName      = data.BranchName,
                            CustodianName   = data.CustodianName,
                            CustodianNumber = data.CustodianNumber,
                            AccountNumber   = data.AccountNumber,
                            FileName        = data.FileName,

                            JobManifestId       = jobManifest.Id,
                            JobManifestBranchId = branchManifest.Id
                        };

                        context.JobManifestLogs.Add(manifestLog);
                    }

                    await context.SaveChangesAsync();
                }
            }

            #endregion

            // Delete the JobData
            #region DeleteJobData

            var fileJobDatas = context.Jobdatas.Where(j => j.JobId == file.FileName);

            foreach (var job in fileJobDatas)
            {
                context.Jobdatas.Remove(job);
            }

            await context.SaveChangesAsync();

            #endregion


            //Geth the manifest for the doc
            var completedManifest = await context.JobManifests
                                    .Include(m => m.JobManifestBranchs)
                                    .Include(l => l.JobManifestLogs)
                                    .SingleOrDefaultAsync(it => it.Id == jobManifest.Id);

            if (jobManifest == null)
            {
                return(NotFound());
            }

            var jobManifestResource = mapper.Map <JobManifest, JobManifestResource>(completedManifest);

            return(Ok(jobManifestResource));
        }
Exemplo n.º 34
0
 internal Handle(JobData job)
 {
     this.job = job;
 }
Exemplo n.º 35
0
        /// <summary>
        /// 傳入 Assembly 物件,從 Assembly 指定的 NameSpace & ClassName 到 Assembly 中取得並回傳 MethodInfo.
        /// </summary>
        /// <param name="ass">Assembly for Job DLL</param>
        /// <param name="Job">JobData 物件</param>
        /// <returns>Tuple 物件 (包含:MethodIfo, new Job Instance)</returns>
        public static Tuple <MethodInfo, object, LogAttributeData <WriteLogAttribute>, LogAttributeData <WriteExceptionLogAttribute>, LogAttributeData <ErrorLevelAttribute> > Common(
            Assembly ass,
            JobData Job)
        {
            object jobClassObject = null;
            LogAttributeData <WriteLogAttribute>          writeLogAttr   = new LogAttributeData <WriteLogAttribute>();
            LogAttributeData <WriteExceptionLogAttribute> writeExAttr    = new LogAttributeData <WriteExceptionLogAttribute>();
            LogAttributeData <ErrorLevelAttribute>        errorLevelAttr = new LogAttributeData <ErrorLevelAttribute>();

            MethodInfo jobMethod           = null;
            MethodInfo BeforePrepareMethod = null;
            MethodInfo PrepareDataMethod   = null;
            MethodInfo ProcessDataMethod   = null;
            MethodInfo AfterProcessMethod  = null;

            Type magicType = ass.GetType(string.Format("{0}.{1}", Job.NameSpace, Job.ClassName));

            if (magicType != null)
            {
                //判別 Load 進來的 Class 型態是不是實作 IAction 的介面,若不是,則 throw Exception.
                if (magicType.GetInterfaces().AsEnumerable <Type>().Where(c => c == typeof(IAction)).FirstOrDefault() == null)
                {
                    throw new IActionNotImplementException(string.Format("The {0} of class {1} is must be to inheritance by interface of IAtion.", Job.DLLName, Job.ClassName))
                          {
                              Datetime   = DateTime.Now,
                              MethodInfo = string.Format("DLLPath={0}, DLLName={1}, NameSpace={2}, ClassName={3}", dllPath, Job.DLLName, Job.NameSpace, Job.ClassName)
                          };
                }

                ConstructorInfo jobConstructor = magicType.GetConstructor(Type.EmptyTypes);
                jobClassObject = jobConstructor.Invoke(null);

                jobMethod           = magicType.GetMethod(JOB_METHOD_NAME);
                BeforePrepareMethod = magicType.GetMethod(BEFORE_PREPARE_METHOD_NAME, BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic);
                PrepareDataMethod   = magicType.GetMethod(PREPARE_DATA_METHOD_NAME, BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic);
                ProcessDataMethod   = magicType.GetMethod(PROCESS_DATA_METHOD_NAME, BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic);
                AfterProcessMethod  = magicType.GetMethod(AFTER_PROCESS_METHOD_NAME, BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic);

                #region 包裝 WriteLogAttribute 容器
                writeLogAttr.SetBeforePrepareMethod(BeforePrepareMethod);
                writeLogAttr.SetPrepareDataMethod(PrepareDataMethod);
                writeLogAttr.SetProcessDataMethod(ProcessDataMethod);
                writeLogAttr.SetAfterProcessMethod(AfterProcessMethod);
                #endregion

                #region 包裝 WriteLogExAttribute 容器
                writeExAttr.SetBeforePrepareMethod(BeforePrepareMethod);
                writeExAttr.SetPrepareDataMethod(PrepareDataMethod);
                writeExAttr.SetProcessDataMethod(ProcessDataMethod);
                writeExAttr.SetAfterProcessMethod(AfterProcessMethod);
                #endregion

                #region 包裝 ErrorLevelAttribute 容器
                errorLevelAttr.SetBeforePrepareMethod(BeforePrepareMethod);
                errorLevelAttr.SetPrepareDataMethod(PrepareDataMethod);
                errorLevelAttr.SetProcessDataMethod(ProcessDataMethod);
                errorLevelAttr.SetAfterProcessMethod(AfterProcessMethod);
                #endregion

                if (jobMethod == null)
                {
                    throw new JobMethodNotFoundException("Please check the method is correct!")
                          {
                              Datetime   = DateTime.Now,
                              MethodInfo = string.Format("DLLPath={0}, DLLName={1}, NameSpace={2}, ClassName={3}", dllPath, Job.DLLName, Job.NameSpace, Job.ClassName)
                          };
                }
            }
            else
            {
                throw new JobMethodNotFoundException("Please check the namespace or class name is correct!")
                      {
                          Datetime   = DateTime.Now,
                          MethodInfo = string.Format("DLLPath={0}, DLLName={1}, NameSpace={2}, ClassName={3}", dllPath, Job.DLLName, Job.NameSpace, Job.ClassName)
                      };
            }

            return(Tuple.Create(jobMethod, jobClassObject, writeLogAttr, writeExAttr, errorLevelAttr));
        }
        public void Execute(JobData jobData)
        {
            var fs = CentralizedFileStorage.GetFileStore(UserExportPlugin.FILESTORE_KEY);

            if (fs.GetFile("", "processing.txt") == null)
                return;

            try
            {
                UsersListOptions list = new UsersListOptions()
                {
                    PageIndex = 0,
                    PageSize = 100,
                    IncludeHidden = true,
                    AccountStatus = "All"
                };

                StringBuilder resultCsv = new StringBuilder(100000);

                bool moreRecords = true;

                //Build the header
                List<string> elements = new List<string>();
                elements.Add("UserName");
                elements.Add("DisplayName");
                elements.Add("Account Email");
                elements.Add("LastLoginDate");
                elements.Add("Language");
                elements.Add("AccountStatus");
                elements.Add("Allow Partners To Contact");
                elements.Add("Allow Site To Contact");
                elements.Add("Avatar URL");
                elements.Add("Birthday");
                elements.Add("Bio");
                elements.Add("Location");
                elements.Add("TotalPosts");

                foreach (var profileFeild in PublicApi.UserProfileFields.List())
                {
                    elements.Add(profileFeild.Title);
                }

                resultCsv.AppendLine(string.Join(",", elements.Select(Csv.Escape)));

                while (moreRecords)
                {
                    var results = PublicApi.Users.List(list);

                    moreRecords = results.TotalCount > (++list.PageIndex*list.PageSize);

                    foreach (var user in results)
                    {
                        elements.Clear();

                        elements.Add(user.Username);
                        elements.Add(user.DisplayName);
                        elements.Add(user.PrivateEmail);
                        elements.Add(PublicApi.Language.FormatDateAndTime(user.LastLoginDate.GetValueOrDefault(DateTime.MinValue)));
                        elements.Add(user.Language);
                        elements.Add(user.AccountStatus);
                        elements.Add(user.AllowSitePartnersToContact.ToString());
                        elements.Add(user.AllowSiteToContact.ToString());
                        elements.Add(user.AvatarUrl);
                        elements.Add(PublicApi.Language.FormatDateAndTime(user.Birthday.GetValueOrDefault(DateTime.MinValue)));
                        elements.Add(user.Bio(""));
                        elements.Add(user.Location);
                        elements.Add(user.TotalPosts.ToString());

                        var profileFeilds = user.ProfileFields.ToLookup(l => l.Label);

                        foreach (var profileFeild in PublicApi.UserProfileFields.List())
                        {
                            if (profileFeilds.Contains(profileFeild.Name))
                            {
                                elements.Add(profileFeilds[profileFeild.Name].First().Value);
                            }
                            else
                            {
                                elements.Add(string.Empty);
                            }
                        }

                        resultCsv.AppendLine(string.Join(",", elements.Select(Csv.Escape)));
                    }
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    using (StreamWriter wr = new StreamWriter(ms))
                    {
                        wr.Write(resultCsv);
                        wr.Flush();

                        ms.Seek(0, SeekOrigin.Begin);

                        fs.AddUpdateFile("", "results.csv", ms);
                    }
                }
            }
            catch (Exception ex)
            {
                PublicApi.Eventlogs.Write("Error exporting users:" + ex, new EventLogEntryWriteOptions() { Category = "User Export" });
            }
            finally
            {
                PublicApi.Eventlogs.Write("Finished exporting users", new EventLogEntryWriteOptions() {Category = "User Export"});

                fs.Delete("", "processing.txt");
            }
        }
Exemplo n.º 37
0
 static JobController()
 {
     jobData = JobData.GetInstance();
 }
Exemplo n.º 38
0
 protected override void OnExecute(int index, ref JobData data)
 {
     data.alpha = data.curve.Value.Evaluate(Base.time) * data.alpha;
 }
Exemplo n.º 39
0
 public DimTo(JobData data)
     : base(data)
 {
 }
Exemplo n.º 40
0
 public EnableSuc(JobData jobData)
     : base(jobData)
 {
 }
Exemplo n.º 41
0
 public void Initialize(JobData jobData, NebulaContext nebulaContext)
 {
     _nebulaContext = nebulaContext;
 }
        public void CancelJobEmptyId()
        {
            var data = new JobData();

            data.Cancel();
        }
Exemplo n.º 43
0
 /// <summary>
 /// Deletes the job permanently from the job store.
 /// </summary>
 /// <param name="job">The job.</param>
 /// <param name="deleteHistory">If set to true, the history will also be deleted.</param>
 /// <returns></returns>
 public bool DeleteJob(JobData job, bool deleteHistory = false)
 {
     return(DeleteJob(job.Id, deleteHistory));
 }
 private static JobData GetJobData(IScheduler scheduler,JobKey jobKey)
 {
     var jobData = new JobData(jobKey.Name, jobKey.Group, GetTriggers(scheduler, jobKey));
     jobData.Init();
     return jobData;
 }
Exemplo n.º 45
0
        //*******************************************************************
        /// <summary>実行ジョブフロー領域の表示</summary>
        //*******************************************************************
        private void ShowJobNet()
        {
            container.ContainerCanvas.Children.Clear();
            container.JobItems.Clear();
            // 実行ジョブデータ(実行ジョブアイコンの生成用)
            JobData jobData = null;

            // 実行ジョブを表示------------------
            foreach (DataRow row in container.JobControlTable.Select())
            {
                jobData = new JobData();
                // 実行ジョブタイプ
                jobData.JobType = (ElementType)row["job_type"];
                SolidColorBrush iconColor = getIconColor(row);

                //added by YAMA 2014/07/01
                //CommonItem room = new CommonItem(container, jobData, Consts.EditType.READ, iconColor);
                SolidColorBrush characterColor = getCharacterColor(row);
                CommonItem      room           = new CommonItem(container, jobData, Consts.EditType.READ, iconColor, characterColor);

                // 実行ジョブID
                room.JobId = Convert.ToString(row["job_id"]);
                // 実行内部ジョブID
                room.InnerJobId = Convert.ToString(row["inner_job_id"]);
                //実行ジョブ名
                room.JobName = Convert.ToString(row["job_name"]);
                // X位置
                room.SetValue(Canvas.LeftProperty, Convert.ToDouble(row["point_x"]));
                // Y位置
                room.SetValue(Canvas.TopProperty, Convert.ToDouble(row["point_y"]));

                // ToolTip設定
                room.ContentItem.SetToolTip();

                room.RemoveAllEvent();
                //room.ContextMenu = contextMenu;


                if (jobData.JobType.Equals(ElementType.JOBNET))
                {
                    room.MouseDoubleClick += new System.Windows.Input.MouseButtonEventHandler(jobnetItem_MouseDoubleClick);
                }
                else
                {
                    room.MouseDoubleClick += UserControl_MouseDoubleClick4Read;
                }

                // 実行ジョブフロー領域に追加
                container.ContainerCanvas.Children.Add(room);
                container.JobItems.Add(room.InnerJobId, room);
            }

            // フローを表示------------------
            // 開始実行ジョブID、終了実行ジョブId
            string startJobId, endJobId;
            // 開始実行ジョブ、終了実行ジョブ
            IRoom startJob, endJob;
            // フロー幅
            int flowWidth;
            // フロータイプ(直線、曲線)
            FlowLineType lineType;
            // フロータイプ( 0:通常、 1:TURE、 2:FALSE)
            int flowType = 0;

            foreach (DataRow row in container.FlowControlTable.Select())
            {
                startJobId = Convert.ToString(row["start_inner_job_id"]);
                endJobId   = Convert.ToString(row["end_inner_job_id"]);
                flowWidth  = Convert.ToInt32(row["flow_width"]);
                flowType   = Convert.ToInt32(row["flow_type"]);

                // フロータイプの判定
                if (flowWidth == 0)
                {
                    lineType = FlowLineType.Line;
                }
                else
                {
                    lineType = FlowLineType.Curve;
                }

                startJob = (IRoom)container.JobItems[startJobId];
                endJob   = (IRoom)container.JobItems[endJobId];

                container.MakeFlow(lineType, startJob, endJob, flowType, Consts.EditType.READ);
            }
        }
 private static JobData GetJobData(IScheduler scheduler, string jobName, string group)
 {
     var jobData = new JobData(jobName, group, GetTriggers(scheduler, jobName, group));
     jobData.Init();
     return jobData;
 }
        public void TestJobGetContentKeysRetry()
        {
            var data = new JobData { Name = "testData", Id = "testId" };

             var dataContextMock = TestMediaServicesClassFactory.CreateLoadPropertyMockConnectionClosed(2, data);

             _mediaContext.MediaServicesClassFactory = new TestMediaServicesClassFactory(dataContextMock.Object);

             data.SetMediaContext(_mediaContext);

             var actual = ((IJob)data).InputMediaAssets;

             dataContextMock.Verify((ctxt) => ctxt.LoadProperty(data, "InputMediaAssets"), Times.Exactly(2));
        }
Exemplo n.º 48
0
        //protected static Logger LOG = NLog.LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 主要執行的 Method 入口
        /// <param name="job">目前執行的 Job 相關資料.</param>
        /// <param name="writeLogAttr">WriteLog 的設定相關資料</param>
        /// <param name="writeExAttr">WriteExLog 的設定相關資料</param>
        /// </summary>
        public virtual void DoJob(
            JobData job,
            LogAttributeData <WriteLogAttribute> writeLogAttr,
            LogAttributeData <WriteExceptionLogAttribute> writeExAttr,
            LogAttributeData <ErrorLevelAttribute> errorLevelAttr,
            Logger loggerInner,
            Logger loggerInnerErr)
        {
            #region NLog 相關物件
            //Logger loggerInner = NLogHelper.GetFileLogConfig(LogLevel.Info);
            //Logger loggerInnerErr = NLogHelper.GetErrorFileLogConfig(LogLevel.Error);
            #endregion

            WriteLogAttribute          LogAttr      = null;
            WriteExceptionLogAttribute LogExAttr    = null;
            ErrorLevelAttribute        ErrLevelAttr = null;

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Reset(); //碼表歸零
            sw.Start(); //碼表開始計時

            //loggerInner.Info("[DoJob] Start");

            try
            {
                LogAttr = writeLogAttr.GetBeforePrepareAttr();          //取得當前的 BeforPrepare 方法是否有設定 WriteLogAttribute.
                if (LogAttr != null)
                {
                    WriteInfo(LogAttr, job, "[BeforePrepare] Start...");
                }

                BeforePrepare();
                if (LogAttr != null)
                {
                    loggerInner.Info(string.Format("[{0}].{1}.{2}  Completed... total {3}", job.JobName, "[DotJob]", "[BeforePrepare]", sw.Elapsed.TotalMilliseconds.ToString()));
                }
            }
            catch (Exception ex)
            {
                ErrLevelAttr = errorLevelAttr.GetBeforePrepareAttr();   //取得當前的 BeforPrepare 方法是否有設定 ErrorLevelAttribute.
                LogExAttr    = writeExAttr.GetBeforePrepareAttr();      //取得當前的 BeforPrepare 方法是否有設定 WriteExceptionLogAttribute.
                if (LogExAttr != null)
                {
                    WriteExLog(LogExAttr, job, "[BeforePrepare]", ex, ErrLevelAttr);
                }

                throw ex;
            }

            try
            {
                LogAttr = writeLogAttr.GetPrepareDataMethodAttr();
                if (LogAttr != null)
                {
                    WriteInfo(LogAttr, job, "[PrepareData] Start...");
                }

                PrepareData();
                if (LogAttr != null)
                {
                    loggerInner.Info(string.Format("[{0}].{1}.{2}  Completed... total {3}", job.JobName, "[DotJob]", "[PrepareData]", sw.Elapsed.TotalMilliseconds.ToString()));
                }
            }
            catch (Exception ex)
            {
                ErrLevelAttr = errorLevelAttr.GetPrepareDataMethodAttr(); //取得當前的 PrepareData 方法是否有設定 ErrorLevelAttribute.
                LogExAttr    = writeExAttr.GetPrepareDataMethodAttr();    //取得當前的 PrepareData 方法是否有設定 WriteExceptionLogAttribute.
                if (LogExAttr != null)
                {
                    WriteExLog(LogExAttr, job, "[PrepareData]", ex, ErrLevelAttr);
                }

                throw ex;
            }

            try
            {
                LogAttr = writeLogAttr.GetProcessDataMethodAttr();
                if (LogAttr != null)
                {
                    WriteInfo(LogAttr, job, "[ProcessData] Start...");
                }

                ProcessData();
                if (LogAttr != null)
                {
                    loggerInner.Info(string.Format("[{0}].{1}.{2}  Completed... total {3}", job.JobName, "[DotJob]", "[ProcessData]", sw.Elapsed.TotalMilliseconds.ToString()));
                }
            }
            catch (Exception ex)
            {
                ErrLevelAttr = errorLevelAttr.GetProcessDataMethodAttr(); //取得當前的 ProcessData 方法是否有設定 ErrorLevelAttribute.
                LogExAttr    = writeExAttr.GetProcessDataMethodAttr();    //取得當前的 ProcessData 方法是否有設定 WriteExceptionLogAttribute.
                if (LogExAttr != null)
                {
                    WriteExLog(LogExAttr, job, "[ProcessData]", ex, ErrLevelAttr);
                }

                throw ex;
            }

            try
            {
                LogAttr = writeLogAttr.GetAfterProcessMethodAttr();
                if (LogAttr != null)
                {
                    WriteInfo(LogAttr, job, "[AfterProcess] Start...");
                }

                AfterProcess();
                if (LogAttr != null)
                {
                    loggerInner.Info(string.Format("[{0}].{1}.{2}  End... total {3}", job.JobName, "[DotJob]", "[AfterProcess]", sw.Elapsed.TotalMilliseconds.ToString()));
                }
            }
            catch (Exception ex)
            {
                ErrLevelAttr = errorLevelAttr.GetAfterProcessMethodAttr(); //取得當前的 AfterProcess 方法是否有設定 ErrorLevelAttribute.
                LogExAttr    = writeExAttr.GetAfterProcessMethodAttr();    //取得當前的 AfterProcess 方法是否有設定 WriteExceptionLogAttribute.
                if (LogExAttr != null)
                {
                    WriteExLog(LogExAttr, job, "[AfterProcess]", ex, ErrLevelAttr);
                }

                throw ex;
            }

            sw.Stop();//碼錶停止
        }
 public void CancelJobEmptyId()
 {
     var data = new JobData();
      data.Cancel();
 }
 protected abstract void InternalProcess(User user, Group @group, JobData jobData);
        public async Task Execute(BackgroundProcessContext context)
        {
            //var lockKey = $"{_options.TopicPrefix}delay:lock";
            var  lockKey = $"{_delayTopicName}:lock";
            long delay   = 0; //毫秒
            await _redisStorage.Lock(lockKey, lockTimeSpan, async() =>
            {
                var now      = DateTime.Now;
                var maxScore = DateUtils.GetTimeStamp(now);
                var list     = await _redisStorage.GetTopDueDealyJobId(_delayTopicName, maxScore + PreReadSecond * 1000, BatchCount); //多查询1秒的数据,便于精确控制延迟
                foreach (var item in list)
                {
                    if (context.IsShutdownRequested)
                    {
                        return;
                    }
                    if (_isStart == false)
                    {
                        return;                //已经关闭了 就直接返回吧
                    }
                    if (item.Value > maxScore) //预拉去了PreReadSecond秒的数据,可能有还没到时间的
                    {
                        delay = item.Value - maxScore;
                        break;
                    }

                    var jobId = item.Key;
                    // 延时任务到期加入即时任务队列
                    var hashEntities = await _redisStorage.HashGetAll(Helper.GetJobHashId(_options, jobId));//这里要出错了呢
                    JobData jobData  = null;
                    try
                    {
                        jobData = JobData.ToJobData(hashEntities);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"RedisMessageBus解析延迟任务数据报错");
                    }

                    if (jobData != null)
                    {
                        await _redisStorage.DueDealyJobEnqueue(_delayTopicName, jobData);
                    }
                    else
                    {
                        _logger.LogError("RedisMessageBus延迟任务解析出错为空,这里就从hash中删除了");
                        await _redisStorage.RemoveNullDealyJob(_delayTopicName, jobId);
                    }
                }

                if (list.Count == 0)//没有数据时
                {
                    delay = PreReadSecond * 1000;
                }
            }, async() => await TaskEx.DelayNoException(PreReadSecond * 1000, context.CancellationToken));  //出现并发也休息一会

            if (delay > 0)
            {
                var minDelay = Math.Min((int)delay, PreReadSecond * 1000);
                _redisStorage.WaitForDelayJob(TimeSpan.FromMilliseconds(minDelay), context.CancellationToken);
                //await TaskEx.DelayNoException(Math.Min((int)delay, PreReadSecond * 1000), context.CancellationToken);
            }
        }
        private static void OnVerify(object state)
        {
            mDetectionTimer.Change(-1, -1);
            try
            {
                using (var connection = JobStorage.Current.GetConnection())
                    using (var lockStorage = connection.AcquireDistributedLock("JobAgentServer", TimeSpan.FromSeconds(30)))//防止多个server端竞争
                    {
                        //拿到有上报的jobId集合
                        var jobIdList = connection.GetAllItemsFromSet(keyPrefix);

                        if (jobIdList == null || !jobIdList.Any())
                        {
                            return;
                        }

                        foreach (var jobId in jobIdList)
                        {
                            JobData jobData = connection.GetJobData(jobId);

                            //拿到真正的运行结果
                            var hashKey = keyPrefix + jobId;
                            var result  = connection.GetAllEntriesFromHash(hashKey);
                            using (var tran = connection.CreateWriteTransaction())
                            {
                                //job已经不存在了 就直接删除set
                                if (jobData == null)
                                {
                                    tran.AddJobState(jobId, new SucceededState(null, 0, 0));
                                    tran.RemoveFromSet(keyPrefix, jobId);
                                    tran.Commit();
                                    continue;
                                }

                                double totalMilliseconds = (DateTime.UtcNow - jobData.CreatedAt).TotalMilliseconds;
                                long   latency           = (long)totalMilliseconds;

                                //如果job存在 但是没有拿到hash数据 认为成功
                                if (result == null || !result.Any())
                                {
                                    tran.AddJobState(jobId, new SucceededState(null, latency, latency));
                                    tran.RemoveFromSet(keyPrefix, jobId);
                                    tran.RemoveHash(hashKey);
                                    tran.Commit();
                                    continue;
                                }

                                var            resultOfAgent = result.First();
                                JobAgentResult resultData    = CodingUtil.FromJson <JobAgentResult>(resultOfAgent.Value);

                                //异常数据 认为成功
                                if (resultData == null)
                                {
                                    tran.AddJobState(jobId, new SucceededState(null, latency, latency));
                                    tran.RemoveFromSet(keyPrefix, jobId);
                                    tran.RemoveHash(hashKey);
                                    tran.Commit();
                                    continue;
                                }

                                //jobagent实际上运行的时长
                                long.TryParse(resultOfAgent.Key, out var realTotalMilliseconds);
                                if (realTotalMilliseconds < 1)
                                {
                                    realTotalMilliseconds = latency;
                                }
                                var isSuccess = resultData.R == "ok";
                                tran.RemoveFromSet(keyPrefix, jobId);
                                tran.RemoveHash(hashKey);

                                // latency 代表的是 从开始调度 到 实际结束 总共的时长
                                // realTotalMilliseconds 代表的是 jobagent开始执行 到 实际结束的 总共的时长
                                if (isSuccess)
                                {
                                    var currentState = connection.GetStateData(jobId);
                                    if (currentState != null && !string.IsNullOrEmpty(currentState.Name) &&
                                        currentState.Name.Equals("Failed"))
                                    {
                                        tran.AddJobState(jobId, new SucceededState(null, latency, realTotalMilliseconds));
                                    }
                                    else
                                    {
                                        backgroundJobClient.ChangeState(jobId, new SucceededState(null, latency, realTotalMilliseconds));
                                    }
                                }
                                else
                                {
                                    var jobItem = jobData.Job.Args.FirstOrDefault() as HttpJobItem;
                                    var ex      = new AgentJobException(jobItem.AgentClass, resultData.E);
                                    backgroundJobClient.ChangeState(jobId, new FailedState(ex));
                                    HttpJob.SendFail(jobId, jobItem, "AgentJobFail", ex);
                                }

                                //如果是stop上报过来的时候 记录这个job最后的执行id
                                if (!string.IsNullOrEmpty(resultData.Action) && resultData.Action.Equals("stop") && !string.IsNullOrEmpty(resultData.RunId))
                                {
                                    var jobItem    = jobData.Job.Args.FirstOrDefault() as HttpJobItem;
                                    var jobKeyName =
                                        $"recurring-job:{(!string.IsNullOrEmpty(jobItem.RecurringJobIdentifier) ? jobItem.RecurringJobIdentifier : jobItem.JobName)}";
                                    tran.SetRangeInHash(jobKeyName, new List <KeyValuePair <string, string> > {
                                        new KeyValuePair <string, string>("LastJobId", resultData.RunId)
                                    });
                                }

                                //出错的话 需要走通用的出错流程
                                tran.Commit();
                            }
                        }
                    }
            }
            catch (Exception e)
            {
                Logger.ErrorException("agent reporter fail", e);
            }
            finally
            {
                mDetectionTimer.Change(1000 * 2, 1000 * 2);
            }
        }
Exemplo n.º 53
0
 private void LoggerWriter(JobData job, Logger logger, string MethodName)
 {
     //將 Log 寫入到 FileSystem 中或 EventLog 事件檢視器中.
     logger.Info(string.Format("[{0}].{1}.{2} ", job.JobName, "[DotJob]", MethodName));
 }
Exemplo n.º 54
0
        //*******************************************************************
        /// <summary>ジョブフロー領域の表示</summary>
        //*******************************************************************
        private void ShowJobNet()
        {
            container.ContainerCanvas.Children.Clear();
            container.JobItems.Clear();

            // ジョブデータ(ジョブアイコンの生成用)
            JobData jobData = null;

            // ジョブを表示------------------
            foreach (DataRow row in container.JobControlTable.Select())
            {
                jobData = new JobData();
                // ジョブタイプ
                jobData.JobType = (ElementType)row["job_type"];

                CommonItem room = new CommonItem(container, jobData, Consts.EditType.Modify, (RunJobMethodType)row["method_flag"]);
                // ジョブID
                room.JobId = Convert.ToString(row["job_id"]);
                //ジョブ名
                room.JobName = Convert.ToString(row["job_name"]);
                // X位置
                room.SetValue(Canvas.LeftProperty, Convert.ToDouble(row["point_x"]));
                // Y位置
                room.SetValue(Canvas.TopProperty, Convert.ToDouble(row["point_y"]));

                room.IsEnabled = false;

                // ジョブフロー領域に追加
                container.ContainerCanvas.Children.Add(room);
                container.JobItems.Add(room.JobId, room);
            }

            // フローを表示------------------
            // 開始ジョブID、終了ジョブId
            string startJobId, endJobId;
            // 開始ジョブ、終了ジョブ
            IRoom startJob, endJob;
            // フロー幅
            int flowWidth;
            // フロータイプ(直線、曲線)
            FlowLineType lineType;
            // フロータイプ( 0:通常、 1:TURE、 2:FALSE)
            int flowType = 0;

            foreach (DataRow row in container.FlowControlTable.Select())
            {
                startJobId = Convert.ToString(row["start_job_id"]);
                endJobId   = Convert.ToString(row["end_job_id"]);
                flowWidth  = Convert.ToInt16(row["flow_width"]);
                flowType   = Convert.ToInt16(row["flow_type"]);

                // フロータイプの判定
                if (flowWidth == 0)
                {
                    lineType = FlowLineType.Line;
                }
                else
                {
                    lineType = FlowLineType.Curve;
                }

                startJob = (IRoom)container.JobItems[startJobId];
                endJob   = (IRoom)container.JobItems[endJobId];

                container.MakeFlow(lineType, startJob, endJob, flowType, Consts.EditType.READ);
            }
        }
Exemplo n.º 55
0
 public void DefaultConstructorCreatesEmptyDictionary()
 {
     JobData jobData = new JobData();
     Assert.AreEqual(0, jobData.State.Count);
 }
 /// <summary>
 /// 提供遠端啟動 Job (手動啟動)
 /// </summary>
 /// <param name="jobData"></param>
 public void StartNewScheduleJob(JobData jobData)
 {
     MainThreadContext.Main.StartNewScheduleJob(jobData);
 }
Exemplo n.º 57
0
 public SwitchOff(JobData data)
     : base(data)
 {
 }
 public abstract bool CanProcess(JobData jobData);
Exemplo n.º 59
0
		public void JobData_GetterAndSetter()
		{
			JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger);

			JobData jobData = new JobData();
			spec.JobData = jobData;
			Assert.AreSame(jobData, spec.JobData);
		}
Exemplo n.º 60
0
        public static void OnCreatePlayer(ClusterClient client, INetPacketStream packet)
        {
            var pak = new CreatePlayerPacket(packet);
            var clusterConfiguration = DependencyContainer.Instance.Resolve <ClusterConfiguration>();
            var jobs = DependencyContainer.Instance.Resolve <JobLoader>();

            using (var database = DependencyContainer.Instance.Resolve <IDatabase>())
            {
                DbUser dbUser = database.Users.Get(x =>
                                                   x.Username.Equals(pak.Username, StringComparison.OrdinalIgnoreCase) &&
                                                   x.Password.Equals(pak.Password, StringComparison.OrdinalIgnoreCase));

                // Check if user exist and with good password in database.
                if (dbUser == null)
                {
                    Logger.LogWarning($"[SECURITY] Unable to create new character for user '{pak.Username}' from {client.RemoteEndPoint}. " +
                                      "Reason: bad presented credentials compared to the database.");
                    client.Disconnect();
                    return;
                }

                DbCharacter dbCharacter = database.Characters.Get(x => x.Name == pak.Name);

                // Check if character name is not already used.
                if (dbCharacter != null)
                {
                    Logger.LogWarning($"Unable to create new character for user '{pak.Username}' from {client.RemoteEndPoint}. " +
                                      $"Reason: character name '{pak.Name}' already exists.");
                    ClusterPacketFactory.SendError(client, ErrorType.USER_EXISTS);
                    return;
                }

                DefaultCharacter  defaultCharacter = clusterConfiguration.DefaultCharacter;
                DefaultStartItems defaultEquipment = pak.Gender == 0 ? defaultCharacter.Man : defaultCharacter.Woman;
                JobData           jobData          = jobs[pak.Job];

                dbCharacter = new DbCharacter()
                {
                    UserId       = dbUser.Id,
                    Name         = pak.Name,
                    Slot         = pak.Slot,
                    SkinSetId    = pak.SkinSet,
                    HairColor    = (int)pak.HairColor,
                    FaceId       = pak.HeadMesh,
                    HairId       = pak.HairMeshId,
                    BankCode     = pak.BankPassword,
                    Gender       = pak.Gender,
                    ClassId      = pak.Job,
                    Hp           = HealthFormulas.GetMaxOriginHp(defaultCharacter.Level, defaultCharacter.Stamina, jobData.MaxHpFactor),
                    Mp           = HealthFormulas.GetMaxOriginMp(defaultCharacter.Level, defaultCharacter.Intelligence, jobData.MaxMpFactor, true),
                    Fp           = HealthFormulas.GetMaxOriginFp(defaultCharacter.Level, defaultCharacter.Stamina, defaultCharacter.Dexterity, defaultCharacter.Strength, jobData.MaxFpFactor, true),
                    Strength     = defaultCharacter.Strength,
                    Stamina      = defaultCharacter.Stamina,
                    Dexterity    = defaultCharacter.Dexterity,
                    Intelligence = defaultCharacter.Intelligence,
                    MapId        = defaultCharacter.MapId,
                    PosX         = defaultCharacter.PosX,
                    PosY         = defaultCharacter.PosY,
                    PosZ         = defaultCharacter.PosZ,
                    Level        = defaultCharacter.Level,
                    Gold         = defaultCharacter.Gold,
                    StatPoints   = 0, //TODO: create game constants.
                    SkillPoints  = 0, //TODO: create game constants.
                    Experience   = 0,
                };

                //TODO: create game constants for slot.
                dbCharacter.Items.Add(new DbItem(defaultEquipment.StartSuit, 44));
                dbCharacter.Items.Add(new DbItem(defaultEquipment.StartHand, 46));
                dbCharacter.Items.Add(new DbItem(defaultEquipment.StartShoes, 47));
                dbCharacter.Items.Add(new DbItem(defaultEquipment.StartWeapon, 52));

                database.Characters.Create(dbCharacter);
                database.Complete();
                Logger.LogInformation("Character '{0}' has been created successfully for user '{1}' from {2}.",
                                      dbCharacter.Name, pak.Username, client.RemoteEndPoint);

                ClusterPacketFactory.SendPlayerList(client, pak.AuthenticationKey, dbUser.Characters);
            }
        }