public BotClient(string token, string chatid) { logger = new FileLogger(false); settings = new Settings(); chat_id = chatid.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList(); try { telebotClient = new TelegramBotClient(token); } catch (System.ArgumentException e) { logger.Log(string.Format("TelegramBotClient ERROR: {0}", e.Message), true); logger.Close(); throw new Exception("ERROR: Telegram Bot Client not init!"); } var me = telebotClient.GetMeAsync().Result; logger.Log(string.Format("Hello! I am user {0} and my name is {1}.", me.Id, me.FirstName), true); if (chatid == "") { logger.Log("Chat ID not set yet", true); } telebotClient.OnMessage += Bot_OnMessage; telebotClient.StartReceiving(); }
public string ReadString() { try { string res = ""; byte[] inBuffer = new byte[1024]; int get = 0; do { get = ioStream.Read(inBuffer, 0, inBuffer.Length); res += Encoding.GetEncoding(Settings.DefaultEncoding).GetString(inBuffer).TrimEnd('\0'); Array.Clear(inBuffer, 0, inBuffer.Length); } while (get >= inBuffer.Length); if (Settings.DefaultEncoding != "UTF8") { res = DefaultToUTF8(res); } return(res); } catch (IOException e) { logger.Log(string.Format("ReadPipe ERROR: {0}", e.ToString()), true); } return(""); }
private static void ServerThread(object data) { NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.InOut, numThreads); int threadId = Thread.CurrentThread.ManagedThreadId; logger.Log(string.Format("Start Email thread[{0}].", threadId)); // Wait for a client to connect pipeServer.WaitForConnection(); logger.Log(string.Format("Client connected on Email thread[{0}].", threadId)); try { // Read the request from the client. Once the client has // written to the pipe its security token will be available. StreamString ss = new StreamString(pipeServer); // Verify our identity to the connected client using a // string that the client anticipates. string content = ss.ReadString(); logger.Log(string.Format("Get Email message:\n{0}", content)); var CountArray = content.Length; var Subject = Settings.DefaultEmail_subject; var Body = String.Join("\n", content); MailAddress From = new MailAddress(Settings.DefaultSender); MailAddress To = new MailAddress(Settings.DefaultRecipient); var msg = new MailMessage(From, To) { Body = Body, Subject = Subject }; if (Settings.DefaultTo_copy != "") { string[] elements = Settings.DefaultTo_copy.Split(';'); foreach (var element in elements) { msg.CC.Add(new MailAddress(element.Trim())); } } var smtpClient = new SmtpClient(Settings.DefaultSmtpServer, Settings.DefaultServerPort) { Credentials = new NetworkCredential(Settings.DefaultLogin, Settings.DefaultPassword), EnableSsl = true }; smtpClient.Send(msg); } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { logger.Log(string.Format("Email ServerThread ERROR: {0}", e.Message), true); } pipeServer.Close(); }
public PipeTeleServer() { Console.OutputEncoding = System.Text.Encoding.UTF8; PipeName = Settings.DefaultTPipeName; botClient = new BotClient(Settings.DefaultToken, Settings.DefaultChatId); logger = new FileLogger(false); int i; Thread[] servers = new Thread[numThreads]; logger.Log(string.Format("\nStart Telegram Named pipe server stream {0}\n", PipeName), true); logger.Log("Waiting for client connect...", true); logger.Log("Press 'q' to exit", true); for (i = 0; i < numThreads; i++) { servers[i] = new Thread(ServerThread); servers[i].Start(); } Thread.Sleep(250); Task.Factory.StartNew(() => { while (!ExitWait.exit) { for (int j = 0; j < numThreads; j++) { if (servers[j] != null) { if (servers[j].Join(250)) { logger.Log(string.Format("Telegram Server thread[{0}] finished.", servers[j].ManagedThreadId)); servers[j].Abort(); servers[j] = null; } } else { servers[j] = new Thread(ServerThread); servers[j].Start(); } } } for (int j = 0; j < numThreads; j++) { if (servers[j] != null) { servers[j].Abort(); servers[j] = null; } } logger.Log(string.Format("\nTelegram Server {0} stops, exiting.", PipeName), true); }); }
private static void ServerThread(object data) { NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.InOut, numThreads); int threadId = Thread.CurrentThread.ManagedThreadId; logger.Log(string.Format("Start Telegram thread[{0}].", threadId)); // Wait for a client to connect pipeServer.WaitForConnection(); logger.Log(string.Format("Client connected on Telegram thread[{0}].", threadId)); try { // Read the request from the client. Once the client has // written to the pipe its security token will be available. StreamString ss = new StreamString(pipeServer); // Verify our identity to the connected client using a // string that the client anticipates. string content = ss.ReadString(); logger.Log(string.Format("Get Telegram message:\n{0}", content)); logger.Log(string.Format("GetIncomeMessages {0}", content.Contains("GetIncomeMessages()"))); if (content.Contains("GetIncomeMessages()")) { var msgs = botClient.GetIncomeMessages(); if (msgs == null) { msgs = "{[===[No new messages]===]}"; } ReadMessagesToStream msgsReader = new ReadMessagesToStream(ss, msgs); ss.ClearMessages += new OnReplyHandler(BotClient.ClearIncomeMessages); pipeServer.RunAsClient(msgsReader.Start); } else { botClient.Send(content); } } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { logger.Log(string.Format("Telegram ServerThread ERROR: {0}", e.Message), true); } pipeServer.Close(); }
public static void Log(LogTarget target, string message, bool isError = false) { if (_enableLogging) { switch (target) { case LogTarget.File: _logger = new FileLogger(); _logger.Log(message, isError); break; case LogTarget.Database: _logger = new DBLogger(); _logger.Log(message, isError); break; case LogTarget.EventLog: _logger = new EventLogger(); _logger.Log(message, isError); break; default: return; } } }
static void Main(string[] args) { logger = new FileLogger(false); var settings = new Settings(); settings.Read(); if (Settings.DefaultToken == "") { logger.Log("ERROR: Token not set!", true); logger.Close(); throw new Exception("ERROR: Token not set!"); } var exit = new ExitWait(); exit.Start(); if (Settings.DefaultStartTele == "ON") { new PipeTeleServer(); } if (Settings.DefaultStartEmail == "ON") { new PipeEmailServer(); } }
public static void Log(LogTarget target, string message) { switch (target) { case LogTarget.File: logger = new FileLogger(); logger.Log(message); break; default: return; } }
public static void Log(LogTarget target, LogType logType, string message) { switch (target) { case LogTarget.File: _logger = new FileLogger(); _logger.Log($"{DateTime.Now} | {logType} | {message}"); break; default: return; } }
async void Bot_OnMessage(object sender, MessageEventArgs e) { if (e.Message.Text != null) { logger.Log(string.Format("Received a text message in chat {0}:\n", e.Message.Chat.Id), true); logger.Log(string.Format("{0}", e.Message.Text)); if (chat_id.FirstOrDefault(item => item == e.Message.Chat.Id.ToString()) == null) { chat_id.Add(e.Message.Chat.Id.ToString()); Settings.DefaultChatId = String.Join(";", chat_id.ToArray()); settings.Update(); await telebotClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "Ок " + e.Message.From + ". I`ll subscribe to this chat" ); } else { income_msgs.Add(e.Message.Text.Trim()); } } }
public static void Log(LogTarget target, string type, string weighingOrderCode, string message, string userID) { switch (target) { case LogTarget.Database: logger = new DBLogger(); logger.Log(type, weighingOrderCode, message, userID); break; default: return; } }
public static void Log(LogTarget target, string message) { switch (target) { case LogTarget.File: logger = new FileLogger(); logger.Log(message); break; case LogTarget.Database: logger = new DBLogger(); logger.Log(message); break; case LogTarget.EventLog: logger = new EventLogger(); logger.Log(message); break; } }
protected override void Execute(CodeActivityContext context) { switch (logTarget.Get(context)) { case LogTarget.File: logger = new FileLogger(); logger.Log(logMessage.Get(context)); break; case LogTarget.EventLog: logger = new EventLogger(); logger.Log(logMessage.Get(context)); break; default: return; } }
public async Task Invoke(HttpContext context) { var requestId = Guid.NewGuid(); var requestMessage = await FormatRequest(context.Request, requestId); var originalBodyStream = context.Response.Body; await using var responseBody = new MemoryStream(); context.Response.Body = responseBody; _requestLogger.Log(requestMessage); await _next(context); var responseMessage = await FormatResponse(context.Response, requestId); _responseLogger.Log(responseMessage); await responseBody.CopyToAsync(originalBodyStream); }
private static void SetMessage(LogType logtype, string message) { switch (logtype) { case LogType.info: _message = $"[INFO]\t\t{message}"; break; case LogType.error: _message = $"[ERROR]\t\t{message}"; break; case LogType.warning: _message = $"[WARNING]\t\t{message}"; break; } _logbase.Log(_message); }
public static void Log(LogTarget target, string message) { switch (target) { case LogTarget.File: _logger = new FileLogger(); _logger.Log(message); break; case LogTarget.Database: _logger = new DataBaseLogger(); _logger.Log(message); break; case LogTarget.EventLog: _logger = new EventLogger(); _logger.Log(message); break; default: return; } }
public static void Log(LogTarget target, int id, string message, DateTime dateTimeStamp) { switch (target) { case LogTarget.File: logger = new FileLogger(); logger.Log(id, message, dateTimeStamp); break; case LogTarget.Database: logger = new DbLogger(); logger.Log(id, message, dateTimeStamp); break; case LogTarget.EventLog: logger = new EventLogger(); logger.Log(id, message, dateTimeStamp); break; default: return; } }
public static void Log(LogTarget target, Exception exception) { switch (target) { case LogTarget.File: logger = new FileLogger(); logger.Log(exception); break; case LogTarget.EventLog: logger = new EventLogger(); logger.Log(exception); break; case LogTarget.Database: logger = new DbLogger(); logger.Log(exception); break; default: return; } }
public static void Log(string message) { logger = new FileLogger(); logger.Log(message); }
public static void ChainOfRepoQuestion() { BillHandlerBase billHandler500 = new BillHandler500(); BillHandlerBase billHandler200 = new BillHandler200(); BillHandlerBase billHandler100 = new BillHandle100(); BillHandlerBase billHandler25 = new BillHandle25(); BillHandlerBase coinHandler5 = new CoinHandler5(); BillHandlerBase coinHandler2 = new CoinHandler2(); BillHandlerBase chainRoot = billHandler500; billHandler500.SetNext(billHandler200); billHandler200.SetNext(billHandler100); billHandler100.SetNext(billHandler25); billHandler25.SetNext(coinHandler5); coinHandler5.SetNext(coinHandler2); Console.WriteLine("748:"); chainRoot.Handle(748); Console.WriteLine("=================="); Console.WriteLine("385:"); chainRoot.Handle(385); Console.WriteLine("=================="); Console.WriteLine("400:"); chainRoot.Handle(400); Console.WriteLine("=================="); Console.WriteLine("402:"); chainRoot.Handle(402); Console.WriteLine("LogsPart ============"); LogBase fatalLogger = new FatalLogger(); LogBase errorLogger = new ErrorLogger(); LogBase debugLogger = new DebugLogger(); LogBase infoLogger = new InfoLogger(); LogBase chainRootLog = fatalLogger; fatalLogger.SetNext(errorLogger); errorLogger.SetNext(debugLogger); debugLogger.SetNext(infoLogger); chainRootLog.Log("Dude", 1); Console.WriteLine("=================="); chainRootLog.Log("Memoization", 4); Console.WriteLine("=================="); chainRootLog.Log("XD TV", 3); LogBase chainRootLog2 = infoLogger; infoLogger.SetNext(debugLogger); debugLogger.SetNext(errorLogger); errorLogger.SetNext(fatalLogger); fatalLogger.SetNext(null); chainRootLog2.Log("Dude", 1); Console.WriteLine("=================="); chainRootLog2.Log("Memoization", 4); Console.WriteLine("=================="); chainRootLog2.Log("XD TV", 3); }
/// <summary> /// Recored message. Message will not be recored when property LogLevel is higher than the specified log level. /// </summary> /// <param name="message">The message/message format to record.</param> /// <param name="logLevel">Log level of the message.</param> /// <param name="args">The parameters of message format.</param> public static void Print(string message, LogLevel logLevel = LogLevel.Debug, params object[] args) { if (null == _logInstance) { throw new InvalidOperationException("Logger should be initialized before using."); } if (_enabled == LogDisabled || logLevel < _logInstance.LogLevel) { return; } _logInstance.Log(logLevel, string.Format(message, args)); }
static void Main(string[] args) { //Question 1 Context ctx = new Context(new ShipSafe(0)); ctx.LevelUp(); ctx.LevelUp(); ctx.TakeDamage(); ctx.LevelUp(); ctx.LevelUp(); ctx.LevelUp(); ctx.TakeDamage(); ctx.TakeDamage(); //Question 2 Component root = new Composite(2); Component circle1 = new Leaf(1); Component rectangle = new Leaf(2); root.AddChild(circle1); root.AddChild(rectangle); Component container1 = new Composite(1); Component circle2 = new Leaf(3); Component circle3 = new Leaf(1); container1.AddChild(circle2); container1.AddChild(circle3); root.AddChild(container1); Component container2 = new Composite(1); Component t1 = new Leaf(5); Component t2 = new Leaf(1); Component t3 = new Leaf(1); container2.AddChild(t1); container2.AddChild(t2); container2.AddChild(t3); root.AddChild(container2); root.Draw(""); Console.WriteLine(root.countLeaf()); //Console.WriteLine(container1.countLeaf()); //Console.WriteLine(container2.countLeaf()); //Console.WriteLine(t1.countLeaf()); Console.WriteLine(isZugi(root)); //Question 3 CarProxy car = new CarProxy(); // Drive the car car.StartDriving(); car.showLocation(); //Question 5 FatalLogger fatal = new FatalLogger(); ErrorLogger error = new ErrorLogger(); InfoLogger info = new InfoLogger(); LogBase chainRoot = fatal; fatal.SetNext(error); error.SetNext(info); info.SetNext(null); chainRoot.Log("tell me why", 2); Console.WriteLine("=================="); //Question 8 GymAccessObject gymthings = new GymBase(); gymthings.Run(); //Question 10 IWindow window = new BaseWindow(); IWindow Tlatmeimad = new TlatMeimadWindow(window); IWindow super = new FlashingWindow(Tlatmeimad); Console.WriteLine(super.GetDetails()); IWindow myfavoriteWindow = new Colors(new TlatMeimadWindow(new FlashingWindow(new BaseWindow()))); Console.WriteLine(myfavoriteWindow.GetDetails()); //Question 12 ComputerFactoryMethod cf = new ComputerFactoryMethod(); Computer v1 = cf.GetComputer("Gaming"); }