public static void DisConnect() { var tmpCts = Interlocked.Exchange(ref cts, null); if (tmpCts == null) { return; } CommitStartStop(false); tmpCts.Cancel(); var tmpDataS = Interlocked.Exchange(ref _dataStream, new Subject <(byte, ArraySegment <int>, ArraySegment <byte>)>()); tmpDataS?.OnCompleted(); var tmpStateS = Interlocked.Exchange(ref _stateStream, new Subject <BrainDevState>()); tmpStateS?.OnCompleted(); bufferManager.Clear(); var tmp = Interlocked.Exchange(ref socket, null); try { tmp?.Close(); } catch (Exception e) { Console.WriteLine(e); } AppLogger.Debug("BrainDeviceManager.DisConnect"); }
public void onLogon(SessionID value) { AppLogger.Debug(value.ToString()); Console.WriteLine(string.Format("@onLogon:{0}", value.ToString())); SessionID = value; StartPublishingExecutionReports(); }
public void onLogon(SessionID value) { AppLogger.Debug(value.ToString()); Console.WriteLine(string.Format("@onLogon:{0}", value.ToString())); new Thread(ProcesssNewOrderSingleThread).Start(null); SessionID = value; }
private void SessionUpdated(object session, Boolean toKillProcesses) { Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (DispatcherOperationCallback) delegate(object o) { try { AppLogger.Debug("SessionUpdated()", "Enter"); if (toKillProcesses) { ToKillProcesses(); } SessionHandler.UpdateBySessionMessage(session); if (IsActiveSession) { State = STATES.Session; } else if (State != STATES.NotSession) { State = STATES.FinishingSession; } AppLogger.Debug("SessionUpdated()", "Finish"); } catch (Exception ex) { AppLogger.Error("SessionUpdated()", "Error: " + ex.Message + ". State is " + State); } return(null); }, null); }
public static async Task <int> SendCompletelyAsync(this Socket socket, IList <ArraySegment <byte> > buffers, SocketFlags socketFlags, CancellationToken token, SyncBufManager bufMgr) { token.ThrowIfCancellationRequested(); var sent = 0; var count = 0; for (var i = 0; i < buffers.Count; i++) { count += buffers[i].Count; } var copy = bufMgr.TakeBuffer(count); try { count = 0; for (var i = 0; i < buffers.Count; i++) { ArraySegment <byte> arraySegment = buffers[i]; Buffer.BlockCopy(arraySegment.Array, arraySegment.Offset, copy, count, arraySegment.Count); count += arraySegment.Count; } var bytes = await socket.SendCompletelyAsync(copy, count, socketFlags, token); sent += bytes; AppLogger.Debug($"SendCompletelyAsync:{sent},{buffers.Show()}"); return(sent); } finally { bufMgr.ReturnBuffer(copy); } }
public void Process(ArraySegment <byte> data) { var count = data.Count; var buf = data.Array; const int leastLen = 1; if (buf == null || count < leastLen) { AppLogger.Error($"corruted SetFilter result,received len: {count}"); return; } count = (count - 1) / 2; var lst = new List <int>(count); var startIdx = data.Offset + 1; for (var i = 0; i < count; i++) { var index0 = i * 2 + startIdx; var flag0 = buf[index0]; var flag1 = buf[index0 + 1]; var code = BitDataConverter.ImpedanceCode(flag0, flag1); lst.Add(code); } CommitMultiImpedance(lst); AppLogger.Debug($"TestMultiImpedanceHandler: Data Processed"); }
public IHttpActionResult SubmitLog([FromBody] LoggingMessage logging) { switch (logging.LogType) { case 1: Devicelog.Info(null, logging.PrepareLogMessage()); break; case 2: Devicelog.Warn(null, logging.PrepareLogMessage()); break; case 3: Devicelog.Debug(null, logging.PrepareLogMessage()); break; case 4: Devicelog.Error(logging.ExceptionObj, logging.PrepareLogMessage()); break; default: Devicelog.Info(null, logging.PrepareLogMessage()); break; } return(Ok(new { Status = Constants.WebApiStatusOk, data = "Success" })); }
private void _WebSocket_OnOpen(object sender, EventArgs e) { AppLogger.Debug("WebSocket opened"); _lastReceivedTime = DateTime.UtcNow; OnConnectionOpen?.Invoke(); }
public void OnLogon(SessionID sessionID) { AppLogger.Debug(sessionID.ToString()); Console.WriteLine(string.Format("@onLogon:{0}", sessionID.ToString())); SessionID = sessionID; StartPublishingExecutionReports(); }
public void FileUpload(IEnumerable <HttpPostedFileBase> upload) { AppLogger.Debug("start import", null); if (upload != null) { AppLogger.Debug($"кол-во файлов: {upload.Count()}", null); string importDir = Server.MapPath(Settings.UserFiles + Settings.ImportDir); // чистим папку от предыдущих файлов DirectoryInfo di = new DirectoryInfo(importDir); if (di.Exists) { foreach (FileInfo file in di.GetFiles()) { file.Delete(); } } else { di.Create(); } // сохраняем файлы для импорта foreach (var file in upload) { if (file != null && file.ContentLength > 0) { string savePath = importDir + file.FileName; file.SaveAs(savePath); } } #region comments //FileInfo[] files = { di.GetFiles("*.xml") // .Where(w => w.FullName.ToLower() // .Contains("cat")) // .OrderByDescending(p => p.LastWriteTime) // .FirstOrDefault(), // di.GetFiles("*.xml") // .Where(w => w.FullName.ToLower() // .Contains("prod")) // .OrderByDescending(p => p.LastWriteTime) // .FirstOrDefault(), // di.GetFiles("*.zip") // .OrderByDescending(p => p.LastWriteTime) // .FirstOrDefault() }; #endregion FileInfo[] files = di.GetFiles("*.zip") .OrderByDescending(p => p.LastWriteTime) .Take(2) .ToArray(); Importer.DoImport(files); } }
public void fromApp(Message value, SessionID sessionId) { AppLogger.Debug(value.ToString()); Console.WriteLine(string.Format("@fromApp:{0}", value.ToString())); //if (value is QuickFix44.NewOrderSingle) //{ // ProcesssNewOrderSingleThread((QuickFix44.NewOrderSingle)value); //} }
private static async Task OnReceived(Socket socket, DisposableValue <ArraySegment <byte> > arrSeg, CancellationToken ctsToken) { var buffer = arrSeg.Value; var buf = buffer.Array; var count = buffer.Count; if (count > 0 && buf != null) { var funcId = (DevCommandFuncId)buf[buffer.Offset]; AppLogger.Debug($"func:{funcId},{buffer.Show()}"); switch (funcId) { case DevCommandFuncId.StartStop: HandlerStartStop(socket, buffer, ctsToken); return; case DevCommandFuncId.SetSampleRate: await SetSampleRate(socket, buffer, ctsToken); return; case DevCommandFuncId.SetTrap: await SetTrap(socket, buffer, ctsToken); return; case DevCommandFuncId.SetFilter: await SetFilter(socket, buffer, ctsToken); return; case DevCommandFuncId.QueryParam: await QueryParam(socket, buffer, ctsToken); return; case DevCommandFuncId.QueryFaultState: await QueryFaultState(socket, buffer, ctsToken); return; case DevCommandFuncId.TestSingleImpedance: await TestSingleImpedance(socket, buffer, ctsToken); return; case DevCommandFuncId.TestMultiImpedance: await TestMultiImpedance(socket, buffer, ctsToken); return; } } await SimpleSend(socket, buffer); }
private void _WebSocket_OnOpen(object sender, EventArgs e) { AppLogger.Debug("WebSocket opened"); _lastReceivedTime = DateTime.UtcNow; string authRequest = _wsV1ReqBuilder.Build(); _WebSocket.Send(authRequest); AppLogger.Debug("WebSocket authentication sent"); }
/// <summary> /// データ受信イベント /// </summary> /// <param name="message"></param> public void OnReceived(CommunicationObject message) { appLog.Debug("<FW> {0} Received {1}({2})", this.GetType().Name, message.mType, message.GetMessageName()); lock (RequestList) { RequestList.Remove(message.GetMessageName()); } Dispatcher.Invoke(new ReceivedDelegate(OnResponseEmpty), message); ViewBaseCommon.OnReceived(message, Dispatcher, this.functionList); }
private static async Task SimpleSend(Socket socket, ArraySegment <byte> buffer) { var buf = buffer.Array; var count = buffer.Count; var sent = 0; while (sent < count) { sent += await socket.SendAsync(buf, sent, count - sent, SocketFlags.None); } AppLogger.Debug($"SimpleSend:{sent},len:{buf.Length},{buf.Show()}"); }
private void CleanTimerScreen() { AppLogger.Debug("CleanTimerScreen()", "Date: " + DateTime.Now.ToString("mm:ss:ff")); try { _drawHandler.CleanScreen(); } catch (Exception ex) { AppLogger.Error("CleanTimerScreen()", ex.Message); } }
private Guid GetCurrentSiteId() { var _repository = new Repository("dbConnection"); var domainUrl = Request.Url.Host.ToLower().Replace("www.", ""); var siteId = _repository.GetSiteId(domainUrl); if (siteId == Guid.Empty) { AppLogger.Debug($"CoreController: Не получилось определить Domain для {domainUrl}"); } return(siteId); }
public void toAdmin(Message value, SessionID sessionId) { AppLogger.Debug(value.ToString()); if (value is QuickFix42.Logon) { //QuickFix42.Logon logon = (QuickFix42.Logon)value; //int msgSeq = Convert.ToInt32(logon.getHeader().getField(MsgSeqNum.FIELD)); //if(msgSeq==1)//Reset On StartTime //{ // logon.setChar(ResetSeqNumFlag.FIELD, ResetSeqNumFlag.YES); //} } Console.WriteLine(string.Format("@toAdmin:{0}", value.ToString())); }
public void Process(ArraySegment <byte> data) { var count = data.Count; var buf = data.Array; const int leastLen = 1 + 1; if (buf == null || count < leastLen) { AppLogger.Error($"corruted SetFilter result,received len: {count}"); return; } var startIdx = data.Offset; var flag = buf[startIdx + 1]; var success = flag == 0; AppLogger.Debug($"SetFilter success? {success}"); }
public void Process(ArraySegment <byte> data) { var count = data.Count; var buf = data.Array; const int leastLen = 1 + 2; if (buf == null || count < leastLen) { AppLogger.Error($"corruted SetFilter result,received len: {count}"); return; } var startIdx = data.Offset; var flag0 = buf[startIdx + 1]; var flag1 = buf[startIdx + 2]; var code = BitDataConverter.ImpedanceCode(flag0, flag1); SetSingleImpedance(code); AppLogger.Debug($"TestSingleImpedance: {flag0},{flag1}"); }
public static async Task <int> SendCompletelyAsync(this Socket socket, IList <ArraySegment <byte> > buffers, SocketFlags socketFlags, CancellationToken token) { token.ThrowIfCancellationRequested(); var sent = 0; for (var i = 0; i < buffers.Count; i++) { token.ThrowIfCancellationRequested(); var bytes = await socket.SendCompletelyAsync(buffers[i], socketFlags, token); if (bytes == 0) { break; } sent += bytes; } AppLogger.Debug($"SendCompletelyAsync:{sent},{buffers.Show()}"); return(sent); }
private void CmsRepository_DislyEvent(object sender, DislyEventArgs e) { switch (e.EventLevel) { case LogLevelEnum.Debug: AppLogger.Debug(e.Message, e.Exception); break; case LogLevelEnum.Error: AppLogger.Error(e.Message, e.Exception); break; case LogLevelEnum.Warn: AppLogger.Warn(e.Message, e.Exception); break; case LogLevelEnum.Info: AppLogger.Info(e.Message, e.Exception); break; } }
public static void WriteLine(string format, params object[] args) { switch (LogVersion.ToLower()) { case "console": Console.WriteLine(format, args); break; case "log": AppLogger.Debug(string.Format(format, args)); break; case "all": Console.WriteLine(format, args); AppLogger.Debug(string.Format(format, args)); break; default: break; } }
public IObservable <OperationResult> SendEmail(Person personData) { return(Observable.Create <OperationResult>( observer => { return Task.Run(async() => { try { using (var smtpClient = new SmtpClient(_smtpConfig.Host, _smtpConfig.Port) { EnableSsl = true, Credentials = new NetworkCredential(_smtpConfig.Username, _smtpConfig.Password) }) { var mail = await _emailGenerator.GenerateEmail(personData); var stopWatch = Stopwatch.StartNew(); await smtpClient.SendMailAsync(mail); observer.OnNext(new OperationResult.Success()); AppLogger.Debug( $"Id : {personData.Id} - Email has been sent to {personData.Email} in {stopWatch.Elapsed.TotalSeconds:0.000} seconds."); } } catch (Exception e) { observer.OnError(e); AppLogger.Error(e.Message); } observer.OnCompleted(); return Disposable.Empty; }); })); }
private void OnItemSelected(object sender, RoutedEventArgs e) { var item = sender as ListViewItem; if (item == null) { return; } AppLogger.Debug($"{item.Content},{item.TabIndex}"); var viewmodel = DataContext as EEGExampleViewModel; if (viewmodel == null) { return; } var aresult = viewmodel.TestSingleImpedance(item.TabIndex); aresult?.ContinueWith(ar => { item.IsSelected = false; if (!ar.IsFaulted) { var single = _currentState.LastSelectedSingleImpedanceChannel; if (1 <= single && single <= _currentState.ChannelCount) { var ritem = ImpedanceListBox.Items[single - 1] as ListBoxItem; if (ritem != null) { ritem.Content = $"Channel {single}: {_currentState.LastSingleImpedanceCode}"; } } ViewWinUtils.ShowDefaultDialog($"Test Single Channel Impedance #{single}: {_currentState.LastSingleImpedanceCode}"); } else { ViewWinUtils.ShowDefaultDialog(ar.Exception); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
/*// CLR unhandled exception * private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) * { * AppLogger.Error("OnUnhandledException()", "Exception: " + e.ExceptionObject); * return; * } * * // Windows Forms unhandled exception * private static void OnGuiUnhandedException(object sender, ThreadExceptionEventArgs e) * { * AppLogger.Error("OnGuiUnhandedException()", "Exception: " + e.Exception); * return; * }*/ #endregion #region Init methods private void InitializeLocker() { //AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException); try { this.Hide(); InitializeSHClient(); this.Lock(); this.InitializeTimers(); workingTimer.Start(); _taskbarNotifierHandler = new TaskbarNotifierHandler(_shClient._sessionHandler.ClientSession); RunInspector(); AppLogger.Debug("InitializeLocker()", "All components initialized successfully."); } catch (Exception ex) { this.isError = true; LockSystem(); this.ErrorInformer.Content = "ERROR: " + ex.Message; AppLogger.Error("InitializeLocker()", ex.Message); } }
public static void WriteLine(string format, ConsoleColor color = ConsoleColor.White, params object[] args) { Console.ForegroundColor = color; switch (LogVersion.ToLower()) { case "console": Console.WriteLine(format, args); break; case "log": AppLogger.Debug(string.Format(format, args)); break; case "all": Console.WriteLine(format, args); AppLogger.Debug(string.Format(format, args)); break; default: break; } Console.ForegroundColor = ConsoleColor.White; }
public IHttpActionResult Post(ModelEmployee model) { try { if (ModelState.IsValid) { if (_unitOfWork.Employees.GetById(model.Id) != null) { AppLogger.Debug("New employee unsuccessfull. From: Employees using Web API"); ModelState.AddModelError("ID", "Id is in use"); } else { //<Destination>(Source) var emp = _mapper.Map <Employee>(model); _unitOfWork.Employees.Add(emp); if (_unitOfWork.Complete() > 0) { var newModel = _mapper.Map <ModelEmployee>(emp); //CreatedAtRoute("GetEmployee", new { moniker = newModel.Id }, newModel); AppLogger.Info("New employee successfull. From: Employees using Web API"); return(Ok(newModel)); } ; } } } catch (Exception ex) { AppLogger.Error("New employee error. From: Employees using Web API"); return(InternalServerError(ex)); } AppLogger.Debug("New employee unsuccessfull. From: Employees using Web API"); return(BadRequest(ModelState)); }
private async Task StartDevice() { BrainDeviceManager.Init(); var sender = await BrainDeviceManager.Connnect("127.0.0.1", 9211); _currentState = default(BrainDevState); //保证设备参数正常才继续跑逻辑 BrainDeviceManager.BrainDeviceState.Subscribe(ss => { _currentState = ss; 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"); }); int totalReceived = 0; BrainDeviceManager.SampleDataStream.Subscribe(tuple => { var(order, datas, arr) = tuple; var copyArr = datas.CopyToArray(); if (copyArr != null) { _viewStream.OnNext(copyArr); } //Console.Write($" {order} "); totalReceived++; //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; } 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); var fs = new FileResource(_currentState, 19801983, 1, BrainDeviceManager.BufMgr); fs.StartRecord(BrainDeviceManager.SampleDataStream); cmdResult = await sender.Start(); if (cmdResult != CommandError.Success) { AppLogger.Error("Failed to start sampler"); } else { AppLogger.Debug($"start receive sample data"); await Task.Delay(1000 *60); AppLogger.Debug($"stoping"); await sender.Stop(); AppLogger.Debug($"stop receive sample data"); await Task.Delay(1000); } BrainDeviceManager.DisConnect(); fs.Dispose(); }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { cmsRepository.DislyEvent += CmsRepository_DislyEvent; base.OnActionExecuting(filterContext); ControllerName = filterContext.RouteData.Values["Controller"].ToString().ToLower(); ActionName = filterContext.RouteData.Values["Action"].ToString().ToLower(); Guid _PageId; try { Domain = _cmsRepository.getSiteId(Request.Url.Host.ToLower().Replace("www.", "")); } catch (Exception ex) { if (Request.Url.Host.ToLower().Replace("www.", "") != ConfigurationManager.AppSettings["BaseURL"]) { filterContext.Result = Redirect("/Error/"); } else { Domain = String.Empty; } AppLogger.Debug("CoreController: Не получилось определить Domain", ex); } ViewBag.Domain = Domain; StartUrl = "/Admin/" + (String)RouteData.Values["controller"] + "/"; #region Настройки сайта //SettingsInfo = _cmsRepository.getCmsSettings(); // Сайт, на котором находимся //if (Domain != String.Empty) SettingsInfo.ThisSite = _cmsRepository.getSite(Domain); #endregion #region Данные об авторизованном пользователе Guid _userId = new Guid(); try { _userId = new Guid(System.Web.HttpContext.Current.User.Identity.Name); } catch { FormsAuthentication.SignOut(); } AccountInfo = _accountRepository.getCmsAccount(_userId); // Список доменов, доступных пользователю AccountInfo.Domains = _accountRepository.getUserDomains(_userId); #endregion #region Права пользователя UserResolutionInfo = _accountRepository.getCmsUserResolutioInfo(_userId, ControllerName); // Если нет прав на проссмотр, то направляем на главную try { if (!UserResolutionInfo.Read) { filterContext.Result = Redirect("/Admin/"); } } catch { } #endregion #region Ограничение пользователя (не администратора портала и не разработчика) на доступ только к своим сайтам (доменам) int IsRedirect = 0; SiteInfo = _cmsRepository.getSite(); // информация по сайту if (AccountInfo.Group.ToLower() != "developer" && AccountInfo.Group.ToLower() != "administrator") { if (AccountInfo.Domains != null) { foreach (DomainList domain in AccountInfo.Domains) { if (domain.SiteId == Domain) { IsRedirect++; } } } //перенаправляем на первый из своих доменов if (IsRedirect == 0) { string url = "http://" + AccountInfo.Domains[0].DomainName + "/Admin/"; Response.Redirect(url, true); } } #endregion #region Логи try { _PageId = Guid.Parse(filterContext.RouteData.Values["id"].ToString()); LogInfo = _cmsRepository.getCmsPageLog(_PageId); } catch { } #endregion }