public void MouseDown(MouseEventArgs e) { (e.Source as UIElement).Focus(); if (SliceLineVisible) { var editor_grid = GetImageEditorGrid(e.Source as UIElement); if (editor_grid != null) { var position = e.GetPosition(editor_grid); position.X /= Scale; position.Y /= Scale; try { SliceSelectedImage(position); } catch (Exception ex) { NLogger.Warn("Slice image failed.ex:{0}", ex.ToString()); } this.CancleEdit(); } e.Handled = true; } else if (this.CropToolsVisible) { e.Handled = true; } }
public SplashWindow() { InitializeComponent(); if (NetEnvironmentCheck.IsValid()) { _splashTimer = new DispatcherTimer(); _splashTimer.Interval = TimeSpan.FromMilliseconds(400); _splashTimer.Tick += new EventHandler(splashTimer_Tick); _splashTimer.Start(); _mainWindow = new MainIntegrationWindow(); } else { // var warningContent = @"Before running protoNow, you have to install KB2468871 on your machine. //The download page will be opened automatically after you clicking ok button."; MessageBox.Show(GlobalData.FindResource("Warn_FramePath_Info"), GlobalData.FindResource("Common_Title")); try { System.Diagnostics.Process.Start("http://www.microsoft.com/en-us/download/details.aspx?id=3556"); } catch (Exception exp) { NLogger.Warn("Open URL error : " + exp.Message); } Application.Current.Shutdown(); } }
public void TestWarnPass() { var message = TestContext.TestName; logger.Warn(new Exception(), $"{message}", null); Assert.AreEqual($"Warn|{message}", target.LastMessage); }
public void AddToLibrary(ICustomLibrary customLibrary) { try { string objectName = CommonDefine.Untitled; ISerializeWriter writer = GetSerializeWriter(ref objectName); if (writer == null) { return; } IDocumentService DocService = ServiceLocator.Current.GetInstance <IDocumentService>(); ILibrary library = DocService.LibraryManager.GetLibrary(customLibrary.LibraryGID, customLibrary.FileName); if (library != null) { ICustomObject newObject = library.AddCustomObject(writer, objectName, CreateIconImage(false), null); if (newObject != null) { customLibrary.AddCustomObject(newObject.Guid); } } else { // If we cannot get the specific library, there is something wrong about this custom library. // Refresh this custom library customLibrary.Refresh(); } } catch (Exception ex) { NLogger.Warn("Add to library failed. ex:{0}", ex.ToString()); MessageBox.Show(GlobalData.FindResource("Error_Create_Library") + ex.Message); } }
private bool IsEnableMenuOpen() { if (_oldSelectedList != null) { if (_oldSelectedList.Count < 1) { return(false); } } else { NLogger.Warn("IsEnableMenuOpen->_oldSelectedList = null");//test code for find out reason return(false); } foreach (Guid ID in _oldSelectedList) { WidgetListItem item = FindUIItemByGUID(ID); if (item != null) { if (item.ItemType == ListItemType.GroupItem || item.ItemType == ListItemType.DynamicPanelStateItem) { return(false); } } else { NLogger.Warn("IsEnableMenuOpen->Founded item = null");//test code for find out reason return(false); } } return(true); }
public void CloseWithoutSave() { if (!_isEnable) { return; } NLogger.Info("User closed a document without saving before."); this.LoadRecoveryFiles(); IDocumentService doc = ServiceLocator.Current.GetInstance <IDocumentService>(); if (!GlobalData.IsKeepLastAutoSaved && doc.Document != null) { NLogger.Info("IsKeepLastAutoSaved is false.Try to remove last recovery file.Guid is {0}", doc.Document.Guid); var existFile = RecoveryInfo.RecoveryFiles.FirstOrDefault(x => x.Guid == doc.Document.Guid); if (existFile != null) { NLogger.Info("Last recovery file is exist, remove it from settings."); RecoveryInfo.RecoveryFiles.Remove(existFile); try { File.Delete(existFile.GetFullPath()); NLogger.Info("Remove last recovery file successfully."); } catch (Exception ex) { NLogger.Warn("Remove last recovery file failed.{0}", ex.ToString()); } SaveRecoveryFiles(); } } }
public void CloseFile(IDocumentService doc) { if (!_isEnable) { return; } NLogger.Info("Closing file."); this.LoadRecoveryFiles(); if (doc != null && doc.Document != null && !doc.Document.IsDirty) { NLogger.Info("The current document isn't dirty.It has been saved before.Try to remove relevant recovery file."); var existFile = RecoveryInfo.RecoveryFiles.FirstOrDefault(x => x.Guid == doc.Document.Guid); if (existFile != null) { NLogger.Info("Relevant recovery file is exist."); RecoveryInfo.RecoveryFiles.Remove(existFile); try { File.Delete(existFile.GetFullPath()); NLogger.Info("Remove Relevant recovery file successfully."); } catch (Exception ex) { NLogger.Warn("Remove Relevant recovery file failed.ex:{0}", ex.ToString()); } SaveRecoveryFiles(); } } }
public void Log <TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter) { var msg = formatter?.Invoke(state, exception) ?? exception?.Message; if (!string.IsNullOrEmpty(msg)) { msg = $"{eventId.Name} {msg}"; switch (logLevel) { case Microsoft.Extensions.Logging.LogLevel.Trace: if (_logger.IsTraceEnable) { _logger.Trace(msg); } break; case Microsoft.Extensions.Logging.LogLevel.Debug: if (_logger.IsDebugEnable) { _logger.Debug(msg); } break; case Microsoft.Extensions.Logging.LogLevel.Information: if (_logger.IsDebugEnable) { _logger.Debug(msg); } break; case Microsoft.Extensions.Logging.LogLevel.Warning: if (_logger.IsWarnEnable) { _logger.Warn(msg, exception); } break; case Microsoft.Extensions.Logging.LogLevel.Error: if (_logger.IsErrorEnable) { _logger.Error(msg, error: exception); } break; case Microsoft.Extensions.Logging.LogLevel.Critical: if (_logger.IsErrorEnable) { _logger.Error(msg, error: exception); } break; case Microsoft.Extensions.Logging.LogLevel.None: break; default: throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); } } }
public void ExportToLibrary() { try { SaveFileDialog saveFile = new SaveFileDialog(); saveFile.Filter = CommonDefine.LibraryFilter; saveFile.FileName = CommonDefine.Untitled; if (saveFile.ShowDialog() == true) { string objectName = CommonDefine.Untitled; ISerializeWriter writer = GetSerializeWriter(ref objectName); if (writer == null) { return; } //Create a new Library. Thumbnail is empty now, and waiting for a improvement IDocumentService DocService = ServiceLocator.Current.GetInstance <IDocumentService>(); ILibrary newLibrary = DocService.LibraryManager.CreateLibrary(writer, objectName, CreateIconImage(false), null); if (newLibrary != null) { newLibrary.SaveCopyTo(saveFile.FileName); DocService.LibraryManager.DeleteLibrary(newLibrary.Guid); } } } catch (Exception ex) { NLogger.Warn("Export to Library failed. ex:{0}", ex.ToString()); MessageBox.Show(GlobalData.FindResource("Error_Create_Library") + ex.Message); } }
private void ImportToLibrary(string fileName, string safeFileName, int insertIndex = 1) { var doc = ServiceLocator.Current.GetInstance <IDocumentService>(); try { var libraryGuid = doc.LibraryManager.PeekLibraryGuidFromFile(fileName); if (libraryGuid != default(Guid)) { if (this.WidgetExpands.Any(x => x.LibraryGID == libraryGuid)) { var winDuplicate = new DuplicateLibraryWindow(); winDuplicate.Owner = Application.Current.MainWindow; winDuplicate.ShowDialog(); if (!winDuplicate.Result.HasValue) { return; } else if (winDuplicate.Result.Value) { ///update var matchItem = this.WidgetExpands.Where(x => x.LibraryGID == libraryGuid).FirstOrDefault(); if (matchItem != null) { var removeIndex = this.WidgetExpands.IndexOf(matchItem); this.WidgetExpands.Remove(matchItem); doc.LibraryManager.DeleteLibrary(libraryGuid); ImportToLibrary(fileName, safeFileName, removeIndex); } } else { ///as new var copyNewPath = System.IO.Path.Combine( System.Environment.GetEnvironmentVariable("TMP"), string.Format("{0}.libpn", Environment.TickCount)); doc.LibraryManager.CreateNewLibraryFile(fileName, copyNewPath); ImportToLibrary(copyNewPath, safeFileName); } } else { var path = System.IO.Path.Combine( this.CreateLibraryFolder(libraryGuid), safeFileName); File.Copy(fileName, path, true); var loadLibrary = doc.LibraryManager.LoadLibrary(path); InsertLibrary(loadLibrary, insertIndex); } } } catch (Exception ex) { NLogger.Warn("Failed to import library {0},ex:{1}", fileName, ex.ToString()); MessageBox.Show(ex.ToString()); } }
public void CreateCustomLibrary(Guid libraryId, string libraryName) { if (string.IsNullOrEmpty(libraryName)) { throw new ArgumentException("libraryName cannot be empty"); } var doc = ServiceLocator.Current.GetInstance <IDocumentService>(); try { var iloadLibrary = doc.LibraryManager.GetLibrary(libraryId); if (iloadLibrary != null && !this.WidgetExpands.Any(e => e.LibraryGID == libraryId)) { var path = System.IO.Path.Combine( this.CreateLibraryFolder(libraryId), string.Format("{0}.libpn", libraryName)); iloadLibrary.Save(path); var expand = new WidgetExpand { LibraryGID = iloadLibrary.Guid, Header = iloadLibrary.Title, FileName = iloadLibrary.Name, IsCustomWidget = true, IsExpand = true, ExpandCache = true }; foreach (var customObject in iloadLibrary.CustomObjects) { var bytes = default(byte[]); if (customObject.Icon != null) { bytes = new byte[customObject.Icon.Length]; customObject.Icon.Read(bytes, 0, bytes.Length); } var widgetModel = new WidgetModel { Id = customObject.Guid, Name = customObject.Name, Icon = bytes != null?Convert.ToBase64String(bytes) : null, LbrType = "custom" }; expand.WidgetModels.Insert(0, widgetModel); } this.WidgetExpands.Insert(1, expand); var _ListEventAggregator = ServiceLocator.Current.GetInstance <IEventAggregator>(); _ListEventAggregator.GetEvent <CustomWidgetChangedEvent>().Publish(expand); } } catch (Exception ex) { NLogger.Warn("Failed to create custom library. ex:{0}", ex.ToString()); MessageBox.Show(ex.ToString()); } }
public void WarnTest() { ILogger nLogger = Substitute.For <ILogger>(); NLogger logger = new NLogger(nLogger); logger.Warn("message", new object[] { }); nLogger.Received().Warn("message", Arg.Any <object[]>()); }
public void CropCutCommandHandler(object obj) { try { this.CropAndCutSelectedImg(); } catch (Exception ex) { NLogger.Warn("Crop and cut Image failed. ex:{0}", ex.ToString()); } this.CancleEdit(); }
public void CropCopyCommandHandler(object obj) { try { this.CopySelectedArea(); } catch (Exception ex) { NLogger.Warn("Copy image failed. ex:{0}", ex.ToString()); } this.CancleEdit(); }
public void Warn(string format, params object[] args) { Logger.Warn(format, args); if (this.options.Verbose) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("WARN: "); Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine(format, args); Console.ResetColor(); } }
private void RichTextBlock_Loaded(object sender, RoutedEventArgs e) { try { if (DataContext is WidgetViewModelDate) { ((WidgetViewModelDate)DataContext).viewInput = (UIElement)sender; } } catch (System.Exception ex) { NLogger.Warn("Init IInputelment error!\n" + ex.Message); } }
private static void Main() { var logger = new NLogger(nameof(Program)); //var serverCertificate = X509Certificate.CreateFromCertFile(@"TempCert.cer"); using (var httpServer = new HttpServer(new HttpRequestProvider(), logger)) { var httpPort = 8088; var ipAddr = LocalMachineIpAddress ?? IPAddress.Loopback; httpServer.Use(new TcpListenerAdapter(new TcpListener(ipAddr, httpPort))); //httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(new TcpListener(IPAddress.Loopback, 443)), serverCertificate)); httpServer.Use(new ExceptionHandler()); httpServer.Use(new SessionHandler <SimpleSession>(() => new SimpleSession(), int.MaxValue, logger)); httpServer.Use(new ControllerHandler(new DerivedController(), new ModelBinder(new ObjectActivator()), new JsonView())); httpServer.Use(new CompressionHandler(DeflateCompressor.Default, GZipCompressor.Default)); httpServer.Use(new ControllerHandler(new BaseController(), new JsonModelBinder(), new JsonView())); httpServer.Use(new HttpRouter().With(string.Empty, new IndexHandler()) .With("about", new AboutHandler()) .With("Assets", new AboutHandler()) .With("strings", new RestHandler <string>(new StringsRestController(), JsonResponseProvider.Default))); httpServer.Use(new ClassRouter(new MySuperHandler())); httpServer.Use(new TimingHandler(logger)); httpServer.Use(new MyHandler()); httpServer.Use(new FileHandler()); httpServer.Use(new ErrorHandler()); httpServer.Use((context, next) => { Console.WriteLine("Got Request!"); return(next()); }); httpServer.Start(); logger.Info($"Started server : http://{ipAddr}:{httpPort}"); logger.Info($"Press any key to stop"); Console.ReadLine(); logger.Warn($"Stopping server..."); } }
private void SaveRecoveryFiles() { try { SyncNamed.WaitOne(); using (var rdr = new StreamWriter(RecoveryFileXmlPath)) { var serializer = new XmlSerializer(typeof(RecoveryInfo)); serializer.Serialize(rdr, RecoveryInfo); NLogger.Info("Save RecoveryInfo successfully."); } SyncNamed.ReleaseMutex(); } catch (Exception ex) { NLogger.Warn("Save RecoveryInfo failed.{0}", ex.ToString()); } }
private void OnBulletStyleChange(object obj) { BeginChange(); try { TextMarkerStyle style = (TextMarkerStyle)obj; if (Selection != null) { if (Selection.Text.Length == 0) { if (CaretPosition != null && CaretPosition.Paragraph != null) { Paragraph para = CaretPosition.Paragraph; ProcessParagraph(style, para); CaretPosition = para.ContentEnd; } } else if (Selection.Text.Length > 0) { TextPointer pStart = Selection.Start; TextPointer pEnd = Selection.End; Paragraph para = pStart.Paragraph; while (para != null && para.ContentStart.CompareTo(pEnd) < 0) { ProcessParagraph(style, para); para = para.NextBlock as Paragraph; } } } } catch (System.Exception ex) { NLogger.Warn("RichEditControl OnBulletStyleChange error," + ex.Message.ToString()); } EndChange(); }
/// 创建session public async Task <SessionIce> CreateSession(string ip, int port) { //设置locator var locator = LocatorPrxHelper.uncheckedCast(Communicator.stringToProxy("FootStone/Locator:default -h " + ip + " -p " + port)); Communicator.setDefaultLocator(locator); //获取session factory var tmpconid = Guid.NewGuid().ToString("N"); var sessionFactoryPrx = ISessionFactoryPrxHelper .uncheckedCast(Communicator.stringToProxy("sessionFactory") .ice_locatorCacheTimeout(0) .ice_connectionId(tmpconid) .ice_timeout(15000)); //建立网络连接,设置心跳为30秒 Connection connection = await sessionFactoryPrx.ice_getConnectionAsync(); connection.setACM(30, ACMClose.CloseOff, ACMHeartbeat.HeartbeatAlways); NLogger.Debug(connection.getInfo().connectionId + " session connection:Endpoint=" + connection.getEndpoint().ToString()); //添加push Prx var sessionPushI = new SessionPushI(); var proxy = ISessionPushPrxHelper.uncheckedCast(Adapter.addWithUUID(sessionPushI)); foreach (var proto in iceClientOptions.PushObjects) { Adapter.addFacet(proto.push, proxy.ice_getIdentity(), proto.name); } //监听连接断开事件,并且绑定该连接到adapter connection.setCloseCallback(_ => { NLogger.Warn($"{tmpconid} connecton closed!"); sessionPushI.SessionDestroyed(); }); connection.setAdapter(Adapter); //创建session,并且注册push Prx到服务器 await sessionFactoryPrx.CreateSessionAsync(proxy); return(new SessionIce(sessionFactoryPrx, sessionPushI)); }
private void ImportExecute(object obj) { EditorFocus(); OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = CommonDefine.ImageFilter; if (openFile.ShowDialog() == false) { return; } try { if (_page != null) { Stream oldStream; if (ImgSource != null) { oldStream = new MemoryStream((int)_page.Icon.Length); _page.Icon.Seek(0, SeekOrigin.Begin); _page.Icon.CopyTo(oldStream); oldStream.Seek(0, SeekOrigin.Begin); } else { oldStream = null; } MemoryStream stream = new MemoryStream(File.ReadAllBytes(openFile.FileName)); ImportIcon(stream); if (CurrentUndoManager != null) { ImportPageIconCommand imgCmd = new ImportPageIconCommand(this, oldStream, stream); CurrentUndoManager.Push(imgCmd); } } } catch (System.Exception e) { NLogger.Warn("Import page icon failed: ", e.Message); } }
public ActionResult <string> TestLog() { try { Logger.Debug($"Log4net调试日志:{Guid.NewGuid().ToString("N")}"); Logger.Info($"Log4net消息日志:{Guid.NewGuid().ToString("N")}"); Logger.Warn($"Log4net警告日志:{Guid.NewGuid().ToString("N")}"); NLogger.Debug($"NLog调试日志:{Guid.NewGuid().ToString("N")}"); NLogger.Info($"NLog消息日志:{Guid.NewGuid().ToString("N")}"); NLogger.Warn($"NLog警告日志:{Guid.NewGuid().ToString("N")}"); throw new NullReferenceException("空异常"); } catch (Exception ex) { Log4net.Logger.Error($"Log4net异常日志:{Guid.NewGuid().ToString("N")}", ex); NLogger.Error($"NLog异常日志:{Guid.NewGuid().ToString("N")}", ex); } return(""); }
public void CheckRecoveryFileExist() { if (!_isEnable) { return; } this.LoadRecoveryFiles(); if (RecoveryInfo != null && RecoveryInfo.RecoveryFiles != null) { try { NLogger.Info("Check files in recovery setting exist."); var recoveryfiles = RecoveryInfo.RecoveryFiles.Where(x => File.Exists(x.GetFullPath())).ToList(); RecoveryInfo.RecoveryFiles = recoveryfiles; this.SaveRecoveryFiles(); } catch (Exception ex) { NLogger.Warn("CheckRecoveryFileExist failed.{0}", ex.ToString()); } } }
private void OnBulletChange(object newValue) { TextMarkerStyle style = (TextMarkerStyle)newValue; try { if (style == TextMarkerStyle.None) { BulletToNone(); } else if (style == TextMarkerStyle.Disc) { NoneToBullet(); } } catch (System.Exception ex) { NLogger.Warn("RichBlocks OnBulletChange error," + ex.Message.ToString()); } TranslateControlToText(); }
public void CreateLibrary() { try { RenameWindow win = new RenameWindow(); win.NewName = CommonDefine.Untitled; win.Owner = Application.Current.MainWindow; win.ShowDialog(); if (win.Result.HasValue && win.Result.Value) { string libraryName = win.NewName; string objectName = CommonDefine.Untitled; ISerializeWriter writer = GetSerializeWriter(ref objectName); if (writer == null) { return; } //Create a new Library. Thumbnail is empty now, and waiting for a improvement IDocumentService DocService = ServiceLocator.Current.GetInstance <IDocumentService>(); ILibrary newLibrary = DocService.LibraryManager.CreateLibrary(writer, objectName, CreateIconImage(false), null); if (newLibrary != null) { ICustomLibraryService customLibraryService = ServiceLocator.Current.GetInstance <ICustomLibraryService>(); customLibraryService.GetMyLibrary().CreateCustomLibrary(newLibrary.Guid, libraryName); } } } catch (Exception ex) { NLogger.Warn("Add Library failed. ex:{0}", ex.ToString()); MessageBox.Show(GlobalData.FindResource("Error_Create_Library") + ex.Message); } }
private static void GetToken(string ucode, string psd) { Dictionary <string, string> postDataDic = new Dictionary <string, string>(); postDataDic.Add("grant_type", "password"); postDataDic.Add("username", ucode); postDataDic.Add("password", psd); postDataDic.Add("client_id", "com.inspur.ecm.client.android"); postDataDic.Add("client_secret", "6b3c48dc-2e56-440c-84fb-f35be37480e8"); HttpResponseMessage resMsg = HttpHelper.PostFormData(loginUrl, postDataDic).Result; string str = resMsg.Content.ReadAsStringAsync().Result; if (resMsg.IsSuccessStatusCode) { Dictionary <string, string> responseDic = JsonConvert.DeserializeObject <Dictionary <string, string> >(str); token = "Bearer " + responseDic["access_token"]; } else { NLogger.Warn("消息推送账号登录失败!"); } }
public ActionResult <IEnumerable <string> > Get() { string sid = this.Sid; try { Logger.Debug($"Log4net调试日志:{Guid.NewGuid().ToString("N")}"); Logger.Info($"Log4net消息日志:{Guid.NewGuid().ToString("N")}"); Logger.Warn($"Log4net警告日志:{Guid.NewGuid().ToString("N")}"); NLogger.Debug($"NLog调试日志:{Guid.NewGuid().ToString("N")}"); NLogger.Info($"NLog消息日志:{Guid.NewGuid().ToString("N")}"); NLogger.Warn($"NLog警告日志:{Guid.NewGuid().ToString("N")}"); throw new NullReferenceException("空异常"); } catch (Exception ex) { Logger.Error($"Log4net异常日志:{Guid.NewGuid().ToString("N")}", ex); NLogger.Error($"NLog异常日志:{Guid.NewGuid().ToString("N")}", ex); } return(new string[] { "value1", "value2" }); }
void createLibrary_Click(object sender, RoutedEventArgs e) { try { string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); path += @"\protoNow.exe"; //pass create library info and current language. string args = "create " + GlobalData.Culture; System.Diagnostics.Process.Start(path, args); var _ListEventAggregator = ServiceLocator.Current.GetInstance <IEventAggregator>(); _ListEventAggregator.GetEvent <DisplayAppLoadingEvent>().Publish(true); SendNClick("mml.createlibrary"); } catch (Exception ex) { NLogger.Warn("Create Library failed. ex:{0}", ex.ToString()); MessageBox.Show(GlobalData.FindResource("Error_Create_Library") + ex.Message); } }
public void Warn() => NLogger?.Warn(Message, TaskType, "LOG", TaskHash, Logging.STAGE, Logging.CurrentLoadProcess?.Id);
public void Warn() => NLogger?.Warn(Message, TaskType, "LOG", TaskHash, ControlFlow.ControlFlow.STAGE, ControlFlow.ControlFlow.CurrentLoadProcess?.LoadProcessKey);