private JobResult StartWorkflow()
        {
            if (_workflow.Count == 0)
            {
                return(new JobResult(
                           JobStatus.CompletedWithError,
                           new AutoJobException(Current.Id, null, _msgNoWorkflow)));
            }

            if (!mLock.WaitOne())
            {
                return(null);
            }

            JobResult result   = null;
            var       jobQueue = new Queue <IAutomatedJob>();

            _workflow.ForEach(j => { jobQueue.Enqueue(j); });
            IJobContext context = null;

            context = GetJobContext();
            result  = ProcessJobs(jobQueue, context);

            mLock.ReleaseMutex();
            return(result);
        }
示例#2
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            //Gets the mail-addresses with googlemail.com or gmail.com
            foreach (MailAddressEntryObject recipient in _recipientsEntry)
            {
                if (recipient.Address.Address.EndsWith("@gmail.com") ||
                    recipient.Address.Address.EndsWith("@googlemail.com"))
                {
                    _recipients.Add(recipient.Address.Address);
                }
            }
            string to = String.Join(",", _recipients.ToArray());

            //TODO Fetching Longitude and Latitude!
            Dictionary<String, String> geoCode =
                Helpers.GetGeocodes(operation.Einsatzort.Location + " " + operation.Einsatzort.Street + " " + operation.Einsatzort.StreetNumber);
            String longitude = "0";
            String latitude = "0";
            if (geoCode != null)
            {
                longitude = geoCode[Resources.LONGITUDE];
                latitude = geoCode[Resources.LATITUDE];
            }
            String body = operation.ToString(SettingsManager.Instance.GetSetting("eAlarm", "text").GetString());
            String header = operation.ToString(SettingsManager.Instance.GetSetting("eAlarm", "header").GetString());
            var postParameters = new Dictionary<string, string>
                                     {
                                         {"email", to},
                                         {"header", header},
                                         {"text", body},
                                         {"long", longitude},
                                         {"lat", latitude}
                                     };
            string postData = postParameters.Keys.Aggregate("",
                                                            (current, key) =>
                                                            current +
                                                            (HttpUtility.UrlEncode(key) + "=" +
                                                             HttpUtility.UrlEncode(postParameters[key]) + "&"));

            byte[] data = Encoding.UTF8.GetBytes(postData);
            webRequest.ContentLength = data.Length;

            Stream requestStream = webRequest.GetRequestStream();
            var webResponse = (HttpWebResponse)webRequest.GetResponse();
            Stream responseStream = webResponse.GetResponseStream();

            requestStream.Write(data, 0, data.Length);
            requestStream.Close();

            if (responseStream != null)
            {
                var reader = new StreamReader(responseStream, Encoding.Default);
                string pageContent = reader.ReadToEnd();
                reader.Close();
                responseStream.Close();
                webResponse.Close();

                //TODO Analyzing Response
            }
        }
示例#3
0
        public override void Execute(PlacementAction action, IJobContext context)
        {
            var display = context.Display;

            if (action.Placement.DisplayIndex is int displayIndex)
            {
                if (_displayService.Displays.ContainsKey(displayIndex))
                {
                    display = _displayService.Displays[displayIndex];
                }
                else
                {
                    return;
                }
            }

            if (action.Placement.Bounds == null)
            {
                var bounds = display.WorkingArea;
                User32Api.SetWindowPos(context.Window.Handle, IntPtr.Zero, bounds.X, bounds.Y, bounds.Width, bounds.Height, WindowPos.SWP_SHOWWINDOW);
                User32Api.ShowWindow(context.Window.Handle, ShowWindowCommands.ShowMaximized);
            }
            else
            {
                var bounds = display.WorkingArea.CropByPercentage(action.Placement.Bounds) + context.Window.Border;
                User32Api.SetWindowPos(context.Window.Handle, IntPtr.Zero, bounds.X, bounds.Y, bounds.Width, bounds.Height, WindowPos.SWP_SHOWWINDOW);
            }
        }
        public void Execute(IJobContext context)
        {
            int parsedTimeout;
            var timeout = context.Parameters != null &&
                          context.Parameters.ContainsKey("expirationtimeout") &&
                          int.TryParse(context.Parameters["expirationtimeout"], out parsedTimeout) &&
                          parsedTimeout > 0 ? parsedTimeout  : 5;//Default timeout 5mins

            using (_marketingRepository)
            {
                var expiredTime       = DateTime.UtcNow.AddMinutes(-timeout);
                var expiredPromotions = _marketingRepository.PromotionUsages.Where(p =>
                                                                                   p.Status == (int)PromotionUsageStatus.Reserved && p.UsageDate.HasValue &&
                                                                                   p.UsageDate.Value < expiredTime).ToList();

                if (expiredPromotions.Any())
                {
                    foreach (var item in expiredPromotions)
                    {
                        //item.Status = (int)PromotionUsageStatus.Expired;
                        _marketingRepository.Remove(item);
                    }
                    _marketingRepository.UnitOfWork.Commit();
                }
            }
        }
        public void Execute(IJobContext context)
        {
                var currentTime = DateTime.UtcNow;
                var statusFilter = OrderStatus.Pending.ToString();

                using (_storeRepository)
                using (_orderRepository)
                {
                    var stores = _storeRepository.Stores.Expand(x => x.FulfillmentCenter).ToList();

                    var items = _orderRepository.Orders
                        .Where(x => x.Status == statusFilter)
                        .Expand("OrderForms/Shipments")
                        .ToArray();

                    foreach (var item in items)
                    {
                        var store = stores.FirstOrDefault(x => x.StoreId == item.StoreId);
                        if (store != null
                            && store.FulfillmentCenter != null
                            && item.Created.HasValue
                            && item.Created.Value.AddMinutes(store.FulfillmentCenter.PickDelay) < currentTime)
                        {
                            item.Status = OrderStatus.InProgress.ToString();
                            if (item.OrderForms.Any())
                            {
                                item.OrderForms[0].Shipments.ToList()
                                    .ForEach(x => x.Status = ShipmentStatus.InventoryAssigned.ToString());
                            }
                            _orderRepository.UnitOfWork.Commit();
                        }
                    }
                }
            }
        private void PrintFaxes(IJobContext context, Operation operation)
        {
            if (!context.Parameters.ContainsKey("ArchivedFilePath") || !context.Parameters.ContainsKey("ImagePath"))
            {
                Logger.Instance.LogFormat(LogType.Trace, this, Resources.NoPrintingPossible);
                return;
            }

            System.IO.FileInfo sourceImageFile = new System.IO.FileInfo((string)context.Parameters["ImagePath"]);
            if (!sourceImageFile.Exists)
            {
                Logger.Instance.LogFormat(LogType.Error, this, Resources.FileNotFound, sourceImageFile.FullName);
                return;
            }

            // Grab all created files to print
            string imagePath = (string)context.Parameters["ImagePath"];

            foreach (string queueName in _settings.GetSetting("AlarmSourcePrinterJob", "PrintingQueueNames").GetStringArray())
            {
                var queues = _settings.GetSetting(SettingKeys.PrintingQueuesConfiguration).GetValue<PrintingQueuesConfiguration>();
                PrintingQueue pq = queues.GetPrintingQueue(queueName);
                if (pq == null || !pq.IsEnabled)
                {
                    continue;
                }

                PrintFaxTask task = new PrintFaxTask();
                task.ImagePath = imagePath;
                task.Print(pq);
            }
        }
