static void Main(string[] args) { var l1 = new Logger(); l1.Value = "foo"; l1.Save(); var l2 = new Logger2(); l2.Value = 123; l2.Save(); #region after Generics //var l1 = new GenericLogger<string>(); //l1.Value = "foo"; //l1.Save(); //var l2 = new GenericLogger<int>(); //l2.Value = 123; //l2.Save(); #endregion Console.ReadLine(); }
/// <summary> /// Get the HTML document for the specified URI. /// </summary> /// <param name="uri">The URI to load.</param> /// <param name="token">The cancellation token.</param> /// <returns>Returns the requested page, if found. Otherwise, null.</returns> private async static Task <HtmlDocument?> GetDocumentAsync(Uri uri, IPageProvider pageProvider, CancellationToken token) { HtmlDocument?page = null; try { page = await pageProvider.GetHtmlDocumentAsync(uri.AbsoluteUri, uri.Host, CachingMode.UseCache, ShouldCache.Yes, SuppressNotifications.Yes, token) .ConfigureAwait(false); if (token.IsCancellationRequested) { page = null; } } catch (OperationCanceledException) { } catch (Exception e) { Logger2.LogError(e, "Attempt to query site to determine forum adapter failed."); } return(page); }
/// <summary> /// Defines the name and version information based on attributes pulled from the assembly file. /// </summary> private static void DefineNameAndVersion() { try { var assembly = typeof(ProductInfo).GetTypeInfo().Assembly; var prod = assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(AssemblyProductAttribute)); var ver = assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(AssemblyInformationalVersionAttribute)); var fVer = assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(AssemblyFileVersionAttribute)); AssemblyVersion = assembly.GetName().Version; if (prod != null && prod.ConstructorArguments.Count > 0) { Name = prod.ConstructorArguments[0].Value as string ?? Name; } if (ver != null && ver.ConstructorArguments.Count > 0) { Version = ver.ConstructorArguments[0].Value as string ?? Version; } if (fVer != null && fVer.ConstructorArguments.Count > 0) { string fileVersionString = fVer.ConstructorArguments[0].Value as string ?? "0.0.0.1"; FileVersion = new Version(fileVersionString); } } catch (Exception e) { Logger2.LogError(e, "Attempt to define the name and version of the program failed."); } }
public void initPipe() { try { var PipeServer = new NamedPipeServerStream("np1", PipeDirection.Out); var PipeChild = new NamedPipeClientStream(".", "np2", PipeDirection.In); sr = new StreamReader(PipeChild); sw = new StreamWriter(PipeServer); PipeServer.WaitForConnection(); PipeChild.Connect(); sw.AutoFlush = true; bool res = PipeServer.IsConnected; Logger2.Infor("pipe连接结果:" + res.ToString()); this.Invoke(new Action(() => { richTextBox1.AppendText(res.ToString() + " " + DateTime.Now + "\n"); })); ReciveDataAnalyze(); } catch (Exception ex) { MessageBox.Show(ex.Message, "主进程"); } }
public void StartProcess(ProcessStartInfo ps) { try { Logger2.Infor("starting process"); using (Process pt = Process.Start(ps)) //using (Process progressTest = Process.Start(ps)) { // _ = progressTest.TotalProcessorTime; // 为异步获取订阅事件 pt.OutputDataReceived += new DataReceivedEventHandler(OnDataReceived); pt.ErrorDataReceived += new DataReceivedEventHandler(OnDataReceived); // 异步获取命令行内容 pt.BeginOutputReadLine(); //Thread.Sleep(2000); //pt.WaitForExit(); //pt.Close(); } } catch (Exception ee) { throw; } }
public void InitPipe() { try { ChildPipeClient_1 = new NamedPipeClientStream(".", "np1", PipeDirection.In); //所有管道都在使用中,父子说明重复了 ChildPipeServer_2 = new NamedPipeServerStream("np2", PipeDirection.Out); sr_1 = new StreamReader(ChildPipeClient_1); sw_2 = new StreamWriter(ChildPipeServer_2); ChildPipeClient_1.Connect(); //此处的顺序很重要,必须与服务器向匹配,否则会一直阻塞 ChildPipeServer_2.WaitForConnection(); sw_2.AutoFlush = true; //reconnecting 只有客户端 //ReConnect(); Logger2.Infor("pipe connected 02"); StartPipeThread(); } catch (Exception ex) { Logger2.Error(ex.Message); ChildPipeClient_1.Close(); ChildPipeServer_2.Close(); sr_1.Close(); sw_2.Close(); MessageBox.Show(ex.Message, "子进程"); // throw; } }
public App() { logger = new Logger("Logger1", LogMode.CURRENT_FOLDER, AlertMode.CONSOLE); logger.LifeCycle = true; logger2 = new Logger2("ApplicationHundleExceptionLogger", LogMode.CURRENT_FOLDER, AlertMode.CONSOLE); this.DispatcherUnhandledException += App_DispatcherUnhandledException1; }
public static void Main() { //Logger2.Write("hello"); //try //{ // string a = "ff"; // int b = Convert.ToInt32(a); //} //catch (Exception ex) //{ // Logger2.Write(ex.Message); //} Stopwatch st = new Stopwatch(); st.Start(); string mg = "handshake error, plc init failed 在 System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)在 System.Net.Sockets.Socket.Connect(String host, Int32 port)在 PLCCommunicationKit.SocketBaseKit.SocketBase.initSocketBase(String ip, Int32 "; System.Threading.Tasks.Parallel.For(0, 1000, x => { Logger2.Infor("test" + x.ToString()); Logger2.Error(mg + x.ToString()); //Console.WriteLine(x); }); st.Stop(); Console.WriteLine(st.ElapsedMilliseconds); Console.ReadKey(); }
public App() { logger = new Logger("Logger1", LogMode.CURRENT_FOLDER, AlertMode.CONSOLE); logger.LifeCycle = true; logger2 = new Logger2("ApplicationHundleExceptionLogger", LogMode.CURRENT_FOLDER, AlertMode.CONSOLE); this.DispatcherUnhandledException += App_DispatcherUnhandledException1; //#region Base Life Cycle //this.Startup += App_Startup; //this.LoadCompleted += App_LoadCompleted; //this.Activated += App_Activated; //this.Deactivated += App_Deactivated; //this.SessionEnding += App_SessionEnding; //this.Exit += App_Exit; //#endregion //#region Errors //this.DispatcherUnhandledException += App_DispatcherUnhandledException; //#endregion //#region Navigation //this.FragmentNavigation += App_FragmentNavigation; //this.Navigated += App_Navigated; //this.Navigating += App_Navigating; //this.NavigationFailed += App_NavigationFailed; //this.NavigationProgress += App_NavigationProgress; //this.NavigationStopped += App_NavigationStopped; //#endregion }
private void Logs() { Logger2 logger2 = new Logger2("MyLogger", LogMode.CURRENT_FOLDER, AlertMode.CONSOLE); //logger2.Log("bonjour", "mon message"); //logger2.Log(new Exception("New Exception message"),"Error occured"); Task.Factory.StartNew(() => { int i = 0; while (true) { Task.Factory.StartNew(() => { try { this.clientView.UCClient.clientBillTxtB.Text = "hey"; } catch (Exception e) { logger2.Log("error :" + i); i++; } }); } }); //Logger logger = new Logger(); //logger.Log("Default logger welcome"); //logger.Log("With temp options", LogMode.CONSOLE); //Logger logger1 = new Logger("MyLogger", LogMode.CONSOLE, AlertMode.CONSOLE); //logger1.Log("Welcome from custom logger"); //Logger logger2 = new Logger(); //logger2.Log("With temp options", LogMode.CONSOLE, AlertMode.MESSAGE_BOX); //Logger logger3 = new Logger("overlay",LogMode.CONSOLE, AlertMode.OVERLAY); //for (int i = 0; i < 4; i++) //{ // logger3.Log("First one"); // logger3.Log("Second one "); //} //Logger logger4 = new Logger("current folder", LogMode.CURRENT_FOLDER, AlertMode.OVERLAY); //logger4.Log("logger 4 to current folder"); //Task.Factory.StartNew(() => //{ // for (int i = 0; i < 1000000000; i++) // { // logger4.Log("next reported lognext reported lognext reported lognext reported lognext reported lognext reported lognext reported lognext reported lognext"); // } //}); //logger4.Log("other"); }
private static void OnDataReceived(object Sender, DataReceivedEventArgs e) { if (e.Data != null) { Console.WriteLine(e.Data); Logger2.Infor(e.Data); } }
private void ReConnect() { if (ChildPipeClient_1.IsConnected != true) { ChildPipeClient_1.Connect(10000); Console.WriteLine("pipe1 before " + ChildPipeClient_1.IsConnected.ToString()); Logger2.Infor("pipe1 before " + ChildPipeClient_1.IsConnected.ToString()); } }
public void ShouldReturnJsonWithAnEnvPropertyOfDevelopmentTest() { var conf = new Dictionary <string, string> { { "Lambda.Logging:LogLevel:BunyanLambdaLogger*", "Trace" } }; var logger = Logger2.Create(conf, nameof(BunyanLambdaLoggerWithEnvTest), "development"); logger.LogTrace("This should include a property of env with a value of development"); }
public void Logger2Test() { Logger2 instance1 = Logger2.GetInstance(); Logger2 instance2 = Logger2.GetInstance(); Assert.Same(instance1, instance1); instance1.Counter++; Assert.Equal(instance1.Counter, instance2.Counter); instance2.Counter++; Assert.Equal(instance1.Counter, instance2.Counter); }
static void Main(string[] args) { try { Logger2.Infor("inside sub process 01"); if (args.Length > 0) { CpuType cpu = (CpuType)Convert.ToInt32(args[0]); string ip = args[1]; CreateSocketProcess cs = new CreateSocketProcess(cpu, ip); MyProxy = cs.MyPlcInstance; MyProxy.Open(); //cs.DB = Convert.ToInt32(args[2]); //cs.StartAddr = Convert.ToInt32(args[3]); //cs.ReadCount = Convert.ToInt32(args[4]); #region MyRegion //pip communicate //foreach (string s in args) //{ // Logger2.Infor("args is :" + s); //} // Console.WriteLine(args[0]); //sw.WriteLine("client recieved :"+temp); #endregion PipeHelper ph = new PipeHelper(); ph.InitPipe(); //ReadPlcAndWritePipe(cs, MyProxy); Console.ReadKey(); } else { Console.WriteLine("wrong input para number,please check"); Console.ReadKey(); } } catch (Exception ex) { Logger2.Error(ex.Message); MessageBox.Show(ex.Message, "子进程提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void StartPipeThread() { //Task ReadingTask = new Task(Pipe4Reading); //Task<bool> SendingTask = new Task(Pipe4Sending,"ss"); //Task SendingTask = new Task(() => Pipe4Sending("initing")); Thread th = new Thread(Pipe4Reading); Thread th2 = new Thread(new ParameterizedThreadStart(Pipe4Sending)); th.IsBackground = true; //th2.IsBackground = true; th.Name = "p4r"; th.Start();//接收线程 //th2.Name = "p4w"; sw_2.AutoFlush = true; sw_2.WriteLine("from sub process: sub thread status {0},{1}", th.IsAlive, th2.IsAlive); Logger2.Infor($"from sub process: sub thread status {th.IsAlive},{th2.IsAlive}"); //th2.Start("ssss"); //Console.WriteLine("start rec send thread {0} {1}",th.IsAlive,th2.IsAlive); //Pipe4Sending("ssss"); //Pipe4Sending(); }
private void button5_Click(object sender, EventArgs e) { #region test //var s = Math.Round(53.3012619227981, 2); ////Random sss = new Random(Convert.ToInt32( DateTime.Today.Day)); //double punchingRadius = 51.9290909090909; //punchingRadius = Math.Round(punchingRadius, 2); //var sss = Convert.ToDouble(punchingRadius.ToString().Split('.')[1]) / 200; //richTextBox1.Text = sss.ToString(); #endregion if (check_process_status()) { try { string temp; if ((temp = richTextBox2.Text) != "") { sw.WriteLine(temp); richTextBox2.Clear(); } else { MessageBox.Show("请先输入"); } } catch (Exception ex) { Logger2.Infor(ex.Message); MessageBox.Show(ex.Message); } } else { MessageBox.Show("请先开启子进程", "主线程提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
/// <summary> /// Creates a regex based on the provided strings. /// Treats these strings as simple, comma-delimited option lists, /// with possible * globs. /// </summary> /// <param name="simpleString">The user-defined filter string.</param> /// <param name="injectString">The default, program-provided string to filter on.</param> /// <returns>Returns a regex constructed from the strings.</returns> private Regex CreateSimpleRegex(string simpleString, string?injectString) { if (string.IsNullOrEmpty(simpleString) && string.IsNullOrEmpty(injectString)) { return(EmptyRegex); } string safeGlobString = simpleString.RemoveUnsafeCharacters(); var splits = safeGlobString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); StringBuilder sb = new StringBuilder(); string bar = ""; // Convert comma-separated entries to |'d regex options. // If a segment contains special regex characters, escape those characters. // If a segment contains a *, treat it as a general glob: .* foreach (var split in splits) { string s = split.Trim(); if (!string.IsNullOrEmpty(s)) { s = escapeChars.Replace(s, @"\$1"); s = splat.Replace(s, @".*"); string preBound = ""; string postBound = ""; if (preWord.Match(s).Success) { preBound = @"\b"; } if (postWord.Match(s).Success) { postBound = @"\b"; } sb.Append(bar).Append(preBound).Append(s).Append(postBound); bar = "|"; } } // Add the default string value (if any) at the end. if (!string.IsNullOrEmpty(injectString)) { sb.Append(bar).Append(injectString); } try { return(new Regex($@"{sb.ToString()}", RegexOptions.IgnoreCase)); } catch (ArgumentException e) { Logger2.LogError(e, $"Failed to create regex using string: [{sb.ToString()}]"); } // If the attempt to create the regex to be returned failed, bail and // return a pure false regex. IsInverted = false; return(alwaysFalse); }
public LoggerAdapter(Logger2.ILogger logger) { _logger = logger; }
public static void Critical(Guid correlationId, string content, string action = "", string tag = "", string component = "", string hostName = "", string envInfo = "", bool ariaOn = false) { Logger2.Critical(correlationId, content, action, tag, component, hostName, envInfo); }
/// <summary> /// Gets the list of threadmarks from an index page. /// Handle nested threadmarks. /// If the page doesn't have any threadmarks, return an empty list. /// Runs a filter (ThreadmarksFilter class) on any threadmark titles. /// Any that don't pass aren't included in the list. /// </summary> /// <param name="quest">The quest.</param> /// <param name="page">The index page of the threadmarks.</param> /// <returns>Returns a list of all unfiltered threadmark links.</returns> static IEnumerable <HtmlNode> GetThreadmarksListFromIndex(IQuest quest, HtmlDocument page) { try { HtmlNode content = GetPageContent(page, PageType.Threadmarks); HtmlNode?threadmarksDiv = content.GetDescendantWithClass("div", "threadmarks"); HtmlNode?listOfThreadmarks = null; HtmlNode?threadmarkList = threadmarksDiv?.GetDescendantWithClass("threadmarkList"); if (threadmarkList != null) { // We have a .threadmarkList node. This is either an ol itself, or it will contain a ThreadmarkCategory_# ol node. We want category 1. if (threadmarkList.Name == "ol") { if (threadmarkList.GetAttributeValue("class", "").Contains("ThreadmarkCategory")) { if (!threadmarkList.HasClass("ThreadmarkCategory_1")) { return(Enumerable.Empty <HtmlNode>()); } } listOfThreadmarks = threadmarkList; } else { listOfThreadmarks = threadmarkList.GetDescendantWithClass("ol", "ThreadmarkCategory_1"); } } else { // threadmarkList was null. There is no .threadmarkList node, so check for undecorated ul that contains .threadmarkItem list items. listOfThreadmarks = threadmarksDiv?.Descendants("ul").FirstOrDefault(e => e.Elements("li").Any(a => a.HasClass("threadmarkItem"))); } if (listOfThreadmarks != null) { Func <HtmlNode, bool> filterLambda = (n) => n != null && ((quest.UseCustomThreadmarkFilters && (quest.ThreadmarkFilter?.Match(n.InnerText) ?? false)) || (!quest.UseCustomThreadmarkFilters && DefaultThreadmarkFilter.Match(n.InnerText))); Func <HtmlNode, HtmlNode> nodeSelector = (n) => n.Element("a"); Func <HtmlNode, IEnumerable <HtmlNode> > childSelector = (i) => i.Element("ul")?.Elements("li") ?? new List <HtmlNode>(); var results = listOfThreadmarks.Elements("li").TraverseList(childSelector, nodeSelector, filterLambda); return(results); } } catch (ArgumentNullException e) { Logger2.LogError(e, "Failure when attempting to get the list of threadmarks from the index page. Null list somewhere?"); } return(Enumerable.Empty <HtmlNode>()); }
/// <summary> /// Get a completed post from the provided HTML list item node. /// </summary> /// <param name="li">List item node that contains the post.</param> /// <returns>Returns a post object with required information.</returns> private Post?GetPost(HtmlNode li, IQuest quest) { if (li == null) { throw new ArgumentNullException(nameof(li)); } string author; string id; string text; int number; // Author and ID are in the basic list item attributes author = ForumPostTextConverter.CleanupWebString(li.GetAttributeValue("data-author", "")); id = li.Id.Substring("post-".Length); if (AdvancedOptions.Instance.DebugMode) { author = $"{author}_{id}"; } // Get the primary content of the list item HtmlNode?primaryContent = li.GetChildWithClass("primaryContent"); // On one branch, we can get the post text HtmlNode?messageContent = primaryContent?.GetChildWithClass("messageContent"); HtmlNode?postBlock = messageContent?.Element("article")?.Element("blockquote"); // Predicate filtering out elements that we don't want to include List <string> excludedClasses = new List <string> { "bbCodeQuote", "messageTextEndMarker", "advbbcodebar_encadre", "advbbcodebar_article", "adv_tabs_wrapper", "adv_slider_wrapper" }; if (quest.IgnoreSpoilers) { excludedClasses.Add("bbCodeSpoilerContainer"); } var exclusions = ForumPostTextConverter.GetClassesExclusionPredicate(excludedClasses); // Get the full post text. text = ForumPostTextConverter.ExtractPostText(postBlock, exclusions, Host); // On another branch of the primary content, we can get the post number. HtmlNode?messageMeta = primaryContent?.GetChildWithClass("messageMeta"); // HTML parsing of the post was corrupted somehow. if (messageMeta == null) { return(null); } HtmlNode?publicControls = messageMeta.GetChildWithClass("publicControls"); HtmlNode?postNumber = publicControls?.GetChildWithClass("postNumber"); if (postNumber == null) { return(null); } string postNumberText = postNumber.InnerText; // Skip the leading # character. if (postNumberText.StartsWith("#", StringComparison.Ordinal)) { postNumberText = postNumberText.Substring(1); } number = int.Parse(postNumberText); Post?post; try { Origin origin = new Origin(author, id, number, Site, GetPermalinkForId(id)); post = new Post(origin, text); } catch (Exception e) { Logger2.LogError(e, $"Attempt to create new post failed. (Author:{author}, ID:{id}, Number:{number}, Quest:{quest.DisplayName})"); post = null; } return(post); }
public static void Debug(Guid correlationId, string content, string action = "", string tag = "", string component = "", string hostName = "", string envInfo = "") { Logger2.Debug(correlationId, content, action, tag, component, hostName, envInfo); }
/// <summary> /// 子进程 读取管道中服务器的命令 /// </summary> public void Pipe4Reading() { try { string temp; while ((temp = sr_1.ReadLine()) != null) { try { Logger2.Infor(temp + " 03"); //string temp = "N hello"; string mode = temp.Split(' ')[0]; //string mode = temp.Substring(0, 1); string str_cmd = temp.Substring(2); sw_2.WriteLine(mode); sw_2.WriteLine(str_cmd); switch (mode) { case "R": //reading from plc { object s = Childprogram.MyProxy.Read(str_cmd); sw_2.WriteLine(s); } break; case "W": //writing to plc { sw_2.WriteLine("w"); } break; case "exit": // normal,not about plc { sw_2.WriteLine("exiting"); exit(); } break; case "hello": { sw_2.WriteLine("Hi"); } break; default: MessageBox.Show("error cmd", "子进程解析"); break; } } catch (Exception ex) { MessageBox.Show(ex.Message, "子进程"); } // Logger2.Infor("recing " + temp); } } catch (Exception ex) { MessageBox.Show(ex.Message, "子进程"); // throw; } }
public static void exit() { Logger2.Infor("exited"); Environment.Exit(0); }