private void m_tsbSave_Click(object sender, EventArgs e) { AppLogger.logInfo(this.Name, "handle tsbSave"); this.HandleSaveTask(); }
private void m_tsbEdit_Click(object sender, EventArgs e) { AppLogger.logInfo(this.Name, "handle tsbEdit"); this.HandleEdit(); }
//Implementation IDataErrorInfo methods for validation public string this[string columnName] { get { string error = String.Empty; if (columnName == "id" || columnName == validationName) { if (!ValidationRules.IsName(id)) { error = "Cluster node ID should contain only letters, numbers and _"; AppLogger.Add("ERROR! " + error); } } if (columnName == "address" || columnName == validationName) { if (!ValidationRules.IsIp(address)) { error = "Cluster node address should be IP address"; AppLogger.Add("ERROR! " + error); } } if (columnName == "winX" || columnName == validationName) { if (isWindowed == true) { if (!ValidationRules.IsInt(winX.ToString())) { error = "x should be an integer"; AppLogger.Add("ERROR! " + error); } } } if (columnName == "winY" || columnName == validationName) { if (isWindowed == true) { if (!ValidationRules.IsInt(winY.ToString())) { error = "y should be an integer"; AppLogger.Add("ERROR! " + error); } } } if (columnName == "resX" || columnName == validationName) { if (isWindowed == true) { if (!ValidationRules.IsInt(resX.ToString()) || Convert.ToInt32(resX) < 0) { error = "Width should be an integer"; AppLogger.Add("ERROR! " + error); } } } if (columnName == "resY" || columnName == validationName) { if (isWindowed == true) { if (!ValidationRules.IsInt(resY.ToString()) || Convert.ToInt32(resY) < 0) { error = "Height should be an integer"; AppLogger.Add("ERROR! " + error); } } } MainWindow.ConfigModifyIndicator(); return(error); } }
protected virtual void LogAuditTrail(T entity, string action) { if (CurrentUser != null) { action = action.ToUpperInvariant(); if (_auditTrailRepository == null) { _auditTrailRepository = new GenericRepository <AuditTrail>(Repository.Context); } if (_auditTrailDetailRepository == null) { _auditTrailDetailRepository = new GenericRepository <AuditTrailDetail>(Repository.Context); } try { // Logs audit trail AuditTrail auditTrail = new AuditTrail(); auditTrail.id = Guid.NewGuid().ToString(); auditTrail.object_id = entity.GetType().GetProperty("id").GetValue(entity, null).ToString(); auditTrail.object_type = entity.GetType().ToString(); auditTrail.action = action; auditTrail.date_time = DateTime.Now; auditTrail.user_id = CurrentUser.id; _auditTrailRepository.Insert(auditTrail); switch (entity.EntityState) { case EntityState.Added: { foreach (var property in entity.GetType().GetProperties()) { AuditTrailDetail auditTrailDetail = new AuditTrailDetail(); auditTrailDetail.id = Guid.NewGuid().ToString(); auditTrailDetail.parent_id = auditTrail.id; auditTrailDetail.property_name = property.Name; auditTrailDetail.old_value = string.Empty; auditTrailDetail.new_value = property.GetValue(entity, null) != null?property.GetValue(entity, null).ToString() : null; _auditTrailDetailRepository.Insert(auditTrailDetail); } } break; case EntityState.Modified: { var stateEntry = Repository.Context.ObjectStateManager.GetObjectStateEntry(entity); foreach (var propertyName in stateEntry.GetModifiedProperties()) { AuditTrailDetail auditTrailDetail = new AuditTrailDetail(); auditTrailDetail.id = Guid.NewGuid().ToString(); auditTrailDetail.parent_id = auditTrail.id; auditTrailDetail.property_name = propertyName; auditTrailDetail.old_value = stateEntry.OriginalValues[propertyName] != null ? stateEntry.OriginalValues[propertyName].ToString() : null; auditTrailDetail.new_value = stateEntry.CurrentValues[propertyName] != null ? stateEntry.CurrentValues[propertyName].ToString() : null; _auditTrailDetailRepository.Insert(auditTrailDetail); } } break; default: break; } } catch (Exception ex) { AppLogger.logError(this.ToString(), ex); throw; } } }
protected void Btn_Save(object sender, EventArgs e) { try { double NilMax = 0; double NilMin = 0; var SumRowData = GridviewToolVerification.VisibleRowCount; ScriptManager.RegisterClientScriptBlock(this, GetType(), "alertMessage", @"alert('Verification Success !');", true); for (int i = 0; i < SumRowData; i++) { //var rowIndex = e.VisibleIndex; var varGetData = GridviewToolVerification.FindDetailRowTemplateControl(i, "LayoutDetails") as ASPxFormLayout; if (varGetData != null) { var ValSetNm = GridviewToolVerification.GetRowValues(i, "SetNM"); var convertIntValSetNM = ValSetNm == null ? "" : ValSetNm.ToString(); if (float.Parse(convertIntValSetNM.Split(',')[0]) < 10) { var Persentase = float.Parse(convertIntValSetNM.Split('.')[0]) * 0.02; NilMax = float.Parse(convertIntValSetNM.Split('.')[0]) + Persentase; NilMin = float.Parse(convertIntValSetNM.Split('.')[0]) - Persentase; HiddenMax.Value = NilMax.ToString(); HiddenMin.Value = NilMin.ToString(); } else { var Persentase = float.Parse(convertIntValSetNM.Split('.')[0]) * 0.03; NilMax = float.Parse(convertIntValSetNM.Split('.')[0]) + Persentase; NilMin = float.Parse(convertIntValSetNM.Split('.')[0]) - Persentase; HiddenMax.Value = NilMax.ToString(); HiddenMin.Value = NilMin.ToString(); } var GetSetNm = varGetData.FindControl("Text_NM") as ASPxTextBox; var GetSetMin = varGetData.FindControl("Text_Min") as ASPxTextBox; var GetSetMax = varGetData.FindControl("Text_Max") as ASPxTextBox; GetSetNm.Text = ValSetNm.ToString(); GetSetMax.Text = NilMax.ToString(); GetSetMin.Text = NilMin.ToString(); var ValueId = GridviewToolVerification.GetRowValues(i, "ToolId"); var ValueInventory = GridviewToolVerification.GetRowValues(i, "Id"); var NextDayGet = GridviewToolVerification.GetRowValues(i, "VerDay"); DateTime today = DateTime.Now; var ValueToolSetupId = GridviewToolVerification.GetRowValues(i, "Id"); var ValueNextVerificationDate = GridviewToolVerification.GetRowValues(i, "Id"); //var iList = ToolVerificationRepository.RetrieveDataToolVerification("ToolVerification_GetData", ValueId.ToString(), ValueInventory.ToString()); var Attempt = varGetData.FindControl("lbl_Attempt") as ASPxTextBox; var ValAttempt = Attempt.Text == "ASPxLabel" ? 1 : int.Parse(Attempt.Text) + 1; var InvString = ValueInventory.ToString(); if (ValAttempt > 3) { ValAttempt = 3; } for (int u = 0; u < ValAttempt; u++) { var VerifNumb = u + 1; var GetVerDate = varGetData.FindControl("lblVerificationDate") as ASPxLabel; var GetToolSetupId = varGetData.FindControl("lblInventoryNumber") as ASPxLabel; var GetText_Min = varGetData.FindControl("Text_Min") as ASPxTextBox; var GetText_Max = varGetData.FindControl("Text_Max") as ASPxTextBox; var GetVerification1 = varGetData.FindControl("text_ver" + VerifNumb + "_" + "1") as ASPxTextBox; var GetVerification2 = varGetData.FindControl("text_ver" + VerifNumb + "_" + "2") as ASPxTextBox; var GetVerification3 = varGetData.FindControl("text_ver" + VerifNumb + "_" + "3") as ASPxTextBox; //var ValText_VerDate = iList[0].LastVerificationDate.ToString(); var ValCalNumber = "1"; var ValTollSetupId = ValueToolSetupId.ToString(); var ValTollInv = ValueInventory.ToString(); var ValText_NM = ValSetNm.ToString(); var ValText_Min = GetText_Min.Text; var ValText_Max = GetText_Max.Text; var ValText_Verification1 = GetVerification1.Text; var ValText_Verification2 = GetVerification2.Text; var ValText_Verification3 = GetVerification3.Text; var VerifNumberString = VerifNumb.ToString(); DateTime ValueNext = today.AddDays(int.Parse(NextDayGet.ToString() == "" ? "0" : NextDayGet.ToString())); User user = (User)Session["user"]; var CreatedBy = user.UserName; ToolVerificationRepository.SaveDataToolVerification(ValueNext, VerifNumberString, InvString, ValCalNumber, ValueId.ToString(), ValTollInv, ValText_NM, ValText_Min, ValText_Max, ValText_Verification1, ValText_Verification2, ValText_Verification3, ValTollInv, CreatedBy); } } } Response.Write(@" <script> alert('Save Success'); setTimeout(function(){ window.location = '" + Request.RawUrl + @"'; }, 2000); </script>"); //Response.Redirect(Request.RawUrl); } catch (Exception ex) { AppLogger.LogError(ex); } }
public SmscanDirector() { AppLogger.ConfigApp(); watcher = new SmscanWatcher(Global.SMsourceFolder); }
private void SubscribeChatLog() { Thread.Sleep(TimeSpan.FromSeconds(DetectProcessInterval)); AppLogger.Write("FFXIV chat log subscriber started."); var previousPlayerName = string.Empty; while (true) { var interval = TimeSpan.FromMilliseconds(Config.Instance.ChatLogPollingInterval); var isExistLogs = false; try { // スレッドプライオリティを更新する if (Thread.CurrentThread.Priority != Config.Instance.ChatLogSubscriberThreadPriority) { Thread.CurrentThread.Priority = Config.Instance.ChatLogSubscriberThreadPriority; } if (!this.IsAttached || !Reader.CanGetChatLog()) { interval = TimeSpan.FromSeconds(DetectProcessInterval); continue; } var targetLogs = default(IEnumerable <ChatLogItem>); try { if (this.isWorking) { continue; } this.isWorking = true; if (this.currentPlayer != null && !string.IsNullOrEmpty(this.currentPlayer.Name)) { if (!string.IsNullOrEmpty(previousPlayerName) && !string.Equals( previousPlayerName, this.currentPlayer.Name, StringComparison.OrdinalIgnoreCase)) { this.previousArrayIndex = 0; this.previousOffset = 0; } previousPlayerName = this.CurrentPlayer.Name; } var result = Reader.GetChatLog(this.previousArrayIndex, this.previousOffset); if (result == null) { continue; } this.previousArrayIndex = result.PreviousArrayIndex; this.previousOffset = result.PreviousOffset; if (!result.ChatLogItems.Any()) { continue; } targetLogs = result.ChatLogItems .Where(x => ChatCodes.All.Contains(x.Code)); isExistLogs = targetLogs.Any(); } finally { this.isWorking = false; } if (isExistLogs) { var models = targetLogs .Select(x => ChatLogModel.FromXIVLog(x, this.currentPlayerNames)) .ToArray(); WPFHelper.Dispatcher.Invoke(() => { ChatLogsModel.AddToBuffers(models); }); foreach (var model in models) { if (model.IsMe) { var playerName = this.currentPlayer?.Name; if (string.IsNullOrEmpty(playerName)) { playerName = previousPlayerName; if (string.IsNullOrEmpty(playerName)) { playerName = Config.Instance.ActiveProfile?.CharacterName; } } DiscordBotController.Instance.SendMessage( model.ChatCode, playerName, Config.Instance.ActiveProfile?.Alias, model.Message); } var chName = !string.IsNullOrEmpty(model.ChannelShortName) ? model.ChannelShortName : model.ChannelName; ChatLogger.Write( chName, model.Speaker, model.SpeakerAlias, model.Message); } } } catch (ThreadAbortException) { return; } catch (Exception ex) { AppLogger.Error("Happened exception from chat log subscriber.", ex); interval = TimeSpan.FromSeconds(DetectProcessInterval * 2); } finally { var now = DateTime.Now; if (isExistLogs) { this.lastChatLogReceivedTimestamp = now; Thread.Yield(); } else { if ((now - this.lastChatLogReceivedTimestamp) > ChatIdelThreshold) { interval = ChatIdleInterval; } Thread.Sleep(interval); } } } }
private void microwaveReceiver_ReceiverConnectionChange(object sender, EventArgs e) { //TODO determine any further action AppLogger.Message("MicrowaveControlService : recevier connected: " + microwaveReceiver.Connected); }
/// <summary> /// Search past and open orders based on searching criteria. /// </summary> /// <param name="request">request</param> public void Request(RequestOrdersRequest request) { _WebSocket.Send(request.ToJson()); AppLogger.Info($"WebSocket requested, topic={request.topic}, accountId={request.AccountId} symbol={request.symbol}"); }
public static void Init(IServiceProvider sp, SettingsModel settingsModel) { AppLogger = sp.GetRequiredService <IAppLogger>(); LogsSnapshotRepository = sp.GetRequiredService <LogsSnapshotRepository>(); var items = LogsSnapshotRepository.LoadAsync().AsTask().Result; ((AppLogger)AppLogger).Init(items); var queuesTimeSpan = TimeSpan.Parse(settingsModel.FlushQueuesSnapshotFreq); _taskTimerSyncQueues = new TaskTimer(queuesTimeSpan); var messagesTimeSpan = TimeSpan.Parse(settingsModel.FlushMessagesFreq); _taskTimerSyncMessages = new TaskTimer(messagesTimeSpan); AppGlobalFlags = sp.GetRequiredService <AppGlobalFlags>(); AppGlobalFlags.LoadBlobPagesSize = settingsModel.LoadBlobPagesSize; _serviceProvider = sp; QueueSnapshotCache = sp.GetRequiredService <QueueSnapshotCache>(); MessagesContentCache = sp.GetRequiredService <MessagesContentCache>(); MessagesContentReader = sp.GetRequiredService <MessagesContentReader>(); MetricsByTopic = sp.GetRequiredService <MetricsByTopic>(); _activePagesWarmerAndGc = sp.GetRequiredService <ActivePagesWarmerAndGc>(); TaskSchedulerByTopic = sp.GetRequiredService <TaskSchedulerByTopic>(); _queueSnapshotWriter = sp.GetRequiredService <QueueSnapshotWriter>(); CompressPageBlobOperation = sp.GetRequiredService <CompressPageBlobOperation>(); CompressedMessagesStorage = sp.GetRequiredService <ICompressedMessagesStorage>(); CompressedMessagesUtils = sp.GetRequiredService <CompressedMessagesUtils>(); LegacyCompressedMessagesStorage = sp.GetRequiredService <ILegacyCompressedMessagesStorage>(); MessagesContentPersistentStorage = sp.GetRequiredService <IMessagesContentPersistentStorage>(); ((MessagesPersistentStorage)MessagesContentPersistentStorage).Inject(sp); LastCompressedPageStorage = sp.GetRequiredService <ILastCompressedPageStorage>(); IndexByMinuteWriter = sp.GetRequiredService <IndexByMinuteWriter>(); SyncAndGcBlobOperations = sp.GetRequiredService <SyncAndGcBlobOperations>(); Task.Run(() => InitTopicsAsync(sp)); _taskTimerSyncQueues.Register("SyncQueuesSnapshotToStorage", _queueSnapshotWriter.ExecuteAsync); _taskTimerSyncQueues.Register("ActiveMessagesWarmerAndGc", _activePagesWarmerAndGc.CheckAndWarmItUpOrGcAsync); _taskTimerSyncQueues.Register("IndexByMinuteWriter", IndexByMinuteWriter.SaveMessagesToStorage); _taskTimerSyncQueues.Register("FlushLastCompressedPagesState", LastCompressedPageStorage.FlushAsync); _taskTimerSyncQueues.Register("Update prometheus", () => { MetricsCollector.UpdatePrometheus(); return(new ValueTask()); }); _taskTimerSyncQueues.RegisterExceptionHandler((timer, e) => { AppLogger.AddLog(LogProcess.System, timer, e.Message, e.StackTrace); return(new ValueTask()); }); _taskTimerSyncMessages.Register("PersistentOperationsScheduler", SyncAndGcBlobOperations.Sync); _taskTimerSyncMessages.RegisterExceptionHandler((timer, e) => { AppLogger.AddLog(LogProcess.System, timer, e.Message, e.StackTrace); return(new ValueTask()); }); }
public static bool ProcessSyncData(string packingMonth, int modelId) { using (AppDb context = new AppDb()) { DateTime dtPackingMonth = Convert.ToDateTime(packingMonth); Model oModel = context.Models.FirstOrDefault(p => p.Id == modelId); string asyncConnString = context.Database.Connection.ConnectionString; using (SqlConnection conn = new SqlConnection(asyncConnString)) { if (conn.State == ConnectionState.Closed) { conn.Open(); } SqlCommand cmd = new SqlCommand(); cmd.CommandText = "EXEC usp_GetCGISStagingData @vpm, @model"; cmd.CommandTimeout = 7000; cmd.Parameters.AddWithValue("@vpm", dtPackingMonth.ToString("yyyyMM")); cmd.Parameters.AddWithValue("@model", oModel.ModelName); cmd.Connection = conn; try { cmd.ExecuteNonQuery(); } catch (SqlException se) { AppLogger.LogError(se); return(false); } cmd = new SqlCommand(); cmd.CommandText = "EXEC usp_ProcessCGISFromStaging @vpm, @model"; cmd.CommandTimeout = 7000; cmd.Parameters.AddWithValue("@vpm", dtPackingMonth.ToString("yyyyMM")); cmd.Parameters.AddWithValue("@model", oModel.ModelName); cmd.Connection = conn; try { cmd.ExecuteNonQuery(); } catch (SqlException se) { AppLogger.LogError(se); return(false); } CGISSynchronized csync = new CGISSynchronized(); csync.PackingMonth = dtPackingMonth.ToString("yyyyMM"); csync.ProcessDate = DateTime.Now; csync.TypeId = oModel.TypeId.GetValueOrDefault(); csync.ModelId = modelId; csync.ProcessBy = "Admin"; //TODO:Change to current apps logger context.CGISSynchronizeds.Add(csync); context.SaveChanges(); } } return(true); }
public StringBuilder InsertUpdateProduct(bool isUpdating) { StringBuilder errorMessage = new StringBuilder(); try { AppLogger.logInfo("InsertUpdateProduct"); errorMessage.Append(checkInputData(isUpdating)); if (errorMessage.Length != 0) { return(errorMessage); } if (_model.SelectedManufacturer != null) { _model.Product.ManufacturerId = _model.SelectedManufacturer.Id; } if (_model.SelectedUnit != null) { _model.Product.UnitId = _model.SelectedUnit.Id; } if (_model.SelectedCategory != null) { _model.Product.CategoryId = _model.SelectedCategory.Id; } else { _model.Product.CategoryId = 1; } _model.Product.ChangedBy = SystemParam.CurrentUser.Id; if (isUpdating) { _business.Update(_model.Product); } else { ProductPrice price = new ProductPrice(); price.ProductId = _model.Product.Id; price.Cost = CurrencyUtil.ToDecimal(_model.Cost); price.Price = CurrencyUtil.ToDecimal(_model.Price); price.IsCurrentPrice = true; _model.Product.Price = price.Price; _model.Product.ProductPrices = new List <ProductPrice>() { price }; _business.Insert(_model.Product); } } catch (Exception exc) { AppLogger.logError(exc); errorMessage.AppendLine(exc.Message); } return(errorMessage); }
public AliMailSender(IOptions <AliMailOptions> options, AppLogger logger, IDistributedCache cache) { _logger = logger; _cache = cache; _options = options.Value; }
private bool FindOrCreateParserObject(int lineNumber, string line, XElement filter, List <object> parsedList, out string objectClass, out string thisValue, out string objectState) { thisValue = null; objectClass = null; objectState = null; var objState = State.Unknown; var objClass = ObjectClass.Unknown; ParserObject obj = null; bool isExistingFound = false; _lastCurrentObject = _currentObj; //_currentObj = null; foreach (var prop in filter.XPathSelectElements("Properties/Property")) { var name = prop.Element("Name"); if (name != null && prop.Element("Name") != null && prop.Element("Name").Value.ToLower() == "this") { if (prop.Element("PatternIndex") == null || prop.Attribute("i") == null) { AppLogger.LogLine(string.Format("Invalid profile definition: missing index {0} of property '{1}'", "'i=' or 'PatternIndex'", "this"), lineNumber); continue; } if (int.TryParse(prop.Element("PatternIndex").Value, out int patternIndex)) { if (patternIndex < _sf.Results.Count) { thisValue = (string)parsedList[patternIndex]; var thisVal = thisValue; objectState = filter.Element("State") != null && !string.IsNullOrWhiteSpace(filter.Element("State").Value) ? filter.Element("State").Value : null; if (!string.IsNullOrWhiteSpace(objectState)) { objState = Enum.IsDefined(typeof(State), objectState) ? objectState.ToEnum <State>() : State.Unknown; } objectClass = filter.Element("ObjectClass") != null && !string.IsNullOrWhiteSpace(filter.Element("ObjectClass").Value) ? filter.Element("ObjectClass").Value : null; if (!string.IsNullOrWhiteSpace(objectClass)) { objClass = Enum.IsDefined(typeof(ObjectClass), objectClass) ? objectClass.ToEnum <ObjectClass>() : ObjectClass.Unknown; } var filterKey = filter.Attribute("key").Value; } } } } if (Enum.IsDefined(typeof(ObjectClass), objClass) && !string.IsNullOrWhiteSpace(thisValue)) { var thisVal = thisValue; var foundInterruptedLastState = State.Unknown; ParserObject foundInterruptedObj = null; var foundExistingObjects = ObjectCollection.Where(x => x.GetThis() == thisVal && x.ObjectClass == objClass && objClass != ObjectClass.Device && //TODO ????????? x.IsFindable == true); isExistingFound = foundExistingObjects != null && foundExistingObjects.Count() > 0; if (isExistingFound) { var isCompletedFound = foundExistingObjects.Any(x => x.StateCollection.Any(y => y.State == State.Completed)); if (isCompletedFound) { //Set isFindable = true foreach (var o in foundExistingObjects) { o.IsFindable = false; } isExistingFound = false; } else { foundInterruptedObj = foundExistingObjects.LastOrDefault(); if (foundInterruptedObj != null) { var foundStateCollection = foundInterruptedObj.StateCollection; if (foundStateCollection != null && foundStateCollection.Count > 0) { //foundInterruptedLastState = foundStateCollection[foundStateCollection.Count - 1].State; var foundStateObj = foundStateCollection.LastOrDefault(x => x.State >= 0); if (foundStateObj != null) { foundInterruptedLastState = foundStateObj.State; if (ObjectCollection[ObjectCollection.Count - 1].GetThis() != thisVal || objState < foundInterruptedLastState) { isExistingFound = false; } } } } } } if (!isExistingFound) { if (foundInterruptedObj != null) { obj = foundInterruptedObj.CreateObjectClone(); obj.BaseColor = foundInterruptedObj.BaseColor; foundInterruptedObj.NextContinuedObj = obj; obj.PrevInterruptedObj = foundInterruptedObj; for (int i = 0; i < foundInterruptedObj.StateCollection.Count; i++) { obj.StateCollection.Add(obj.CreateBlankStateObject()); } } else { var filterKey = filter.Attribute("key").Value; bool isVisible = true; if (filter.Attribute("IsVisible") != null) { isVisible = filter.Attribute("IsVisible").Value.ToBoolean(); } obj = new ParserObject(); obj.ObjectClass = objClass; obj.SetDynProperty("this", thisValue); obj.SetDynProperty("FilterKey", filterKey); obj.SetDynProperty("IsVisible", isVisible); obj.LineNum = lineNumber; obj.LogEntry = line; obj.FilterKey = filterKey; } } else { obj = foundExistingObjects.LastOrDefault(); isExistingFound = true; } _currentObj = obj; if (_currentObj == null) { _currentObj = _lastCurrentObject; isExistingFound = true; } } return(isExistingFound); }
private void SubscribeFFXIVProcess() { var language = "Japanese"; Thread.Sleep(TimeSpan.FromSeconds(DetectProcessInterval)); AppLogger.Write("FFXIV process subscriber started."); while (true) { Thread.Sleep(TimeSpan.FromSeconds(DetectProcessInterval)); try { if (this.isWorking) { continue; } this.isWorking = true; var processes = Process.GetProcessesByName("ffxiv_dx11"); if (processes.Length < 1) { if (this.IsAttached) { this.handledProcessID = 0; } this.ClearActiveProfile(); continue; } var ffxiv = processes[0]; if (!MemoryHandler.Instance.IsAttached || this.handledProcessID != ffxiv.Id) { MemoryHandler.Instance.SetProcess( new ProcessModel { Process = ffxiv, IsWin64 = true }, language); this.handledProcessID = ffxiv.Id; this.previousArrayIndex = 0; this.previousOffset = 0; this.currentPlayer = null; AppLogger.Write("Attached to FFXIV."); } this.RefreshActiveProfile(); } catch (ThreadAbortException) { return; } catch (Exception ex) { AppLogger.Error("Happened exception from FFXIV process subscriber.", ex); Thread.Sleep(TimeSpan.FromSeconds(DetectProcessInterval * 2)); } finally { this.isWorking = false; } } }
private async Task <DevCommandSender> ConnectDevAsync() { try { BrainDeviceManager.Init(); //TODO config IP and port var sender = await BrainDeviceManager.Connnect("127.0.0.1", 9211); //TODO config vRef (default = 4.5f) //保证设备参数正常才继续跑逻辑 BrainDeviceManager.BrainDeviceState.Subscribe(ss => { _currentState = ss; ChannelCount = _currentState.ChannelCount; _uithread.InvokeAsync(CreateChannelParts); var pmax = 4.5f * 2 / _currentState.Gain; //YVisibleRange = new DoubleRange(-pmax, pmax); AppLogger.Debug($"Brain Device State Changed Detected: {ss}"); }, () => { AppLogger.Debug("device stop detected"); }); BrainDeviceManager.SampleDataStream.Subscribe(tuple => { var(order, datas, arr) = tuple; var copyArr = datas.CopyToArray(); if (copyArr != null) { _viewStream.OnNext(copyArr); } //Console.Write($" {order} "); //AppLogger.Debug($"order:{order}"); //AppLogger.Debug($"converted values:{datas.Show()}"); //AppLogger.Debug($"original datas:{arr.Show()}"); }, () => { AppLogger.Debug("device sampling stream closed detected"); }); var cmdResult = await sender.QueryParam(); AppLogger.Debug("QueryParam result:" + cmdResult); if (cmdResult != CommandError.Success) { AppLogger.Error("Failed to QueryParam, stop"); BrainDeviceManager.DisConnect(); return(null); } return(sender); } catch (Exception) { return(null); } /* * cmdResult = await sender.SetFilter(false); * AppLogger.Debug("SetFilter result:"+cmdResult); * * cmdResult = await sender.SetTrap(TrapSettingEnum.NoTrap); * AppLogger.Debug("SetTrap result:"+cmdResult); * * cmdResult = await sender.SetSampleRate(SampleRateEnum.SPS_2k); * AppLogger.Debug("SetSampleRate result:"+cmdResult); * * cmdResult = await sender.QueryParam(); * AppLogger.Debug("QueryParam result:"+cmdResult); */ }
private void InitializeBot() { Thread.Sleep(TimeSpan.FromSeconds(5)); AppLogger.Write("DISCORD Bot initializer started."); while (true) { Thread.Sleep(TimeSpan.FromSeconds(DetectBotInterval)); try { var activeProfile = Config.Instance.ActiveProfile; if (activeProfile == null) { this.ClearBots(); Thread.Sleep(TimeSpan.FromSeconds(5)); continue; } var task = Task.Run(async() => { var activeBotSettings = activeProfile.ChannelLinkerList .Where(x => x.IsEnabled && !string.IsNullOrEmpty(x.DiscordChannelID)) .Select(x => this.GetBotByChannelID(x.DiscordChannelID)) .ToArray(); // 新しいBOTを生成する var newBots = activeBotSettings .Where(x => x != null && !this.Bots.ContainsKey(x?.Name)) .ToArray(); foreach (var config in newBots) { var bot = new DiscordSocketClient(); this.Bots.AddOrUpdate( config.Name, (_) => bot, (_, old) => old = bot); bot.Log += this.Bot_Log; bot.MessageReceived += this.Bot_MessageReceived; await bot.LoginAsync(TokenType.Bot, config.Token); await bot.StartAsync(); } // 不要になったBOTを始末する var keys = this.Bots .Where(x => !activeBotSettings.Any(y => y.Name == x.Key)) .Select(x => x.Key) .ToArray(); this.ClearBots(keys); }); task.Wait(); } catch (ThreadAbortException) { return; } catch (Exception ex) { AppLogger.Error("Happened exception from DISCORD Bot initializer.", ex); Thread.Sleep(TimeSpan.FromSeconds(10)); } } }
public void Log(object entity, string Remark = "") { AppLogger.Log(entity, ActionName, ControlName, Remark); }
public async void Start( double pollingInteval, Locales ffxivLocale = Locales.JA) { lock (this) { if (this.isStarted) { return; } this.isStarted = true; } this.FFXIVLocale = ffxivLocale; this.attachFFXIVPluginWorker = new System.Timers.Timer(); this.attachFFXIVPluginWorker.AutoReset = true; this.attachFFXIVPluginWorker.Interval = 5000; this.attachFFXIVPluginWorker.Elapsed += (s, e) => { try { this.Attach(); lock (ResourcesLock) { this.LoadSkillList(); this.LoadZoneList(); this.MergeSkillList(); this.MergeBuffList(); } } catch (Exception ex) { AppLogger.Error(ex, "Attach FFXIV_ACT_Plugin error"); } }; this.scanFFXIVWorker = new ThreadWorker(() => { this.RefreshActive(); if (!this.IsAvailable) { Thread.Sleep(5000); #if !DEBUG return; #endif } this.RefreshCombatantList(); this.RefreshCurrentPartyIDList(); }, pollingInteval, nameof(this.attachFFXIVPluginWorker)); await Task.Run(() => { Thread.Sleep(CommonHelper.GetRandomTimeSpan()); this.attachFFXIVPluginWorker.Start(); Thread.Sleep(CommonHelper.GetRandomTimeSpan()); this.scanFFXIVWorker.Run(); // XIVDBをロードする Thread.Sleep(CommonHelper.GetRandomTimeSpan()); XIVDB.Instance.FFXIVLocale = ffxivLocale; XIVDB.Instance.Load(); // PC名記録をロードする Thread.Sleep(CommonHelper.GetRandomTimeSpan()); PCNameDictionary.Instance.Load(); // PTリストの並び順をロードする Thread.Sleep(CommonHelper.GetRandomTimeSpan()); PCOrder.Instance.Load(); }); }
public static DataViewModel GetData(DataViewModel model) { DataViewModel md = new DataViewModel(); md.currencyFilter = new CurrencyFilter(); md.dateFilter = new DateFilter(); md.statusFilter = new StatusFilter(); md.resultFormat = new ResultFormat(); md.currencyFilter.Currencies = new List <Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>(); md.currencyFilter.Currencies.Add(new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem() { Text = "--Select--", Value = "--Select--" }); md.statusFilter.StatusList = new List <Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>(); md.statusFilter.StatusList.Add(new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem() { Text = "--Select--", Value = "--Select--" }); md.resultFormat.ResultList = new List <Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>(); md.outputModel = new List <OutputModel>(); try { using (_Connection = GetSQLConnection()) { if (_Connection.State == System.Data.ConnectionState.Closed) { _Connection.Open(); } SqlCommand cmd = new SqlCommand(); cmd.Connection = _Connection; cmd.CommandText = "USP_GetTransactionData"; cmd.CommandType = System.Data.CommandType.StoredProcedure; if (model != null) { cmd.Parameters.AddWithValue("@Currency", model.currencyFilter.Currency); cmd.Parameters.AddWithValue("@Status", model.statusFilter.Status.Trim()); if (!string.IsNullOrEmpty(model.dateFilter.StartDate)) { cmd.Parameters.AddWithValue("@Start_Date", model.dateFilter.StartDate); } if (!string.IsNullOrEmpty(model.dateFilter.EndDate)) { cmd.Parameters.AddWithValue("@End_Date", model.dateFilter.EndDate); } } cmd.Parameters.AddWithValue("@Operation", "All"); var reader = cmd.ExecuteReader(); while (reader.Read()) { string Currency = Convert.ToString(reader["Currency"]); md.currencyFilter.Currencies.Add(new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem() { Text = Currency, Value = Currency }); } if (reader.NextResult()) { while (reader.Read()) { string Status = Convert.ToString(reader["Status"]); md.statusFilter.StatusList.Add(new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem() { Text = Status, Value = Status }); } } if (reader.NextResult()) { while (reader.Read()) { string Stat = Convert.ToString(reader["Status"]); string TrnsId = Convert.ToString(reader["ID"]); string Pay = Convert.ToString(reader["Payment"]); md.outputModel.Add(new OutputModel() { Id = TrnsId, Payment = Pay, Status = Stat }); } } } } catch (Exception ex) { AppLogger.Log(ex); } return(md); }
public Combatant GetBossInfo( double bossHPThreshold) { if (!this.IsAvailable) { return(null); } var party = this.GetPartyList(); var combatants = this.GetCombatantList(); if (party == null || combatants == null || party.Count < 1 || combatants.Count < 1) { return(null); } // パーティのHP平均値を算出する var players = party.Where(x => x.type == ObjectType.PC); if (!players.Any()) { return(null); } var avg = players.Average(x => x.MaxHP); // BOSSを検出する var boss = ( from x in combatants where x.MaxHP >= (avg * bossHPThreshold) && x.type == ObjectType.Monster && x.CurrentHP > 0 orderby x.Level descending, (x.MaxHP != x.CurrentHP ? 0 : 1)ascending, x.MaxHP descending, x.ID descending select x).FirstOrDefault(); if (boss != null) { boss.Player = combatants.FirstOrDefault(); } this.SetSkillName(boss); #region Logger if (boss != null) { if (this.previousBoss == null || this.previousBoss.ID != boss.ID) { var ratio = avg != 0 ? boss.MaxHP / avg : boss.MaxHP; var player = combatants.FirstOrDefault(); var message = $"BOSS " + $"name={boss.Name}, " + $"maxhp={boss.MaxHP}, " + $"ptavg={avg.ToString("F0")}, " + $"ratio={ratio.ToString("F1")}, " + $"BOSS_pos={boss.PosX},{boss.PosY},{boss.PosZ}, " + $"player_pos={player.PosX},{player.PosY},{player.PosZ}"; AppLogger.Info(message); } } this.previousBoss = boss; #endregion Logger return(boss); }
public RssService(IUnitOfWork db, ILogger <RssService> logger) { _db = db; _logger = new AppLogger(logger); }
private static async Task <bool> IsUpdateAsync( ReleaseChannels updateChannel, bool isForce = false) { SetupSSL(); // アップデートChannelを保存する LastCheckedUpdateChannel = updateChannel; if (string.IsNullOrEmpty(UpdateSourceUri)) { return(false); } var now = DateTimeOffset.Now; var targetAssembly = Assembly.GetEntryAssembly(); try { // リリースノートを取得する var notes = await ReleaseNotes.DeserializeAsync(new Uri(UpdateSourceUri)); if (notes == null) { AppLogger.Error($"Update checker error. RELEASE_NOTES.xml not found. uri={UpdateSourceUri}"); return(false); } // より新しいバージョンがあるか? var newer = notes.GetNewerVersion( targetAssembly, updateChannel, isForce); if (newer == null) { AppLogger.Write("Update checker. this version is up-to-date."); return(false); } AppLogger.Write($"Update checker found newer version. v{newer.Version}-{newer.ReleaseChannel}"); // アップデートWindowを表示する await Application.Current.Dispatcher.InvokeAsync(() => { UpdateCheckerView.Show( notes.Name, targetAssembly, newer); }); } catch (Exception ex) { AppLogger.Fatal("Update checker fatal error.", ex); throw; } finally { LastUpdateCheckCallback?.Invoke(now); AppLogger.Flush(); } return(true); }
/// <summary> /// 启动午盘休盘价下载。 /// </summary> public int Start() { try { m_eventLogger = AppLogger.InitInstance(); } catch { m_eventLogger = new NullLogger("DownloadProcessor_DefaultLogger"); } m_eventLogger.LineFeed(); string text = "开始下载午盘收盘价服务"; m_eventLogger.WriteInformation(text); USeConsole.WriteLine(text); if (ReadConfig() == false) { return(-1); } CtpOrderQuerier ctpApp = new CtpOrderQuerier(); try { ctpApp.Connect(m_ctpDriverConfig.Address, m_ctpDriverConfig.Port, m_ctpDriverConfig.LoginTimeOut, m_ctpDriverConfig.QueryTimeOut); text = "连接CTP交易服务器成功"; USeConsole.WriteLine(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "连接CTP交易服务器失败," + ex.Message; USeConsole.WriteLine(text); m_eventLogger.WriteError(text); ctpApp.Disconnect(); return(-1); } try { ctpApp.Login(m_ctpAccountConfig.ID, m_ctpAccountConfig.Password, m_ctpAccountConfig.BrokerID); text = "登陆CTP交易服务器成功"; USeConsole.WriteLine(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "登陆CTP交易服务器失败," + ex.Message; USeConsole.WriteLine(text); m_eventLogger.WriteError(text); ctpApp.Disconnect(); return(-1); } try { List <InstrumentField> instrumentList = ctpApp.QueryInstument(); foreach (InstrumentField item in instrumentList) { if (item.ProductClass != ProductClass.Futures) { continue; } USeInstrumentDetail entity = InsturmentFiledToUSeInstrumentDetail(item); instrumentDic.Add(entity.Instrument.InstrumentCode, entity); } text = string.Format("查询期货合约数据完成,共计{0}个合约", instrumentDic.Count); USeConsole.WriteLine(text); m_eventLogger.WriteInformation(text); } catch (Exception ex) { text = "查询期货合约数据失败," + ex.Message; USeConsole.WriteLine(text); m_eventLogger.WriteError(text); ctpApp.Disconnect(); return(-1); } List <DepthMarketDataField> depthMarketDataFieldList = new List <DepthMarketDataField>(); depthMarketDataFieldList = ctpApp.QueryDepthMarketData(); //while (true) //{ // depthMarketDataFieldList = ctpApp.QueryDepthMarketData(); // //返回大于下午开盘的行情时间 // if (VerfiyIsNoonBeginTime(depthMarketDataFieldList) == true) // { // text = string.Format("[{0}]行情已经进入下午开盘时间不在午盘时间内", DateTime.Now); // USeConsole.WriteLine(text); // m_eventLogger.WriteError(text); // ctpApp.Disconnect(); // return -1; // } // //未找到大于11:30:00。 // if (VerfiyIsNoonEndTime(depthMarketDataFieldList) == false) // { // Thread.Sleep(m_queryFrequence); // continue; // } // else // { // break; // } //} ctpApp.Disconnect(); try { foreach (DepthMarketDataField marketData in depthMarketDataFieldList) { if (instrumentDic.ContainsKey(marketData.InstrumentID)) { USeMarket market = instrumentDic[marketData.InstrumentID].Instrument.Market; //保存收盘价 SaveClosePriceToDB(marketData, marketData.InstrumentID, market, DateTime.Today, marketData.LastPrice); instrumentDic.Remove(marketData.InstrumentID); USeConsole.WriteLine(string.Format("保存{0}成功", marketData.InstrumentID)); } } RefrashPriceCloseDownLoad(DateTime.Today, 1); } catch (Exception ex) { text = string.Format("查询,保存当日午盘数据异常:{0}", ex.Message); USeConsole.WriteLine(text); m_eventLogger.WriteInformation(text); return(-1); } return(0); }
public RssService(IUnitOfWork db, ILogger <RssService> logger) { this.db = db; this.logger = new AppLogger(logger); }
private void m_tsbAddNew_Click(object sender, EventArgs e) { AppLogger.logInfo(this.Name, "handle tsbAddNew"); this.HandleCreateNew(); }
public LoggerCommand_UnitTest() { _logger = new AppLogger("log.txt"); _store = new FileStore("test_data", typeof(Xmlformat), typeof(AppData)); }
private void m_tsbCancelTask_Click(object sender, EventArgs e) { AppLogger.logInfo(this.Name, "handle tsbCancel"); this.HandleCancelTask(); }
protected void grid_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e) { try { ASPxGridView grv = (sender as ASPxGridView); if (e.VisibleIndex > -1) { if (e.DataColumn.FieldName == "ReceivedByMarketing") { DataRowView row = grv.GetRow(e.VisibleIndex) as DataRowView; string bpk = row["BPK"].ToString(); string send = row["SendToMarketing"].ToString(); ASPxButton btnRCV = grv.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "btnRCV") as ASPxButton; ASPxLabel lblRCV = grv.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "lblRCV") as ASPxLabel; string caption = e.CellValue.ToString();// Convert.ToString(e.CellValue); if (caption == string.Empty && !string.IsNullOrEmpty(bpk) && !string.IsNullOrEmpty(send)) { btnRCV.Visible = true; lblRCV.Visible = false; } else { lblRCV.Text = caption; btnRCV.Visible = false; lblRCV.Visible = true; } } if (e.DataColumn.FieldName == "PrintNik") { ASPxButton btnPrintNik = grv.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "btnPrintNIK") as ASPxButton; ASPxLabel lblPrintNik = grv.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "lblPrintNIK") as ASPxLabel; string caption = e.CellValue.ToString();// Convert.ToString(e.CellValue); if (caption != string.Empty) { lblPrintNik.Text = caption; btnPrintNik.Visible = false; lblPrintNik.Visible = true; } else { btnPrintNik.Visible = false; lblPrintNik.Visible = false; } } if (e.DataColumn.FieldName == "BPK") { ASPxButton btnBPK = grv.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "btnBPK") as ASPxButton; ASPxLabel lblBPK = grv.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "lblBPK") as ASPxLabel; string caption = e.CellValue.ToString();// Convert.ToString(e.CellValue); if (caption != string.Empty) { lblBPK.Text = caption; btnBPK.Visible = false; lblBPK.Visible = true; } else { btnBPK.Visible = false; lblBPK.Visible = false; } } if (e.DataColumn.FieldName == "SendToMarketing") { ASPxButton btnSend = grv.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "btnSend") as ASPxButton; ASPxLabel lblSend = grv.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "lblSend") as ASPxLabel; string caption = e.CellValue.ToString();// Convert.ToString(e.CellValue); if (caption != string.Empty) { lblSend.Text = caption; btnSend.Visible = false; lblSend.Visible = true; } else { btnSend.Visible = false; lblSend.Visible = false; } } } } catch (Exception ex) { AppLogger.LogError(ex); } }
public static void Main(string[] args) { string filePath = null; if (args.Length == 0) { throw new ArgumentException("Should be called with a Json PlayDrone file to import."); } filePath = args[0]; var log = new Logger(); var appConverter = new FileReader(log); var apps = appConverter.FileToModel(filePath); var count = apps.Count(); // Setup connection var connectionString = ConfigurationManager.ConnectionStrings["MarketDbConnectionString"]; using (var connection = new SqlConnection(connectionString.ConnectionString)) { // Initialise app store with logger and connection var appSqlStore = new AppStore(connection); var appStore = new AppLogger(appSqlStore, appSqlStore, log); var categorySqlStore = new CategoryStore(); var categoryCacheStore = new CategoryCache(categorySqlStore, categorySqlStore); var categoryStore = new CategoryLogger(categoryCacheStore, categoryCacheStore, log); // Assuming apps are added in order to save multiple queries to the database. var existingAppCount = appStore.Count(); // Loop through apps. App store will save every 100,000 apps var appsToSave = new List<Models.App>(); var appCounter = 0; for (int i = existingAppCount; i < count; i++) { // Get the app from the list. var app = apps[i]; // Store the app category if it doesn't exist. if (!categoryStore.Exists(app.category)) { var category = new Models.Category { Id = Guid.NewGuid(), Name = app.category }; categoryStore.Save(category); } // Lookup app category id. var categoryId = categoryStore.GetId(app.category); app.id = Guid.NewGuid(); app.categoryId = categoryId; appsToSave.Add(app); log.LogOperation(string.Format("App {0}/{1} added: {2}", i + 1, count, app.app_id)); appCounter++; // Save apps if(appCounter >= 100000) { appStore.SaveMany(appsToSave); appsToSave.Clear(); appCounter = 0; } } // Save the remainder appStore.SaveMany(appsToSave); log.LogOperation("DONE!!!!"); } }
public static void InitializeVJoyDevice(uint vJoyID, HID_USAGES axis) { lock (vJoyLocker) { if (vJoyInitialized[vJoyID - 1]) { return; } vJoyInitialized[vJoyID - 1] = true; AppLogger.LogToGui("Initializing VJoy virtual joystick driver via vJoyInterface.dll interface", false); try { VJoy currVJoy; if (vJoyObj[vJoyID - 1] == null) { vJoyObj[vJoyID - 1] = new VJoy(); } currVJoy = vJoyObj[vJoyID - 1]; if (currVJoy.vJoyEnabled() && currVJoy.GetVJDAxisExist(vJoyID, axis)) { AppLogger.LogToGui("Connection to VJoy virtual joystick established", false); AppLogger.LogToGui($"VJoy driver. Vendor={currVJoy.GetvJoyManufacturerString()} Product={currVJoy.GetvJoyProductString()} Version={currVJoy.GetvJoySerialNumberString()} Device#={vJoyID} Axis={axis}", false); // Test if DLL matches the driver UInt32 DllVer = 0, DrvVer = 0; if (!currVJoy.DriverMatch(ref DllVer, ref DrvVer)) { AppLogger.LogToGui("WARNING. VJoy version of Driver {DrvVer}) does not match interface DLL Version {DllVer}. This may lead to unexpected problems or crashes. Update VJoy driver and vJoyInterface.dll", false); } VjdStat status = currVJoy.GetVJDStatus(vJoyID); if ((status == VjdStat.VJD_STAT_OWN) || ((status == VjdStat.VJD_STAT_FREE) && (!currVJoy.AcquireVJD(vJoyID)))) { vJoyAvailable[vJoyID - 1] = false; AppLogger.LogToGui("ERROR. Failed to acquire vJoy device# {vJoyID}. Use another VJoy device or make sure there are no other VJoy feeder apps using the same device", false); } else { //vJoyObj.GetVJDAxisMax(vJoyID, axis, ref vJoyAxisMaxValue); //AppLogger.LogToGui($"VJoy axis {axis} max value={vJoyAxisMaxValue}", false); currVJoy.ResetVJD(vJoyID); vJoyAvailable[vJoyID - 1] = true; } } else { vJoyAvailable[vJoyID - 1] = false; AppLogger.LogToGui($"ERROR. VJoy device# {vJoyID} or {axis} axis not available. Check vJoy driver installation and configuration", false); } } catch { vJoyAvailable[vJoyID - 1] = false; AppLogger.LogToGui("ERROR. vJoy initialization failed. Make sure that DS4Windows application can find vJoyInterface.dll library file", false); } } }