示例#7
0
 void IJob.Execute(IJobContext context, Operation operation)
 {
     if (context.Phase == JobPhase.AfterOperationStored)
     {
         Execute(operation);
     }
 }
示例#8
0
        public void Execute(IJobContext context)
        {
            var currentTime  = DateTime.UtcNow;
            var statusFilter = OrderStatus.Pending.ToString();

            using (_storeRepository)
                using (_orderRepository)
                {
                    var stores = _storeRepository.Stores.Expand(x => x.FulfillmentCenter).ToList();

                    var items = _orderRepository.Orders
                                .Where(x => x.Status == statusFilter)
                                .Expand("OrderForms/Shipments")
                                .ToArray();

                    foreach (var item in items)
                    {
                        var store = stores.FirstOrDefault(x => x.StoreId == item.StoreId);
                        if (store != null &&
                            store.FulfillmentCenter != null &&
                            item.Created.HasValue &&
                            item.Created.Value.AddMinutes(store.FulfillmentCenter.PickDelay) < currentTime)
                        {
                            item.Status = OrderStatus.InProgress.ToString();
                            if (item.OrderForms.Any())
                            {
                                item.OrderForms[0].Shipments.ToList()
                                .ForEach(x => x.Status = ShipmentStatus.InventoryAssigned.ToString());
                            }
                            _orderRepository.UnitOfWork.Commit();
                        }
                    }
                }
        }
示例#9
0
        public void RenderPlacement(WindowPlacement previewPlacement, IJobContext context)
        {
            var currentDisplayIndex = context.Display.Index;
            var targetDisplayIndex  = previewPlacement.DisplayIndex;

            foreach (var preview in _previews)
            {
                var previewDisplayIndex = preview.Display.Index;

                var renderOnAny     = !targetDisplayIndex.HasValue && currentDisplayIndex == previewDisplayIndex;
                var renderOnCurrent = targetDisplayIndex.HasValue && targetDisplayIndex.Value == previewDisplayIndex;
                if (renderOnAny || renderOnCurrent)
                {
                    var workingArea = new Rectangle(Point.Empty, preview.WorkingArea.Size);
                    var bounds      = previewPlacement.Bounds != null
                        ? workingArea.CropByPercentage(previewPlacement.Bounds)
                        : workingArea;

                    preview.Placement = bounds;
                }
                else
                {
                    preview.Placement = null;
                }
            }
        }
        public Connection ToAdditionalInfoConnection(IJobContext jobContext)
        {
            if (jobContext == null)
            {
                return(null);
            }
            Connection connection = new Connection();

            connection.ConnectionOpenTime = this.m_openConnectionDurationMs;
            connection.ConnectionFromPool = this.m_connectionFromPool;
            if (jobContext.ExecutionLogLevel == ExecutionLogLevel.Verbose)
            {
                DataSource dataSource = new DataSource();
                dataSource.Name = this.m_dataSourceName;
                if (this.m_dataSourceReference != null)
                {
                    dataSource.DataSourceReference = this.m_dataSourceReference;
                }
                else if (this.m_embeddedConnectionString != null)
                {
                    dataSource.ConnectionString = this.m_embeddedConnectionString;
                }
                dataSource.DataExtension = this.m_dataSourceType;
                connection.DataSource    = dataSource;
            }
            if (this.m_dataSetsMetrics != null)
            {
                connection.DataSets = new List <DataSet>(this.m_dataSetsMetrics.Length);
                for (int i = 0; i < this.m_dataSetsMetrics.Length; i++)
                {
                    connection.DataSets.Add(this.m_dataSetsMetrics[i].ToAdditionalInfoDataSet(jobContext));
                }
            }
            return(connection);
        }
示例#11
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            IList <MobilePhoneEntryObject> recipients = GetRecipients(operation);

            if (recipients.Count == 0)
            {
                Logger.Instance.LogFormat(LogType.Info, this, Properties.Resources.NoRecipientsErrorMessage);
                return;
            }

            string format = _settings.GetSetting("SMSJob", "MessageFormat").GetValue <string>();
            string text   = operation.ToString(format);

            text = text.Replace("Ö", "Oe").Replace("Ä", "Ae").Replace("Ü", "Ue").Replace("ö", "oe").Replace("ä", "ae").Replace("ü", "ue").Replace("ß", "ss");
            // Truncate the string if it is too long
            text = text.Truncate(160, true, true);

            // Invoke the provider-send asynchronous because it is a web request and may take a while
            _provider.Send(_userName, _password, recipients.Select(r => r.PhoneNumber), text);
        }
示例#12
0
        protected override bool CheckCore(IJobContext context)
        {
            var bounds = context.Display.WorkingArea;
            var area   = bounds.CropByPercentage(Area);

            return(area.Contains(context.CursorPosition));
        }
示例#13
0
        public void Execute(IJobContext context)
        {
            var scope = context.Parameters != null && context.Parameters.ContainsKey("scope")
                ? context.Parameters["scope"] : "default";

            _controller.Process(scope);
        }
示例#14
0
        public async Task ExecuteAsync(IJobContext jobctx, CancellationToken cancellation)
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var ctx = scope.ServiceProvider.GetService <ApplicationDbContext>();
                _logger.LogInformation("訊息通知(超過7天)");

                //var mindate = DateTime.Today.AddDays(-60);
                //var vv = ctx.Set<CruxMessage>()
                //    .Where(x => x.Created < mindate)
                //    ;
                //var c = 0;
                //foreach (var v in vv)
                //{
                //    ctx.Remove(v);
                //    c++;
                //}

                //if (c > 0)
                //{
                //    await ctx.SaveChangesAsync();
                //    _logger.LogInformation($"共{c}筆資料刪除");
                //}

                await Task.Delay(1000);

                _logger.LogInformation("Success");
            }
        }
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            if (_configuration.CustomTextExportEnabled)
            {
                try
                {
                    ExportCustomTextFile(operation);
                }
                catch (Exception ex)
                {
                    Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.ExportToCustomFailed);
                    Logger.Instance.LogException(this, ex);
                }
            }

            if (_configuration.EvaExportEnabled)
            {
                try
                {
                    ExportEvaFile(operation);
                }
                catch (Exception ex)
                {
                    Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.ExportToEVAFailed);
                    Logger.Instance.LogException(this, ex);
                }
            }
        }
示例#16
0
 void IJob.Execute(IJobContext context, Operation operation)
 {
     if (context.Phase == JobPhase.OnOperationSurfaced)
     {
         AnalyzeLoopsInfoFile(operation);
     }
 }
示例#17
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            string   key   = operation.ToString(_settings.GetSetting("Divera", "key").GetValue <string>());
            TimeSpan delay = DateTime.Now - operation.Timestamp;

            Content content = new Content()
            {
                type    = operation.ToString(_settings.GetSetting("Divera", "type").GetValue <string>()),
                text    = operation.ToString(_settings.GetSetting("Divera", "text").GetValue <string>()),
                address = operation.Einsatzort.ToString(),
                lat     = (float?)operation.Einsatzort.GeoLatitude,
                lng     = (float?)operation.Einsatzort.GeoLongitude,
                ric     = string.Join(",", operation.Loops),
                vehicle = string.Join(",", GetEMKList(operation)),
                delay   = delay.Seconds
            };

            HttpStatusCode result = 0;

            if (!SendNotification(content, key, ref result))
            {
                Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.ErrorSendingNotification, result);
            }
        }
示例#18
0
        public JobWebSocketServerTest(IJobContext jobContext) : base(jobContext, JOB_TYPE.WEB_SOCKET_SERVER)
        {
            fileData = new ConcurrentDictionary <string, string>();

            server          = new WebSocketServer("ws://0.0.0.0:" + this.Port.ToString());
            this.allSockets = new List <IWebSocketConnection>();
        }
示例#19
0
        public static async Task Execute(IJobContext context)
        {
            if (!CliUtils.ParseArgs(Options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var ruleList = Main.GatherRuleRepository.GetGatherRuleIdList(_includes, _excludes);

            foreach (var(id, siteId) in ruleList)
            {
                var guid = Guid.NewGuid().ToString();

                await Main.GatherRuleRepository.GatherChannelsAsync(null, siteId, id, guid, true);
            }

            await CliUtils.PrintRowLineAsync();

            await Console.Out.WriteLineAsync("恭喜,采集任务执行成功!");
        }
示例#20
0
文件: StatusJob.cs 项目: qkb/Datory
        public async Task RunAsync(IJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            await Console.Out.WriteLineAsync($"SiteServer CLI 版本号: {version.Substring(0, version.Length - 2)}");

            await Console.Out.WriteLineAsync($"当前文件夹: {_settings.ContentRootPath}");

            await Console.Out.WriteLineAsync();

            await Console.Out.WriteLineAsync($"数据库类型: {_settings.Database.DatabaseType.GetValue()}");

            await Console.Out.WriteLineAsync($"连接字符串: {_settings.Database.ConnectionString}");

            var(isConnectionWorks, errorMessage) = await CliUtils.CheckSettingsAsync(_settings);

            if (!isConnectionWorks)
            {
                await Console.Out.WriteLineAsync($"数据库连接错误: {errorMessage}");
            }
            else
            {
                await Console.Out.WriteLineAsync("数据库连接成功!");
            }
        }
示例#21
0
        public async Task RunAsync(IJobContext context, string sqlId, string statusId)
        {
            var hour = DateTime.Now.Hour;

            if (hour == 10 || hour == 16)
            {
                var list = PushDataDal.Instance.GetBadPushList();
                var str  = $"[EPC A-Scan+合包]系统检测有[{list.Count}]单推送给WISH失败了!相关错误单号的查询语句如下:" +
                           $"\r\n select  * from EPC_PushMessage where  Taskid in (";
                if (list.Any())
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (i != (list.Count - 1))
                        {
                            str += $"'{list[i]}',";
                        }
                        else
                        {
                            str += $"'{list[i]}'";
                        }
                    }
                    DingDing(str + ")");
                }
            }
            Thread.Sleep(60 * 1000 * 60);
        }
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            if (_configuration.AMExportEnabled)
            {
                try
                {
                    ExportAlarmMonitorFile(operation);
                }
                catch (Exception ex)
                {
                    Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.ExportToAMFailed);
                    Logger.Instance.LogException(this, ex);
                }
            }

            if (_configuration.EvaExportEnabled)
            {
                try
                {
                    ExportEvaFile(operation);
                }
                catch (Exception ex)
                {
                    Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.ExportToEVAFailed);
                    Logger.Instance.LogException(this, ex);
                }
            }
        }
		public void Execute(IJobContext context)
		{
		    int parsedTimeout;
			var timeout = context.Parameters != null
                && context.Parameters.ContainsKey("expirationtimeout") 
                && int.TryParse(context.Parameters["expirationtimeout"], out parsedTimeout) 
                && parsedTimeout > 0 ? parsedTimeout  : 5; //Default timeout 5mins
            
		        using (_marketingRepository)
		        {
                    var expiredTime =  DateTime.UtcNow.AddMinutes(-timeout);
		            var expiredPromotions =_marketingRepository.PromotionUsages.Where(p =>
		                        p.Status == (int) PromotionUsageStatus.Reserved && p.UsageDate.HasValue &&
		                        p.UsageDate.Value < expiredTime).ToList();

		            if (expiredPromotions.Any())
		            {
		                foreach (var item in expiredPromotions)
		                {
		                    //item.Status = (int)PromotionUsageStatus.Expired;
                            _marketingRepository.Remove(item);
		                }
		                _marketingRepository.UnitOfWork.Commit();
		            }
		        }

		}
 void IJob.Execute(IJobContext context, Operation operation)
 {
     if (context.Phase == JobPhase.OnOperationSurfaced)
     {
         AnalyzeLoopsInfoFile(operation);
     }
 }
示例#25
0
 public JobBaseUrl(IJobContext jobContext, JOB_TYPE type)
 {
     this.JobContext = jobContext;
     this.Id         = jobContext.f_getTotalJob() + 1;
     this.Type       = type;
     this.Status     = 1; /* 1: init */
 }
        private void PrintFaxes(IJobContext context, Operation operation)
        {
            if (!context.Parameters.ContainsKey("ArchivedFilePath") || !context.Parameters.ContainsKey("ImagePath"))
            {
                Logger.Instance.LogFormat(LogType.Trace, this, Resources.NoPrintingPossible);
                return;
            }

            FileInfo sourceImageFile = new FileInfo((string)context.Parameters["ImagePath"]);

            if (!sourceImageFile.Exists)
            {
                Logger.Instance.LogFormat(LogType.Error, this, Resources.FileNotFound, sourceImageFile.FullName);
                return;
            }

            string imagePath = (string)context.Parameters["ImagePath"];

            foreach (string queueName in _settings.GetSetting("AlarmSourcePrinterJob", "PrintingQueueNames").GetStringArray())
            {
                var           queues = _settings.GetSetting(SettingKeys.PrintingQueuesConfiguration).GetValue <PrintingQueuesConfiguration>();
                PrintingQueue pq     = queues.GetPrintingQueue(queueName);
                if (pq == null || !pq.IsEnabled)
                {
                    continue;
                }

                PrintFaxTask task = new PrintFaxTask();
                task.ImagePath = imagePath;
                task.Print(pq);
            }
        }
示例#27
0
 private void ParallelPreloadQueries(OnDemandProcessingContext odpContext)
 {
     if (this.m_useParallelQueryExecution)
     {
         IJobContext jobContext = odpContext.JobContext;
     }
 }
 public void Execute(IJobContext context)
 {
     if (database != null)
     {
         database.ExecuteSqlCommand("EXEC UpdateStatistics");
     }
 }
示例#29
0
        public override void Execute(SnapAction action, IJobContext context)
        {
            var workingArea = context.Display.WorkingArea;
            var bounds      = context.Window.Bounds;

            switch (action.ResizeType)
            {
            case ResizeType.Vertical:
                bounds = new Rectangle(
                    bounds.Left,
                    workingArea.Top,
                    bounds.Width,
                    workingArea.Height);
                break;

            case ResizeType.Horizontal:
                bounds = new Rectangle(
                    workingArea.Left,
                    bounds.Top,
                    workingArea.Width,
                    bounds.Height);
                break;

            default:
                return;
            }

            bounds += context.Window.Border;

            User32Api.SetWindowPos(context.Window.Handle, IntPtr.Zero, bounds.X, bounds.Y, bounds.Width, bounds.Height, WindowPos.SWP_SHOWWINDOW);
        }
示例#30
0
        public JobMessage(IJobContext jobContext) : base(jobContext, JOB_TYPE.MESSAGE)
        {
            //this.Messages = new QueueThreadSafe<Message>();

            //this.ResponseIds = new QueueThreadSafe<Guid>();
            //this.ResponseMessages = new DictionaryThreadSafe<Guid, Message>();
            //this.RequestMessageGroup = new DictionaryThreadSafe<Guid, List<Guid>>();
            //this.RequestMessageGroupTotal = new DictionaryThreadSafe<Guid, int>();

            this.MessagesRequest = new DictionaryThreadSafe <Guid, Message>();
            this.MessagesRequestTimeOutExpire = new ListThreadSafe <Guid>();
            this.MessagesRequestTimeOut       = new ListDoubleThreadSafe <long, Guid>();
            this.timer = new System.Threading.Timer(new System.Threading.TimerCallback((obj) =>
            {
                if (this.MessagesRequestTimeOut.Count == 0)
                {
                    return;
                }

                long timeStart = DateTime.Now.Ticks / 1000;
                Guid[] ids     = this.MessagesRequestTimeOut.FindItem1LessThanAndRemove(FUNC_TIME_OUT_FILTER, timeStart);
                if (ids.Length > 0)
                {
                    foreach (var t in ids)
                    {
                        Tracer.WriteLine("RESPONSE TIME_OUT: {0}", t);
                    }

                    this.MessagesRequestTimeOutExpire.AddRange(ids);
                }
            }), null, 100, 100);
        }
 void IJob.Execute(IJobContext context, Operation operation)
 {
     if (context.Phase == JobPhase.AfterOperationStored)
     {
         PrintOperation(operation);
     }
 }
示例#32
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            // Construct Notification text
            string body = "Einsatz:\r\n";
            body += "Zeitstempel: " + operation.Timestamp.ToString() + "\r\n";
            body += "Stichwort: " + operation.Keywords.Keyword + "\r\n";
            body += "Meldebild: " + operation.Picture + "\r\n";
            body += "Einsatznr: " + operation.OperationNumber + "\r\n";
            body += "Hinweis: " + operation.Comment + "\r\n";
            body += "Mitteiler: " + operation.Messenger + "\r\n";
            body += "Einsatzort: " + operation.Einsatzort.Location + "\r\n";
            body += "Straße: " + operation.Einsatzort.Street + " " + operation.Einsatzort.StreetNumber + "\r\n";
            body += "Ort: " + operation.Einsatzort.ZipCode + " " + operation.Einsatzort.City + "\r\n";
            body += "Objekt: " + operation.Einsatzort.Property + "\r\n";

            ProwlNotification notifi = new ProwlNotification();
            notifi.Priority = ProwlNotificationPriority.Emergency;
            notifi.Event = "Feuerwehr Einsatz";
            notifi.Description = body;

            //Send the Message
            try
            {
                _client.PostNotification(notifi);
            }
            catch (Exception ex)
            {
                Logger.Instance.LogFormat(LogType.Error, this, "An error occurred while sending the Prowl Messages.", ex);
            }
        }
示例#33
0
        public JobWebSocketClientTest(IJobContext jobContext) : base(jobContext, JOB_TYPE.WEB_SOCKET_CLIENT)
        {
            this.URL = "ws://0.0.0.0:" + this.Port.ToString();

            // Create a TCP/IP socket.
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
示例#34
0
 public JobFileHttp(IJobContext jobContext) : base(jobContext, JOB_TYPE.FILE_HTTP_CACHE)
 {
     fileData                = new ConcurrentDictionary <string, string>();
     server                  = new HttpServer();
     server.EndPoint.Port    = this.Port;
     server.RequestReceived += f_server_onRequestReceived;
 }
示例#35
0
        protected IDataReader RunLiveQuery(List <Microsoft.ReportingServices.ReportIntermediateFormat.ParameterValue> queryParams, object[] paramValues)
        {
            IDataReader reader     = null;
            IDbCommand  command    = null;
            IJobContext jobContext = m_odpContext.JobContext;

            if (m_dataSourceConnection == null)
            {
                m_dataSourceConnection = RuntimeDataSource.OpenConnection(m_dataSource, m_dataSet, m_odpContext, m_executionMetrics);
            }
            try
            {
                m_executionMetrics.StartTimer(DataProcessingMetrics.MetricType.Query);
                command = CreateCommand();
                SetCommandParameters(command, queryParams, paramValues);
                string commandText = SetCommandText(command);
                StoreCommandText(commandText);
                SetCommandType(command);
                SetTransaction(command);
                m_odpContext.CheckAndThrowIfAborted();
                SetCommandTimeout(command);
                ExtractRewrittenCommandText(command);
                SetRestartPosition(command);
                DataSourceInfo dataSourceInfo = null;
                if (command is IDbImpersonationNeededForCommandCancel)
                {
                    dataSourceInfo = m_dataSource.GetDataSourceInfo(m_odpContext);
                }
                m_command = command;
                m_commandWrappedForCancel = new CommandWrappedForCancel(m_command, m_odpContext.CreateAndSetupDataExtensionFunction, m_dataSource, dataSourceInfo, m_dataSet.Name, m_dataSourceConnection);
                if (jobContext != null)
                {
                    jobContext.SetAdditionalCorrelation(m_command);
                    jobContext.ApplyCommandMemoryLimit(m_command);
                }
                DataSourceErrorInspector errorInspector = CreateErrorInspector();
                reader = ExecuteReader(jobContext, errorInspector, commandText);
                StoreDataReader(reader, errorInspector);
                return(reader);
            }
            catch (RSException)
            {
                EagerInlineCommandAndReaderCleanup(ref reader, ref command);
                throw;
            }
            catch (Exception e)
            {
                if (AsynchronousExceptionDetection.IsStoppingException(e))
                {
                    throw;
                }
                EagerInlineCommandAndReaderCleanup(ref reader, ref command);
                throw;
            }
            finally
            {
                m_executionMetrics.RecordTimerMeasurement(DataProcessingMetrics.MetricType.Query);
            }
        }
 public ExecuteQueriesContext(IDbConnection connection, IProcessingDataExtensionConnection dataExtensionConnection, DataSourceInfo dataSourceInfo, CreateAndRegisterStream createAndRegisterStream, IJobContext jobContext)
 {
     this.m_connection = connection;
     this.m_dataExtensionConnection = dataExtensionConnection;
     this.m_dataSourceInfo          = dataSourceInfo;
     this.m_createAndRegisterStream = createAndRegisterStream;
     this.m_jobContext = jobContext;
 }
 void IJob.Execute(IJobContext context, Operation operation)
 {
     // This is a Pre-Job. Thus it only has to run right after the operation has surfaced and before being stored.
     if (context.Phase == JobPhase.OnOperationSurfaced)
     {
         AnalyzeLoopsInfoFile(operation);
     }
 }
 private void Init()
 {
     _workflow.Clear();
     _workflow.AddRange(Current.Workflow);
     _jobStatus    = new ConcurrentDictionary <string, JobStatus>();
     _currentJobId = null;
     _context      = null;
 }
示例#39
0
 void IJob.Execute(IJobContext context, Operation operation)
 {
     // This is a Pre-Job. Thus it only has to run right after the operation has surfaced and before being stored.
     if (context.Phase == JobPhase.OnOperationSurfaced)
     {
         AnalyzeLoopsInfoFile(operation);
     }
 }
示例#40
0
 void IJob.Execute(IJobContext context, Operation operation)
 {
     if (context.Phase != JobPhase.AfterOperationStored)
     {
         return;
     }
     Task.Factory.StartNew(() => NotifyProwl(operation));
     Task.Factory.StartNew(() => NotifyMyAndroid(operation));
 }
示例#41
0
        /// <summary>
        /// Executes the jobs that are registered at this job manager.
        /// </summary>
        /// <param name="context">The context  on which basis the jobs are executed.</param>
        /// <param name="operation">The operation on which basis the jobs are executed.</param>
        public void ExecuteJobs(IJobContext context, Operation operation)
        {
            AssertNotDisposed();

            foreach (IJob job in _jobs)
            {
                RunJob(context, operation, job);
            }
        }
示例#42
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            SendMail(operation, context);
        }
 void IJob.Execute(IJobContext context, Operation operation)
 {
     // TODO: May be made modular using a plug-in system and/or delegates in the future!
     switch (context.AlarmSourceName)
     {
         case "FaxAlarmSource": PrintFaxes(context, operation); break;
         default:
             break;
     }
 }
示例#44
0
文件: Importer.cs 项目: peterzhao/aft
        private void Enqueue(SyncObject obj, IJobContext jobContext)
        {
            try
            {
                _destination.Enqueue(_queueName, obj);
                jobContext.CountSuccess();

            }
            catch(Exception ex)
            {
                _errorHandler.HandleSyncObjectFailure(obj, this, ex);
            }
        }
示例#45
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            string header = _settings.GetSetting(SettingKeysJob.Header).GetValue<string>();

            string expression = _settings.GetSetting(SettingKeysJob.MessageContent).GetValue<string>();
            string message = operation.ToString(expression);

            Task.Factory.StartNew(() => SendToProwl(operation, message, header));
            Task.Factory.StartNew(() => SendToNotifyMyAndroid(operation, message, header));
        }
示例#46
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (_configurations.Count == 0)
            {
                return;
            }

            // Remember timestamp for automatically turning them off
            _lastAlarmTimestamp = DateTime.UtcNow;

            foreach (DisplayConfiguration dc in _configurations)
            {
                dc.TurnOn();
            }
        }
        void IJob.Execute(IJobContext context, Operation operation)
        {
            // TODO: Job phase could be "surfaced" as well?
            if (context.Phase != JobPhase.OnOperationSurfaced)
            {
                return;
            }

            switch (context.AlarmSourceName)
            {
                case "FaxAlarmSource": PrintFaxes(context, operation); break;
                default:
                    Logger.Instance.LogFormat(LogType.Trace, this, Resources.NoPrintingPossible);
                    break;
            }
        }
示例#48
0
文件: Importer.cs 项目: peterzhao/aft
 public void Start(IJobContext jobContext)
 {
     for (int batchCount = 1; ; batchCount++)
     {
         Logger.Debug(string.Format("Running batch {0} of {1} with batch size: {2} starting at {3} ", batchCount, Name, _batchSize, jobContext.CurrentRecord));
         var currentBatch = _source.GetBatchOfObjects(_objectType,
                                                  _batchSize,
                                                  jobContext.CurrentRecord,
                                                  jobContext.MinimumModificationDate).ToList();
         currentBatch.ForEach(syncObject => Enqueue(syncObject, jobContext));
         if (currentBatch.Any())
             jobContext.SetCurrentRecord(currentBatch.Last().SalsaKey);
         else
             break;
     };
 }
        void IJob.Execute(IJobContext context, Operation operation)
        {
            // TODO: Job phase could be "surfaced" as well?
            if (context.Phase != JobPhase.OnOperationSurfaced)
            {
                return;
            }

            // TODO: May be made modular using a plug-in system and/or delegates in the future!
            switch (context.AlarmSourceName)
            {
                case "FaxAlarmSource": PrintFaxes(context, operation); break;
                default:
                    Logger.Instance.LogFormat(LogType.Trace, this, Resources.NoPrintingPossible);
                    break;
            }
        }
示例#50
0
文件: Exporter.cs 项目: peterzhao/aft
 public void Start(IJobContext jobContext)
 {
     for (int batchCount = 1; ; batchCount++)
     {
         if(!Config.SalsaWritable) throw new AccessViolationException(String.Format("Cannot export objects to Salsa. {0} is in read-only mode.", Config.Environment));
         Logger.Debug("Dequeue in batch " + batchCount + " with batch size:" + _batchSize + " " + Name);
         var currentBatch = _source.GetBatchOfObjects(_objectType,
                                                  _queueName,
                                                  _batchSize,
                                                  jobContext.CurrentRecord).ToList();
         var tasks = currentBatch.Select(syncObject => Task.Factory.StartNew(arg => ExportSyncObject(syncObject, jobContext), null));
         Task.WaitAll(tasks.ToArray());
         Logger.Trace("Updating current record...");
         if (currentBatch.Any())
             jobContext.SetCurrentRecord(currentBatch.Last().QueueId);
         else
             break;
     };
 }
示例#51
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            string body = operation.ToString(_settings.GetSetting("eAlarm", "text").GetValue<string>());
            string header = operation.ToString(_settings.GetSetting("eAlarm", "header").GetValue<string>());
            string location = operation.Einsatzort.ToString();

            bool encryption = _settings.GetSetting("eAlarm", "Encryption").GetValue<bool>();
            if (encryption)
            {
                string encryptionKey = _settings.GetSetting("eAlarm", "EncryptionKey").GetValue<string>();

                body = Helper.Encrypt(body, encryptionKey);
                header = Helper.Encrypt(header, encryptionKey);
                location = Helper.Encrypt(location, encryptionKey);
            }

            string[] to = GetRecipients(operation).Where(pushEntryObject => pushEntryObject.Consumer == "eAlarm").Select(pushEntryObject => pushEntryObject.RecipientApiKey).ToArray();

            Content content = new Content()
            {
                registration_ids = to,
                data = new Content.Data()
               {
                   awf_title = header,
                   awf_message = body,
                   awf_location = location
               }
            };

            string message = new JavaScriptSerializer().Serialize(content);

            HttpStatusCode result = 0;
            if (!SendGcmNotification(ApiKey, message, ref result))
            {
                Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.ErrorSendingNotification, result);
            }
        }
 void IJob.Execute(IJobContext context, Operation operation)
 {
     UTF8Encoding encoding = new UTF8Encoding(false);
     using (StreamWriter sw = new StreamWriter(_alarmTextFileName, false, encoding))
     {
         sw.WriteLine(operation.OperationNumber);
         sw.WriteLine(operation.Einsatzort.Location);
         sw.WriteLine(operation.OperationPlan);
         sw.WriteLine(operation.Comment);
         sw.WriteLine(operation.Einsatzort.Intersection);
         sw.WriteLine(operation.Picture);
         sw.WriteLine(operation.Messenger);
         sw.WriteLine(operation.Einsatzort.Property);
         sw.WriteLine(operation.Einsatzort.City);
         sw.WriteLine(operation.Einsatzort.Street);
         sw.WriteLine(operation.Resources.ToString("{FullName} | {RequestedEquipment}", null));
         sw.WriteLine(operation.Keywords.EmergencyKeyword);
         sw.WriteLine(operation.Keywords.Keyword);
     }
 }
示例#53
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Einsatznummer: {0}", operation.OperationNumber).AppendLine();
            sb.AppendFormat("Einsatzort: {0}", operation.GetDestinationLocation());

            // Send notification via each growl sender
            _growlSender.ForEach(gs =>
            {
                try
                {
                    gs.SendNotification(this, "Neuer Alarm!", sb.ToString());
                }
                catch (Exception ex)
                {
                    Logger.Instance.LogFormat(LogType.Warning, this, "Could not send Growl notification! See log for information.");
                    Logger.Instance.LogException(this, ex);
                }
            });
        }
示例#54
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase == JobPhase.OnOperationSurfaced)
            {
                if (operation.Einsatzort.HasGeoCoordinates)
                {
                    return;
                }

                GeocoderLocation geocoderLocation = _provider.Geocode(operation.Einsatzort);
                if (geocoderLocation != null)
                {
                    //The most of the widgets and so need the "english-format" (point instead of comma)!
                    operation.Einsatzort.GeoLongitude = geocoderLocation.Longitude;
                    operation.Einsatzort.GeoLatitude = geocoderLocation.Latitude;
                }
                else
                {
                    Logger.Instance.LogFormat(LogType.Warning, this, Properties.Resources.NoCoordinatesFoundByGeocodingService);
                }
            }
        }
示例#55
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            StringBuilder messageText = new StringBuilder();
            messageText.AppendFormat("Ort: {0}, ", operation.GetDestinationLocation());
            if (!string.IsNullOrWhiteSpace(operation.Picture))
            {
                messageText.AppendFormat("{0}; ", operation.Picture);
            }
            if (!string.IsNullOrWhiteSpace(operation.Comment))
            {
                messageText.AppendFormat("{0}", operation.Comment);
            }

            string format = SettingsManager.Instance.GetSetting("SMSJob", "MessageFormat").GetString();
            string text = operation.ToString(format);

            // Truncate the string if it is too long
            text = messageText.ToString().Truncate(160, true, true);

            // Invoke the provider-send asynchronous because it is a web request and may take a while
            _provider.Send(_userName, _password, _recipients.Select(r => r.PhoneNumber), text);
        }
示例#56
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            using (MySqlConnection conn = CreateConnection())
            {
                conn.Open();
                if (conn.State != System.Data.ConnectionState.Open)
                {
                    Logger.Instance.LogFormat(LogType.Error, this, "Could not open SQL Connection!");
                    return;
                }

                // TODO: This string contains CustomData. When actually using this job this should be revised to NOT use any custom data (or make it extensible)!

                StringBuilder queryText = new StringBuilder();
                queryText.AppendFormat("INSERT INTO {0} ", TableName);
                queryText.Append("(Einsatznr, Einsatzort, Einsatzplan, Hinweis, Kreuzung, Meldebild, Mitteiler, Objekt, Ort, Strasse, Fahrzeuge, Alarmtime, Faxtime, Einsatzstichwort, Stichwort) ");
                queryText.Append("VALUES (");
                queryText.AppendFormat("'{0}', ", operation.OperationNumber);
                queryText.AppendFormat("'{0}', ", operation.Einsatzort.Location);
                queryText.AppendFormat("'{0}', ", operation.OperationPlan);
                queryText.AppendFormat("'{0}', ", operation.Comment);
                queryText.AppendFormat("'{0}', ", operation.Einsatzort.Intersection);
                queryText.AppendFormat("'{0}', ", operation.Picture);
                queryText.AppendFormat("'{0}', ", operation.Messenger);
                queryText.AppendFormat("'{0}', ", operation.Einsatzort.Property);
                queryText.AppendFormat("'{0}', ", operation.Einsatzort.City);
                queryText.AppendFormat("'{0}', ", operation.Einsatzort.Street + " " + operation.Einsatzort.StreetNumber);
                queryText.AppendFormat("'{0}', ", operation.Resources.ToString("{FullName} {RequestedEquipment} | ", null));
                queryText.AppendFormat("'{0}', ", operation.GetCustomData<string>("Alarmtime"));
                queryText.AppendFormat("'{0}', ", operation.GetCustomData<string>("Faxtime"));
                queryText.AppendFormat("'{0}', ", operation.Keywords.EmergencyKeyword);
                queryText.AppendFormat("'{0}'", operation.Keywords.Keyword);
                queryText.Append(")");

                MySqlCommand cmd = new MySqlCommand(queryText.ToString(), conn);
                cmd.ExecuteNonQuery();
            }
        }
示例#57
0
 void IJob.Execute(IJobContext context, Operation operation)
 {
     // This is a Pre-Job. Thus it only has to run right after the operation has surfaced and before being stored.
     if (context.Phase == JobPhase.OnOperationSurfaced)
     {
         //Don't overwrite exisiting coordinates
         if (operation.Einsatzort.HasGeoCoordinates)
         {
             return;
         }
         GeocoderLocation geocoderLocation = _provider.GeoCode(operation.Einsatzort);
         if (geocoderLocation != null)
         {
             //The most of the widgets and so need the "english-format" (point instead of comma)!
             operation.Einsatzort.GeoLongitude = geocoderLocation.Longitude.ToString().Replace(',', '.');
             operation.Einsatzort.GeoLatitude = geocoderLocation.Latitude.ToString().Replace(',', '.');
         }
         else
         {
             Logger.Instance.LogFormat(LogType.Error, this, "No coordinats found by geocoding service.");
         }
     }
 }
示例#58
0
        void IJob.Execute(IJobContext context, Operation operation)
        {
            if (context.Phase != JobPhase.AfterOperationStored)
            {
                return;
            }

            IList<MobilePhoneEntryObject> recipients = GetRecipients(operation);
            if (recipients.Count == 0)
            {
                Logger.Instance.LogFormat(LogType.Info, this, Properties.Resources.NoRecipientsErrorMessage);
                return;
            }

            string format = _settings.GetSetting("SMSJob", "MessageFormat").GetValue<string>();
            string text = operation.ToString(format);
            text = text.Replace("Ö", "Oe").Replace("Ä", "Ae").Replace("Ü", "Ue").Replace("ö", "oe").Replace("ä", "ae").Replace("ü", "ue").Replace("ß", "ss");
            // Truncate the string if it is too long
            text = text.Truncate(160, true, true);

            // Invoke the provider-send asynchronous because it is a web request and may take a while
            _provider.Send(_userName, _password, recipients.Select(r => r.PhoneNumber), text);
        }
示例#59
0
文件: Exporter.cs 项目: peterzhao/aft
        private void ExportSyncObject(SyncObject syncObject, IJobContext jobContext)
        {
            try
            {
                if (_destination.Save(syncObject))
                {
                    _source.UpdateStatus(_queueName, syncObject.QueueId, QueueRepository.QueueStatusExported, DateTime.Now);
                    jobContext.CountSuccess();
                }
                else
                {
                    _source.UpdateStatus(_queueName, syncObject.QueueId, QueueRepository.QueueStatusSkipped, DateTime.Now);
                    jobContext.CountIdenticalObject();
                }
                _source.Dequeue(_queueName, syncObject.QueueId);

            }
            catch (SaveToSalsaException ex)
            {

                _errorHandler.HandleSyncObjectFailure(syncObject, this, ex);
                _source.UpdateStatus(_queueName, syncObject.QueueId, QueueRepository.QueueStatusError);
            }
        }
示例#60
0
        private void AttachImage(IJobContext context, MailMessage message)
        {
            if (context.Parameters.Keys.Contains("ImagePath"))
            {
                string imagePath = (string)context.Parameters["ImagePath"];
                if (!string.IsNullOrWhiteSpace(imagePath))
                {
                    if (File.Exists(imagePath))
                    {
                        string[] splitFiles = Helpers.ConvertTiffToJpegAndSplit(imagePath);
                        Stream stream = Helpers.CombineBitmap(splitFiles).ToStream(ImageFormat.Jpeg);

                        message.Attachments.Add(new Attachment(stream, ImageAttachmentFileName));

                        foreach (string s in splitFiles)
                        {
                            File.Delete(s);
                        }
                    }
                }
            }
        }