public static void Main(string[] args) { Logger?.Info("Starting wcf server..."); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; #region self hosting impl. string selfHostUrls = System.Configuration.ConfigurationManager.AppSettings["SelfHostUrls"]?.ToString(); string[] urls = selfHostUrls?.Trim()?.Split(';')?.Select(x => x?.Trim())?.ToArray(); List <Uri> uris = new List <Uri>(); if (urls?.Count() > 0) { foreach (string url in urls) { if (Uri.TryCreate(url, UriKind.Absolute, out var uri)) { uris.Add(uri); } } } if (uris.Count <= 0) { uris.Add(new Uri("http://0.0.0.0:5000")); } #endregion try { using (ServiceHost serviceHost = new ServiceHost(typeof(Service), uris.ToArray())) { serviceHost.UnknownMessageReceived += ServiceHost_UnknownMessageReceived; serviceHost.Opening += ServiceHost_ChannelEvent; serviceHost.Opened += ServiceHost_ChannelEvent; serviceHost.Closing += ServiceHost_ChannelEvent; serviceHost.Closed += ServiceHost_ChannelEvent; serviceHost.Faulted += ServiceHost_ChannelEvent; serviceHost.Open(); Logger?.Info("The service is ready at: "); foreach (var uri in uris) { Logger?.Info(uri.ToString()); } Logger?.Info("Press <ENTER> to terminate service."); Console.ReadLine(); } } catch (Exception ex) { Logger?.Error(ex, ex.Message); //this is for autorestart the service after failure in bad state! Environment.Exit(-1); } }
static void Main(string[] args) { SetupLogger(); FullConfig?config = GetConfig(); if (config == null) { return; } CancellationTokenSource source = new(); Classroom classroom = new Classroom(config, source.Token); Meet? meet = null; try { meet = classroom.InitMeetInstance(source.Token); logger?.Debug("Starting classroom"); Task crTask = classroom.Start(); logger?.Debug("Starting meet"); Task meetTask = meet.Start(); logger?.Debug("Started all"); Console.ReadLine(); source.Cancel(); Task.WaitAll(crTask, meetTask); } catch (AggregateException ex) { if (ex.InnerException is TaskCanceledException) { logger?.Info("Successfully canceled"); } else { logger?.Error(ex); } } catch (Exception ex) { logger?.Error(ex); } finally { source.Dispose(); meet?.Dispose(); classroom.Dispose(); } }
static void Main(string[] args) { if (File.Exists(_logFile)) { _logger = NLog.Web.NLogBuilder.ConfigureNLog(_logFile).GetCurrentClassLogger(); } try { using (var container = new ServiceContainer(new ContainerOptions { EnablePropertyInjection = false })) { var provider = ConfigureServices(container); // run the service ServiceHostProvider .ConfigureService <BinnerWebHostService>(container, provider) .Run(); } } catch (Exception ex) { _logger?.Error(ex, "Main exception"); throw; } finally { NLog.LogManager.Shutdown(); } }
private SensorBase GetExistingSensor(string path) { SensorBase sensor = null; bool exists = _nameToSensor.TryGetValue(path, out var readValue); if (exists) { sensor = readValue as SensorBase; } if (sensor == null && sensor as IPerformanceSensor != null) { var message = $"Path {path} is used by standard performance sensor!"; _logger?.Error(message); throw new InvalidSensorPathException(message); } return(sensor); }
public bool InitializeWindowsUpdateMonitoring(TimeSpan sensorInterval, TimeSpan updateInterval, string specificPath = null) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { _logger?.Error($"Failed to create {nameof(WindowsUpdateFuncSensor)} " + $"because current OS is not Windows"); return(false); } _logger?.Info($"Initialize windows update sensor..."); var updateSensor = new WindowsUpdateFuncSensor(specificPath, _productKey, _dataQueue as IValuesQueue, string.Empty, sensorInterval, SensorType.BooleanSensor, _isLogging, updateInterval); AddNewSensor(updateSensor, updateSensor.Path); return(true); }
private UnitedSensorValue GetValueInternal() { try { T value = _funcToInvoke.Invoke(); return(CreateDataObject(value)); } catch (Exception e) { _logger?.Error(e); return(CreateErrorDataObject(e)); } }
private void Capture_Load(object sender, EventArgs e) { /////////// Setup logger /////////// logger = NLog.LogManager.GetCurrentClassLogger(); logger.Info("Starting application."); //target.Name = "display"; //target.Layout = "${time} | ${Threadid} | ${level} | ${logger} | ${message}"; //target.ControlName = "richTextBox1"; //target.FormName = "Recorder"; //target.UseDefaultRowColoringRules = true; //NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, NLog.LogLevel.Trace); //target.MaxLines = 1024; //target.AutoScroll = true; ///////////// Set new state to prevent the system from entering sleep mode ///////////// // Source: David Anson @ Microsoft (2009) http://dlaa.me/blog/post/9901642 m_previousExecutionState = NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED); if (0 == m_previousExecutionState) { MessageBox.Show("Failed to set system state for sleep mode.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // No way to recover; fail gracefully Close(); } /////////// Set timer to first snapshot /////////// //(Note: this must by setup on the UI thread) try { logger.Info("Configuring Timer"); timer = new FixedStepDispatcherTimer(new TimeSpan(0, 0, 1)); DateTime now = DateTime.Now; DateTime firstTick = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second + 1); timer.Restart(firstTick); } catch (Exception ex) { logger.Error("Error creating DispatcherTimer: " + ex.Message); } logger.Info("Configuring Recorder BackgroundWorker"); bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork); bw.RunWorkerAsync(); }
private bool TryGetWindowsValue(ManagementObject obj, string key, out string value) { bool isComplete = false; try { value = obj[key].ToString(); isComplete = true; } catch (Exception ex) { value = string.Empty; _logger?.Error(ex, $"Failed to get windows {key}"); CreateErrorDataObject(ex); } return(isComplete); }
/// <summary> /// Implementation of the test itself. /// </summary> /// <returns>true if the test passes, false otherwise.</returns> public override async Task <bool> RunAsync() { IPAddress ServerIp = (IPAddress)ArgumentValues["Server IP"]; int ClNonCustomerPort = (int)ArgumentValues["clNonCustomer Port"]; int ClCustomerPort = (int)ArgumentValues["clCustomer Port"]; log.Trace("(ServerIp:'{0}',ClNonCustomerPort:{1},ClCustomerPort:{2})", ServerIp, ClNonCustomerPort, ClCustomerPort); bool res = false; Passed = false; ProtocolClient client = new ProtocolClient(); List <ProtocolClient> testIdentities = new List <ProtocolClient>(); for (int i = 0; i < IdentityTypes.Count; i++) { testIdentities.Add(new ProtocolClient()); } try { MessageBuilder mb = client.MessageBuilder; // Step 1 log.Trace("Step 1"); bool error = false; for (int i = 0; i < IdentityTypes.Count - 2; i++) { ProtocolClient cl = testIdentities[i]; await cl.ConnectAsync(ServerIp, ClNonCustomerPort, true); if (!await cl.EstablishHostingAsync(IdentityTypes[i])) { error = true; break; } cl.CloseConnection(); } bool hostingOk = !error; error = false; for (int i = 0; i < IdentityTypes.Count - 3; i++) { ProtocolClient cl = testIdentities[i]; await cl.ConnectAsync(ServerIp, ClCustomerPort, true); if (await cl.CheckInAsync()) { if (!await cl.InitializeProfileAsync(i.ToString(), null, new GpsLocation(1, 1), null)) { error = true; break; } } else { error = true; break; } cl.CloseConnection(); } bool profileInitOk = !error; await client.ConnectAsync(ServerIp, ClNonCustomerPort, true); Message requestMessage = mb.CreateProfileStatsRequest(); await client.SendMessageAsync(requestMessage); Message responseMessage = await client.ReceiveMessageAsync(); bool idOk = responseMessage.Id == requestMessage.Id; bool statusOk = responseMessage.Response.Status == Status.Ok; bool countOk = responseMessage.Response.SingleResponse.ProfileStats.Stats.Count == 5; List <ProfileStatsItem> controlList = new List <ProfileStatsItem>() { new ProfileStatsItem() { IdentityType = "Type A", Count = 2 }, new ProfileStatsItem() { IdentityType = "Type B", Count = 3 }, new ProfileStatsItem() { IdentityType = "Type Alpha", Count = 1 }, new ProfileStatsItem() { IdentityType = "Type A B", Count = 1 }, new ProfileStatsItem() { IdentityType = "Type Beta", Count = 1 }, }; foreach (ProfileStatsItem item in responseMessage.Response.SingleResponse.ProfileStats.Stats) { ProfileStatsItem controlItem = controlList.Find(i => (i.IdentityType == item.IdentityType) && (i.Count == item.Count)); if (!controlList.Remove(controlItem)) { error = true; break; } } bool contentOk = (controlList.Count == 0) && !error; // Step 1 Acceptance bool step1Ok = idOk && statusOk && hostingOk && profileInitOk && countOk && contentOk; log.Trace("Step 1: {0}", step1Ok ? "PASSED" : "FAILED"); // Step 2 log.Trace("Step 2"); for (int i = IdentityTypes.Count - 2; i < IdentityTypes.Count; i++) { ProtocolClient cl = testIdentities[i]; await cl.ConnectAsync(ServerIp, ClNonCustomerPort, true); if (!await cl.EstablishHostingAsync(IdentityTypes[i])) { error = true; break; } cl.CloseConnection(); } hostingOk = !error; error = false; for (int i = IdentityTypes.Count - 2; i < IdentityTypes.Count; i++) { ProtocolClient cl = testIdentities[i]; await cl.ConnectAsync(ServerIp, ClCustomerPort, true); if (await cl.CheckInAsync()) { if (!await cl.InitializeProfileAsync(i.ToString(), null, new GpsLocation(1, 1), null)) { error = true; break; } } else { error = true; break; } cl.CloseConnection(); } profileInitOk = !error; requestMessage = mb.CreateProfileStatsRequest(); await client.SendMessageAsync(requestMessage); responseMessage = await client.ReceiveMessageAsync(); idOk = responseMessage.Id == requestMessage.Id; statusOk = responseMessage.Response.Status == Status.Ok; countOk = responseMessage.Response.SingleResponse.ProfileStats.Stats.Count == 6; controlList = new List <ProfileStatsItem>() { new ProfileStatsItem() { IdentityType = "Type A", Count = 2 }, new ProfileStatsItem() { IdentityType = "Type B", Count = 3 }, new ProfileStatsItem() { IdentityType = "Type Alpha", Count = 1 }, new ProfileStatsItem() { IdentityType = "Type A B", Count = 2 }, new ProfileStatsItem() { IdentityType = "Type Beta", Count = 1 }, new ProfileStatsItem() { IdentityType = "Type C", Count = 1 }, }; foreach (ProfileStatsItem item in responseMessage.Response.SingleResponse.ProfileStats.Stats) { ProfileStatsItem controlItem = controlList.Find(i => (i.IdentityType == item.IdentityType) && (i.Count == item.Count)); if (!controlList.Remove(controlItem)) { error = true; break; } } contentOk = (controlList.Count == 0) && !error; // Step 2 Acceptance bool step2Ok = idOk && statusOk && hostingOk && profileInitOk && countOk && contentOk; log.Trace("Step 2: {0}", step1Ok ? "PASSED" : "FAILED"); Passed = step1Ok && step2Ok; res = true; } catch (Exception e) { log.Error("Exception occurred: {0}", e.ToString()); } foreach (ProtocolClient cl in testIdentities) { cl.Dispose(); } client.Dispose(); log.Trace("(-):{0}", res); return(res); }
static void Main(string[] args) { logger.Info("Program started"); try { Console.WriteLine("Would you like to view:"); Console.WriteLine("1) Categories"); Console.WriteLine("2) Products"); Console.WriteLine("(Select 1 or 2)"); string Selection = Console.ReadLine(); if (Selection == "1") { string choice; do { Console.WriteLine("1) Display Categories"); Console.WriteLine("2) Add Category"); Console.WriteLine("3) Display Category and related products"); Console.WriteLine("4) Display all Categories and their related products"); Console.WriteLine("5) Edit a Category"); Console.WriteLine("6) Delete a Category"); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); Console.Clear(); logger.Info($"Selection {choice} selected"); if (choice == "1") { var db = new NWConsole_96_EJBContext(); var query = db.Categories.OrderBy(p => p.CategoryName); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine($"{query.Count()} records returned"); Console.ForegroundColor = ConsoleColor.Magenta; foreach (var item in query) { Console.WriteLine($"{item.CategoryName} - {item.Description}"); } Console.ForegroundColor = ConsoleColor.White; } else if (choice == "2") { logger.Info("User choice: 2 - Enter new Category"); try { var db = new NWConsole_96_EJBContext(); bool nameChanged = true; Categories category = InputCategory(db); Categories validCategory = ValidateCategoryName(db, category, nameChanged); if (validCategory != null) { db.AddCategory(validCategory); logger.Info("Category added - {name}", validCategory.CategoryName); } } catch (Exception ex) { logger.Error(ex.Message); } } else if (choice == "3") { logger.Info("User choice: 3 - Display category and related products"); var db = new NWConsole_96_EJBContext(); var query = db.Categories.OrderBy(p => p.CategoryId); Console.WriteLine("Select the category to display related products"); Console.ForegroundColor = ConsoleColor.DarkRed; foreach (var item in query) { Console.WriteLine($"{item.CategoryId}) {item.CategoryName}"); } Console.ForegroundColor = ConsoleColor.White; int id = int.Parse(Console.ReadLine()); Console.Clear(); logger.Info($"CategoryId {id} selected"); Categories category = db.Categories.Include("Products").FirstOrDefault(c => c.CategoryId == id); Console.WriteLine($"{category.CategoryName} - {category.Description}"); if (category.Products.Count() != 0) { foreach (Products p in category.Products.Where(p => !p.Discontinued)) { Console.WriteLine(p.ProductName); } } else { Console.WriteLine("There are no products in this category."); } } else if (choice == "4") { logger.Info("User choice: 4 - Display all categories and related active products."); var db = new NWConsole_96_EJBContext(); var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId); foreach (var item in query) { Console.WriteLine($"{item.CategoryName}"); foreach (Products p in item.Products.Where(p => !p.Discontinued)) { Console.WriteLine($"\t{p.ProductName}"); } } } else if (choice == "5") { logger.Info("User choice: 5 - Edit Category"); Console.WriteLine("Choose the category to edit:"); var db = new NWConsole_96_EJBContext(); var category = GetCategory(db); if (category != null) { Categories UpdatedCategory = InputCategory(db); UpdatedCategory.CategoryId = category.CategoryId; bool editing = !category.CategoryName.Equals(UpdatedCategory.CategoryName); Categories ValidUpdatedCategory = ValidateCategoryName(db, UpdatedCategory, editing); if (ValidUpdatedCategory != null) { db.EditCategory(ValidUpdatedCategory); logger.Info($"Category (id: {category.CategoryId}) updated."); } } } else if (choice == "6") { logger.Info("User choice: 6 - Delete Category"); Console.WriteLine("Select the category to delete"); var db = new NWConsole_96_EJBContext(); var category = GetCategory(db); if (category != null) { var products = db.Products.Where(p => p.CategoryId == category.CategoryId); if (products.Count() == 0) { db.DeleteCategory(category); logger.Info($"Category (id: {category.CategoryId}) deleted."); } else { logger.Error("Cannot delete category with products in it. To delete the category, first remove any products."); } } } Console.WriteLine(); } while (choice.ToLower() != "q"); } else if (Selection == "2") { logger.Info("User choice: 2 - Products"); string choice; do { Console.WriteLine("1) Display Products: "); Console.WriteLine("2) Add Product: "); Console.WriteLine("3) Edit Product: "); Console.WriteLine("4) Delete Product: "); Console.WriteLine("\"q\" to quit"); choice = Console.ReadLine(); Console.Clear(); logger.Info($"Selection {choice} selected"); if (choice == "1") { logger.Info("User choice: 1 - Display Products"); var db = new NWConsole_96_EJBContext(); Console.WriteLine("1) Display Active Products: "); Console.WriteLine("2) Display Discontinued Products: "); Console.WriteLine("3) Display All Products: "); Console.WriteLine("4) Display Specific Product Information: "); string input = Console.ReadLine(); if (input == "1") { logger.Info("User choice: 1 - Display active products"); var activeQuery = db.Products.OrderBy(p => p.ProductName).Where(p => !p.Discontinued); Console.WriteLine($"Number of Active Products: {activeQuery.Count()}"); if (activeQuery.Count() != 0) { foreach (var product in activeQuery) { Console.WriteLine(product.ProductName); } Console.WriteLine(); } else { logger.Info("No active products"); Console.WriteLine("There are no active products"); } } else if (input == "2") { logger.Info("User choice: 2 - Display discontinued prodcuts"); var discontinuedQuery = db.Products.OrderBy(p => p.ProductName).Where(p => p.Discontinued); Console.WriteLine($"Number of Discontinued Products: {discontinuedQuery.Count()}"); Console.ForegroundColor = ConsoleColor.Red; if (discontinuedQuery.Count() != 0) { foreach (var product in discontinuedQuery) { Console.WriteLine(product.ProductName); } Console.WriteLine(); Console.ForegroundColor = ConsoleColor.White; } else { logger.Info("No discontinued products"); } } else if (input == "3") { logger.Info("User choice: 3 - Display all products"); var activeQuery = db.Products.OrderBy(p => p.ProductName).Where(p => !p.Discontinued); var discontinuedQuery = db.Products.OrderBy(p => p.ProductName).Where(p => p.Discontinued); Console.WriteLine("Active Products: "); foreach (var product in activeQuery) { Console.WriteLine($"\t{product.ProductName}"); } Console.WriteLine($"Total Active Products: {activeQuery.Count()}"); Console.WriteLine("Discontinued Products:"); foreach (var product in discontinuedQuery) { Console.WriteLine($"\t{product.ProductName}"); } Console.WriteLine($"Total Discontinued Products: {discontinuedQuery.Count()}"); } else if (input == "4") { logger.Info("User choice 4: Display specific product information"); Console.WriteLine("Select a product to display"); var product = GetProduct(db); if (product != null) { var isActive = product.Discontinued; string status; if (isActive) { status = "true"; } else { status = "false"; } Console.WriteLine($"Product Id: {product.ProductId}\nProduct name: {product.ProductName}\nSupplier Id: {product.SupplierId}\nCategory Id: {product.CategoryId}\nQuantity Per Unit: {product.QuantityPerUnit}\nUnit Price: {product.UnitPrice:C2}\nUnits in Stock: {product.UnitsInStock}\nUnits on Order: {product.UnitsOnOrder}\nReorder Level: {product.ReorderLevel}\nDiscontinued: {status}\n"); } else { logger.Error("No product"); } } else { logger.Error("Invalid Choice"); } } else if (choice == "2") { logger.Info("User choice: 2 - Add product"); try { var db = new NWConsole_96_EJBContext(); Products product = InputProduct(db); bool nameChanged = true; Products validProduct = ValidateProductName(db, product, nameChanged); if (validProduct != null) { db.AddProduct(validProduct); logger.Info("Product added - {name}", validProduct.ProductName); } } catch (Exception ex) { logger.Error(ex.Message); } } else if (choice == "3") { logger.Info("User choice: 3 - Edit product"); Console.WriteLine("Select a product to edit"); var db = new NWConsole_96_EJBContext(); var product = GetProduct(db); if (product != null) { Products UpdatedProduct = InputProduct(db); UpdatedProduct.ProductId = product.ProductId; bool nameChanged = !product.ProductName.Equals(UpdatedProduct.ProductName); Products ValidUpdatedProduct = ValidateProductName(db, UpdatedProduct, nameChanged); if (ValidUpdatedProduct != null) { db.EditProduct(ValidUpdatedProduct); logger.Info($"Product (id: {product.ProductId}) updated."); } } } else if (choice == "4") { logger.Info("User choice: 4 - Delete product"); Console.WriteLine("Select a product to delete"); var db = new NWConsole_96_EJBContext(); var product = GetProduct(db); if (product != null) { var orderDetails = db.OrderDetails.Where(o => o.ProductId == product.ProductId); if (orderDetails.Count() != 0) { logger.Error("Cannot delete product where order exists."); } else { db.DeleteProduct(product); logger.Info($"Product (id: {product.ProductId}) deleted."); } } } }while (choice.ToLower() != "q"); } } catch (Exception ex) { logger.Error(ex.Message); } logger.Info("Program ended"); }
public static ApiResponse GetAutostartState() { if (builder.Config.Tunable.UseLogonTask) { try { using Microsoft.Win32.TaskScheduler.Task logonTask = TaskSchdHandler.GetLogonTask(); if (logonTask != null) { ApiResponse response = new() { StatusCode = StatusCode.AutostartTask, Message = $"Enabled: {logonTask.Enabled}", Details = logonTask.Definition.Actions.ToString() }; return(response); } } catch (Exception ex) { string msg = "error while getting logon task state:"; Logger.Error(ex, msg); return(new() { StatusCode = StatusCode.Err, Message = msg, Details = $"Exception:\nMessage: {ex.Message}\nSource:{ex.Source}" }); } } else { string autostartPath = RegistryHandler.GetAutostartPath(); if (autostartPath != null) { bool approved = RegistryHandler.IsAutostartApproved(); if (approved) { return(new() { StatusCode = StatusCode.AutostartRegistryEntry, Message = $"Enabled", Details = autostartPath.Replace("\"", "") }); } else { return(new() { StatusCode = StatusCode.AutostartRegistryEntry, Message = $"Disabled", Details = autostartPath.Replace("\"", "") }); } } } return(new ApiResponse() { StatusCode = StatusCode.Disabled, Message = "no auto start entries found" }); }
private static void Main(string[] args) { Logger.Info($"TV Rename started with args: {string.Join(" ", args)}"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Check if an application instance is already running Mutex mutex = new Mutex(true, "TVRename", out bool newInstance); if (!newInstance) { // Already running Logger.Warn("An instance is alrady running"); // Create an IPC channel to the existing instance RemoteClient.Proxy(); // Transparent proxy to the existing instance RemoteClient ipc = new RemoteClient(); // If already running and no command line arguments then bring instance to the foreground and quit if (args.Length == 0) { ipc.FocusWindow(); return; } // Send command-line arguments to already running instance CommandLineArgs.MissingFolderBehavior previousMissingFolderBehavior = ipc.MissingFolderBehavior; bool previousRenameBehavior = ipc.RenameBehavior; // Parse command line arguments CommandLineArgs clargs = new CommandLineArgs(new ReadOnlyCollection <string>(args)); if (clargs.RenameCheck == false) { // Temporarily override behavior for renaming folders ipc.RenameBehavior = false; } if (clargs.MissingFolder != CommandLineArgs.MissingFolderBehavior.Ask) { // Temporarily override behavior for missing folders ipc.MissingFolderBehavior = clargs.MissingFolder; } // TODO: Unify command line handling between here and in UI.cs (ProcessArgs). Just send in clargs via IPC? // DoAll implies Scan if (clargs.DoAll || clargs.Scan) { ipc.Scan(); } if (clargs.DoAll) { ipc.ProcessAll(); } if (clargs.Quit) { ipc.Quit(); } // TODO: Necessary? ipc.RenameBehavior = previousRenameBehavior; ipc.MissingFolderBehavior = previousMissingFolderBehavior; return; } #if !DEBUG try { #endif Logger.Info("Starting new instance"); new ApplicationBase().Run(args); GC.KeepAlive(mutex); #if !DEBUG } catch (Exception ex) { Logger.Error(ex, "Application exiting with error"); new ShowException(ex).ShowDialog(); Environment.Exit(1); } #endif Logger.Info("Application exiting"); }
public static string ScrubMovies(string readFile) { try { // determine name of writeFile string ext = readFile.Split('.').Last(); string writeFile = readFile.Replace(ext, $"scrubbed.{ext}"); // if writeFile exists, the file has already been scrubbed if (File.Exists(writeFile)) { // file has already been scrubbed logger.Info("File already scrubbed"); } else { // file has not been scrubbed logger.Info("File scrub started"); // open write file StreamWriter sw = new StreamWriter(writeFile); // open read file StreamReader sr = new StreamReader(readFile); // remove first line - column headers sr.ReadLine(); while (!sr.EndOfStream) { // create instance of Movie class Movie movie = new Movie(); string line = sr.ReadLine(); // look for quote(") in string // this indicates a comma(,) or quote(") in movie title int idx = line.IndexOf('"'); string genres = ""; if (idx == -1) { // no quote = no comma or quote in movie title // movie details are separated with comma(,) string[] movieDetails = line.Split(','); movie.mediaId = UInt64.Parse(movieDetails[0]); movie.title = movieDetails[1]; genres = movieDetails[2]; movie.director = movieDetails.Length > 3 ? movieDetails[3] : "unassigned"; movie.runningTime = movieDetails.Length > 4 ? TimeSpan.Parse(movieDetails[4]) : new TimeSpan(0); } else { // quote = comma or quotes in movie title // extract the movieId movie.mediaId = UInt64.Parse(line.Substring(0, idx - 1)); // remove movieId and first comma from string line = line.Substring(idx); // find the last quote idx = line.LastIndexOf('"'); // extract title movie.title = line.Substring(0, idx + 1); // remove title and next comma from the string line = line.Substring(idx + 2); // split the remaining string based on commas string[] details = line.Split(','); // the first item in the array should be genres genres = details[0]; // if there is another item in the array it should be director movie.director = details.Length > 1 ? details[1] : "unassigned"; // if there is another item in the array it should be run time movie.runningTime = details.Length > 2 ? TimeSpan.Parse(details[2]) : new TimeSpan(0); } sw.WriteLine($"{movie.mediaId},{movie.title},{genres},{movie.director},{movie.runningTime}"); } sw.Close(); sr.Close(); logger.Info("File scrub ended"); } return(writeFile); } catch (Exception ex) { logger.Error(ex.Message); } return(""); }
public static ViewDeviceModel ViewDevice(string data, ProgressDialogController progressController) { ViewDeviceModel result = new ViewDeviceModel(); try { HtmlNode td; string text; //data = System.IO.File.ReadAllText("data"); HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); if (doc == null) { return(null); } doc.LoadHtml(data); if (doc.DocumentNode == null && doc.DocumentNode.ChildNodes == null) { return(null); } if (doc.DocumentNode.ChildNodes.Count > 1) { #region азбор секции с информацией о канале связи HtmlAgilityPack.HtmlNode jqTabsDevices = doc.DocumentNode.SelectNodes("//div[@id='jqTabsDevices']").Single(); if (jqTabsDevices == null) { return(null); } HtmlNodeCollection sessionInformation = jqTabsDevices.SelectNodes("div[2]/div/table/tbody/tr"); if (sessionInformation == null) { return(null); } result.Session = new SessionInformation(); // производитель модема td = sessionInformation[2].SelectNodes("td[2]").Single(); text = td.InnerText; result.Session.ModemManufacturer = text; // Модель устройства td = sessionInformation[3].SelectNodes("td[2]").Single(); text = td.InnerText; result.Session.Model = text; // описание td = sessionInformation[4].SelectNodes("td[2]").Single(); text = td.InnerText; result.Session.Description = text; // статус td = sessionInformation[6].SelectNodes("td[2]").Single(); text = td.InnerText; result.Session.CurrentStatus = text; // сеанс td = sessionInformation[7].SelectNodes("td[2]").Single(); text = td.InnerText; DateTime date = new DateTime(); result.Session.LastSessionDate = DateTime.TryParse(text, out date) ? date : date; #endregion #region азбор секции с показаниями HtmlAgilityPack.HtmlNode jqTabsBalances = doc.DocumentNode.SelectNodes("//div[@id='jqTabsBalances']").Single(); if (jqTabsBalances == null) { return(null); } HtmlNodeCollection counters = jqTabsBalances.SelectNodes("table/tbody/tr"); if (counters == null) { return(null); } result.CountersIndications = new List <IndicationViewItem>(); byte startIndex = 0; for (int i = 0; i < counters.Count; i++) { HtmlNodeCollection hnc = counters[i].SelectNodes("td"); startIndex = 0; IndicationViewItem ivi = new IndicationViewItem(); ivi.PreviousIndications = new Indications(); ivi.NextIndications = new Indications(); #region Парсинг // точка td = hnc[startIndex++]; text = td.InnerText; ivi.AccountingPoint = text; // тип td = hnc[startIndex++]; text = td.InnerText; ivi.CounterType = text; // предыдущие показания T0 td = hnc[startIndex++]; ivi.PreviousIndications.Tarriff0 = GetIndication(td.InnerText); // предыдущие показания T1 td = hnc[startIndex++]; ivi.PreviousIndications.Tarriff1 = GetIndication(td.InnerText); // предыдущие показания T2 td = hnc[startIndex++]; ivi.PreviousIndications.Tarriff2 = GetIndication(td.InnerText); // предыдущие показания T3 td = hnc[startIndex++]; ivi.PreviousIndications.Tarriff3 = GetIndication(td.InnerText); // предыдущие показания T4 td = hnc[startIndex++]; ivi.PreviousIndications.Tarriff4 = GetIndication(td.InnerText); // предыдущие показания достоверность td = hnc[startIndex++]; text = td.InnerText; ivi.PreviousIndications.DataReliability = text; // текущие показания T0 td = hnc[startIndex++]; ivi.NextIndications.Tarriff0 = GetIndication(td.InnerText); // текущие показания T1 td = hnc[startIndex++]; ivi.NextIndications.Tarriff1 = GetIndication(td.InnerText); // текущие показания T2 td = hnc[startIndex++]; ivi.NextIndications.Tarriff2 = GetIndication(td.InnerText); // текущие показания T3 td = hnc[startIndex++]; ivi.NextIndications.Tarriff3 = GetIndication(td.InnerText); // текущие показания T4 td = hnc[startIndex++]; ivi.NextIndications.Tarriff4 = GetIndication(td.InnerText); // предыдущие показания достоверность td = hnc[startIndex++]; text = td.InnerText; ivi.NextIndications.DataReliability = text; // разница td = hnc[startIndex++]; ivi.Difference = GetIndication(td.InnerText); #endregion result.CountersIndications.Add(ivi); } #endregion #region Качество показаний if (result.QualityIndications == null) { result.QualityIndications = new List <QualityIndications>(); } HtmlNodeCollection indicationsQualityMonths = doc.DocumentNode.SelectNodes("//table[contains(@class,'tableQualityIndications')]"); if (indicationsQualityMonths != null) { int monthsCount = indicationsQualityMonths.Count; for (int monthIndex = 0; monthIndex < monthsCount; monthIndex++) { QualityIndications qi = new QualityIndications(); HtmlNode m = indicationsQualityMonths[monthIndex].SelectNodes("thead/tr[1]/th[2]").Single(); qi.Period = m == null ? "???" : m.InnerText; qi.PointsData = ParseMonthQualityIndications(indicationsQualityMonths[monthIndex].SelectNodes("tbody/tr")); result.QualityIndications.Add(qi); } } #endregion } } catch (Exception ex) { //TODO: Добавить логирование _logger?.Error(ex); return(null); } return(result); }
/// <summary> /// 执行dotnet Command命令 /// </summary> /// <param name="projectPath"></param> /// <param name="fileName"></param> /// <param name="arguments"></param> /// <param name="logger"></param> /// <returns></returns> private static bool RunDotnetExternalExe(string projectPath, string fileName, string arguments, NLog.Logger logger) { Process process = null; try { try { logger.Info(fileName + " " + arguments); } catch (Exception) { } if (string.IsNullOrEmpty(arguments)) { throw new ArgumentException(nameof(arguments)); } //执行dotnet命令如果 projectdir路径含有空格 或者 outDir 路径含有空格 都是没有问题的 process = new Process(); process.StartInfo.WorkingDirectory = projectPath; process.StartInfo.FileName = fileName; process.StartInfo.Arguments = arguments; process.StartInfo.CreateNoWindow = true; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.UseShellExecute = false; process.StartInfo.Verb = "runas"; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; process.Start(); process.OutputDataReceived += (sender, args) => { if (!string.IsNullOrWhiteSpace(args.Data)) { if (!args.Data.StartsWith(" ") && args.Data.Contains(": error")) { logger?.Warn(args.Data); } else if (args.Data.Contains(".csproj : error")) { logger?.Error(args.Data); } else { logger?.Info(args.Data); } } }; process.BeginOutputReadLine(); process.ErrorDataReceived += (sender, data) => { if (!string.IsNullOrWhiteSpace(data.Data)) { logger?.Error(data.Data); } }; process.BeginErrorReadLine(); process.WaitForExit(); try { process.Kill(); } catch (Exception) { //ignore } return(process.ExitCode == 0); } catch (Exception ex) { logger?.Error(ex.Message); return(false); } finally { process?.Dispose(); } }
private void ParseFile() { XElement root = XElement.Load(FileName); //For all version of Vixen the Time, EventPeriod, EventValues and Audio are at the root level, //so just select them. SeqLengthInMills = Int32.Parse(root.Element("Time").Value); EventPeriod = Int32.Parse(root.Element("EventPeriodInMilliseconds").Value); EventData = Convert.FromBase64String(root.Element("EventValues").Value); //Someone may have decided to not use audio so we need to check for that as well. var songElement = root.Elements("Audio").SingleOrDefault(); if (songElement != null) { SongFileName = root.Element("Audio").Attribute("filename").Value; } //if the sequence is flattened then the profile element will not exists so lets check for it. var profileElement = root.Elements("Profile").SingleOrDefault(); if (profileElement != null) { ProfileName = root.Element("Profile").Value; } //If in a rare case a profile name is set AND we have channels, discard the profile name so the import will use the sequence channel data if (!String.IsNullOrEmpty(ProfileName) && root.Element("Channels").HasElements) { ProfileName = string.Empty; } foreach (XElement e in root.Elements("Channels").Elements("Channel")) { XAttribute nameAttrib = e.Attribute("name"); XAttribute colorAttrib = e.Attribute("color"); //This exists in the 2.5.x versions of Vixen //<Channel name="Mini Tree Red 1" color="-65536" output="0" id="5576725746726704001" enabled="True" /> if (nameAttrib != null) { CreateMappingList(e, 2); } //This exists in the older versions //<Channel color="-262330" output="0" id="633580705216250000" enabled="True">FenceIcicles-1</Channel> else if (colorAttrib != null) { CreateMappingList(e, 1); } } if (!String.IsNullOrEmpty(SongFileName)) { MessageBox.Show( string.Format("Audio File {0} is associated with this sequence, please select the location of the audio file.", SongFileName), "Select Audio Location", MessageBoxButtons.OK, MessageBoxIcon.Information); } var dialog = new OpenFileDialog { Multiselect = false, Title = string.Format("Open Vixen 2.x Audio [{0}]", SongFileName), Filter = "Audio|*.mp3|All Files (*.*)|*.*", RestoreDirectory = true, InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Vixen\Audio" }; using (dialog) { if (dialog.ShowDialog() == DialogResult.OK) { SongFileName = dialog.SafeFileName; SongPath = Path.GetDirectoryName(dialog.FileName); } } //check to see if the ProfileName is not null, if it isn't lets notify the user so they //can let us load the data if (!String.IsNullOrEmpty(ProfileName)) { MessageBox.Show( string.Format("Vixen {0}.pro is associated with this sequence, please select the location of the profile.", ProfileName), "Select Profile Location", MessageBoxButtons.OK, MessageBoxIcon.Information); dialog = new OpenFileDialog { Multiselect = false, Title = string.Format("Open Vixen 2.x Profile [{0}]", ProfileName), Filter = "Profile|*.pro", RestoreDirectory = true, InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Vixen\Profiles" }; using (dialog) { if (dialog.ShowDialog() == DialogResult.OK) { ProfilePath = Path.GetDirectoryName(dialog.FileName); ProfileName = dialog.SafeFileName; root = null; root = XElement.Load(dialog.FileName); foreach (XElement e in root.Elements("ChannelObjects").Elements("Channel")) { XAttribute nameAttrib = e.Attribute("name"); XAttribute colorAttrib = e.Attribute("color"); //This exists in the 2.5.x versions of Vixen //<Channel name="Mini Tree Red 1" color="-65536" output="0" id="5576725746726704001" enabled="True" /> if (nameAttrib != null) { CreateMappingList(e, 2); } //This exists in the older versions //<Channel color="-262330" output="0" id="633580705216250000" enabled="True">FenceIcicles-1</Channel> else if (colorAttrib != null) { CreateMappingList(e, 1); } } } } } else //if the profile name is null or empty then the sequence must have been flattened so indicate that. { ProfileName = "Sequence has been flattened no profile is available"; } // These calculations could have been put in the properties, but then it gets confusing to debug because of all the jumping around. TotalEventsCount = Convert.ToInt32(Math.Ceiling((double)(SeqLengthInMills / EventPeriod))); ; ElementCount = EventData.Length / TotalEventsCount; EventsPerElement = EventData.Length / ElementCount; // are we seeing an error in the mappings counts? if (mappings.Count != ElementCount) { Logging.Error("ParseFile: Actual mappings (" + mappings.Count + ") and calculated mappings (" + ElementCount + ") do not match. Using the Actual mappings value."); ElementCount = mappings.Count; } // end fix error in the V2 element reporting calculations } // ParseFile
/// <summary> /// Authenticating driver by login and password. /// </summary> /// <returns>authentication string or <c>null</c></returns> /// <param name="login">Login.</param> /// <param name="password">Password.</param> public string Auth(string login, string password) { #if DEBUG logger.Debug("Auth called with args:\nlogin: {0}\npassword: {1}", login, password); #endif try { using (IUnitOfWork uow = UnitOfWorkFactory.CreateWithoutRoot("[ADS]Авторизация пользователя")) { var employee = EmployeeRepository.GetDriverByAndroidLogin(uow, login); if (employee == null) { return(null); } //Generating hash from driver password var hash = (new SHA1Managed()).ComputeHash(Encoding.UTF8.GetBytes(employee.AndroidPassword)); var hashString = string.Join("", hash.Select(b => b.ToString("x2")).ToArray()); if (password == hashString) { //Creating session auth key if needed if (String.IsNullOrEmpty(employee.AndroidSessionKey)) { employee.AndroidSessionKey = Guid.NewGuid().ToString(); uow.Save(employee); uow.Commit(); } return(employee.AndroidSessionKey); } } } catch (Exception e) { logger.Error(e); } return(null); }
private void HandleException(Exception ex) { logger.Error(ex); }
public List <TorrentEntry> AllFilesBeingDownloaded() { List <TorrentEntry> r = new List <TorrentEntry>(); BEncodeLoader bel = new BEncodeLoader(); foreach (BTDictionaryItem dictitem in ResumeDat.GetDict().Items) { if ((dictitem.Type != BTChunk.kDictionaryItem)) { continue; } if ((dictitem.Key == ".fileguard") || (dictitem.Data.Type != BTChunk.kDictionary)) { continue; } if (dictitem.Data is BTError err) { logger.Error($"Error finding BT items: {err.Message}"); return(r); } BTDictionary d2 = (BTDictionary)(dictitem.Data); BTItem p = d2.GetItem("prio"); if ((p is null) || (p.Type != BTChunk.kString)) { continue; } BTString prioString = (BTString)(p); string directoryName = Path.GetDirectoryName(ResumeDatPath) + System.IO.Path.DirectorySeparatorChar; string torrentFile = dictitem.Key; if (!File.Exists(torrentFile)) // if the torrent file doesn't exist { torrentFile = directoryName + torrentFile; // ..try prepending the resume.dat folder's path to it. } if (!File.Exists(torrentFile)) { continue; // can't find it. give up! } BTFile tor = bel.Load(torrentFile); if (tor is null) { continue; } List <string> a = tor.AllFilesInTorrent(); if (a is null) { continue; } int c = 0; p = d2.GetItem("path"); if ((p is null) || (p.Type != BTChunk.kString)) { continue; } string defaultFolder = ((BTString)p).AsString(); BTItem targets = d2.GetItem("targets"); bool hasTargets = ((targets != null) && (targets.Type == BTChunk.kList)); BTList targetList = (BTList)(targets); foreach (string s in a) { if ((c < prioString.Data.Length) && (prioString.Data[c] != BTPrio.Skip)) { try { string saveTo = FileHelper .FileInFolder(defaultFolder, TVSettings.Instance.FilenameFriendly(s)).Name; if (hasTargets) { // see if there is a target for this (the c'th) file foreach (BTItem t in targetList.Items) { BTList l = (BTList)(t); BTInteger n = (BTInteger)(l.Items[0]); BTString dest = (BTString)(l.Items[1]); if (n.Value == c) { saveTo = dest.AsString(); break; } } } int percent = (a.Count == 1) ? PercentBitsOn((BTString)(d2.GetItem("have"))) : -1; TorrentEntry te = new TorrentEntry(torrentFile, saveTo, percent); r.Add(te); } catch (System.IO.PathTooLongException ptle) { //this is not the file we are looking for logger.Debug(ptle); } } c++; } } return(r); }
static void Main(string[] args) { logger.Info("Program started"); try { Location currentLocation = new Location { }; DateTime now = DateTime.Now; DateTime eventDate = now.AddMonths(-6); Random rnd = new Random(); var db = new EventContext(); while (eventDate < now) { int evtPerDay = rnd.Next(0, 6); for (int i = 0; i < evtPerDay; i++) { int hour = rnd.Next(0, 24); int min = rnd.Next(0, 60); int sec = rnd.Next(0, 60); int location = rnd.Next(1, 4); var locationQuery = db.Locations; foreach (var room in locationQuery) { if (location == room.LocationId) { currentLocation = room; } } DateTime currentDate = new DateTime(eventDate.Year, eventDate.Month, eventDate.Day, hour, min, sec); Event currentEvent = new Event { TimeStamp = currentDate, LocationId = location, Location = currentLocation, Flagged = false }; db.AddEvent(currentEvent); } eventDate = eventDate.AddDays(1); } db.SaveEvents(); logger.Info("Retrieving Event Data"); // Display all Events with Locations var query = db.Events.OrderBy(e => e.TimeStamp); Console.WriteLine("Event Activity\n//////////////////////////////////////////"); foreach (var item in query) { Console.WriteLine(item.TimeStamp + " - " + item.Location.Name); } } catch (Exception ex) { logger.Error(ex.Message + " " + ex.InnerException); } logger.Info("Program ended"); }
public Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken) { Logger.Error(context.Exception); return(Task.FromResult(0)); }
private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) { var exception = e.ExceptionObject as Exception; Logger.Error(exception, exception.Message); }
public Recorder(RecorderView view) { this.view = view; view.recorder = this; /////////// Setup logger /////////// logger = NLog.LogManager.GetCurrentClassLogger(); loggerWCF = NLog.LogManager.GetLogger("Capture.Recorder.WCF"); /////////// Setup WCF notification to a BriefMaker /////////// briefMakerClient = new BriefMakerServiceReference.BriefMakerClient(); /////////// Download Symbols /////////// try { logger.Debug("Downloading symbols"); var dbSymbols = from s in dc.Symbols select s; foreach (var s in dbSymbols) { if (String.IsNullOrWhiteSpace(s.Name)) { logger.Error("SymbolID:" + s.SymbolID + " does not have a name(symbol). Item will be skipped."); continue; } if (s.SymbolID > 255 || s.SymbolID < 0) { logger.Error("SymbolID:" + s.SymbolID + " range is not valid. Supported(0-255). Item will be skipped."); continue; } SecurityType secType = s.Type.Trim() == "STK" ? SecurityType.Stock : SecurityType.Index; string market = s.Market.Trim(); var new_symb = new MarketSymbol() { SymbolID = s.SymbolID, Symbol = s.Name.Trim(), securityType = s.Type.Trim() == "STK" ? SecurityType.Stock : SecurityType.Index, Market = s.Market }; symbols.Add(new_symb); } } catch (Exception ex) { logger.Error("Database Exception: " + ex.Message); logger.Error("Make sure that the connection string is set correctly in app.config."); Thread.Sleep(5000); ShutdownRecorder(); } // Setup BinaryWriters logger.Debug("Downloading symbols"); capturingWriter = new BinaryWriter(new MemoryStream(MemoryStreamReserveSpace)); capturingWriter.Write((long)0); // leave some space at the beginning for time later manufacturedWriterForFuture = new BinaryWriter(new MemoryStream(MemoryStreamReserveSpace)); manufacturedWriterForFuture.Write((long)0); // leave some space at the beginning for time later // Run this thread will a little higher priority since it is dealing with real-time information. Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; // Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; view.timer.Tick += new EventHandler(timer1Sec_Tick); while (true) { TimeSpan timespan = new TimeSpan(DateTime.Now.Ticks - lastRecievedUpdate.Ticks); if (timespan.Seconds > 30) { logger.Info("No Data received in over 30 seconds. Requesting Reconnect..."); lastRecievedUpdate = DateTime.Now; ConnectToIB(); } if (terminateRequested || (DateTime.Now.TimeOfDay > settings.ShutDownTime)) { logger.Info("Close requested or automatic end of day shutdown."); ShutdownRecorder(); break; } view.BeginInvoke((MethodInvoker)delegate { view.toolStripStatusLabelEventCt.Text = totalCaptureEventsForDisplay.ToString() + " (" + (totalCaptureEventsForDisplay - lastTotalCaptureEventsForDisplay).ToString() + "/sec)"; // runs on UI thread lastTotalCaptureEventsForDisplay = totalCaptureEventsForDisplay; view.toolStripStatusLabelLastBrfID.Text = lastUpdateTime.ToString(); }); // runs on UI thread Thread.Sleep(1000); } }
private async Task backUpTask() { try { logger.Info("Anhalten für Backup"); this.adminBot.stopListening(); this.feedbackBot.stopListening(); this.inputBot.stopListening(); this.moderateBot.stopListening(); this.publishBot.stopListening(); ManualResetEvent mre = new ManualResetEvent(false); SyncManager.halt(mre); if (!mre.WaitOne(TimeSpan.FromMinutes(3))) { logger.Error("Die Tasks sind nicht alle angehalten! Tasks: " + SyncManager.getRunningTaskCount()); } await this.backupData(); this.adminBot.restartListening(onAdminCallback, HandleErrorAsync); this.feedbackBot.restartListening(onFeedbackCallback, HandleErrorAsync); this.inputBot.restartListening(onInputBotCallback, HandleErrorAsync); this.moderateBot.restartListening(onModerateCallback, HandleErrorAsync); this.publishBot.restartListening(onPublishCallback, HandleErrorAsync); SyncManager.unhalt(); logger.Info("Backup erledigt, weitermachen"); this.statistics.setLastBackup(DateTime.Now); removeOldBackups(); } catch (Exception e) { logger.Error(e, "Fehler im Backup-Task"); } }
private static void SetRandoopBinariesVarsVS(Configuration config) { string dir = (config == Configuration.Debug ? "Debug" : "Release"); randoopExe = randoopHome + @"\Randoop\bin\" + dir + @"\Randoop.exe"; if (!File.Exists(randoopExe)) { Logger.Error("*** Error: randoop could not find file {0}.", randoopExe); System.Environment.Exit(1); } randoopBareExe = randoopHome + @"\RandoopBare\bin\" + dir + @"\RandoopBare.exe"; if (!File.Exists(randoopBareExe)) { Logger.Error("*** Error: randoop could not find file {0}.", randoopBareExe); System.Environment.Exit(1); } }
public void RunBots(bool interactive) { var templates = Config.ListAllBots().ToArray(); if (templates.Length == 0) { if (!interactive) { Log.Warn("No bots are configured in the load list."); return; } Log.Info("It seems like there are no bots configured."); Log.Info("Fill out this quick setup to get started."); var newBot = CreateNewBot(); string address; while (true) { Console.WriteLine("Please enter the ip, domain or nickname (with port; default: 9987) where to connect to:"); address = Console.ReadLine(); if (TS3Client.TsDnsResolver.TryResolve(address, out var _)) { break; } Console.WriteLine("The address seems invalid or could not be resolved, continue anyway? [y/N]"); var cont = Console.ReadLine(); if (string.Equals(cont, "y", StringComparison.InvariantCultureIgnoreCase)) { break; } } newBot.Connect.Address.Value = address; Console.WriteLine("Please enter the server password (or leave empty for none):"); newBot.Connect.ServerPassword.Password.Value = Console.ReadLine(); const string defaultBotName = "default"; if (!newBot.SaveNew(defaultBotName)) { Log.Error("Could not save new bot. Ensure that the bot has access to the directory."); return; } var botMetaConfig = Config.Bots.GetOrCreateItem(defaultBotName); botMetaConfig.Run.Value = true; if (!Config.Save()) { Log.Error("Could not save root config. The bot won't start by default."); } var runResult = RunBot(newBot); if (!runResult.Ok) { Log.Error("Could not run bot ({0})", runResult.Error); } return; } foreach (var template in Config.Bots.GetAllItems().Where(t => t.Run)) { var result = RunBotTemplate(template.Key); if (!result.Ok) { Log.Error("Could not instantiate bot: {0}", result.Error); } } }
protected override void ErrorInternal(string message, Exception error, KeyValuePair <string, object>[] extData = null) { _logger?.Error(error, buildString(error, message, extData)); }
public void addLog(string logLevel, string logMessage, Exception exception = null) { if (exception == null) { switch (logLevel) { case "info": nLog.Info(logMessage); break; case "warn": nLog.Warn(logMessage); break; case "debug": nLog.Debug(logMessage); break; case "error": nLog.Error(logMessage); break; case "fatal": nLog.Fatal(logMessage); break; default: nLog.Error(logMessage); break; } } else { switch (logLevel) { case "info": nLog.Info(exception, logMessage); break; case "warn": nLog.Warn(exception, logMessage); break; case "debug": nLog.Debug(exception, logMessage); break; case "error": nLog.Error(exception, logMessage); break; case "fatal": nLog.Fatal(exception, logMessage); break; default: nLog.Error(exception, logMessage); break; } } }
public static async Task RemoveGivenFilesAsync(IEnumerable <string> FileList, List <string> DirectoryList = null, Definitions.List.TaskInfo CurrentTask = null) { try { if (CurrentTask != null) { await Task.Delay(5000); } Parallel.ForEach(FileList, currentFile => { FileInfo File = new FileInfo(currentFile); if (File.Exists) { if (CurrentTask != null) { CurrentTask.TaskStatusInfo = Framework.StringFormat.Format(SLM.Translate(nameof(Properties.Resources.TaskStatus_DeletingFile)), new { FileName = File.Name, FormattedFileSize = FormatBytes(File.Length) }); } Alphaleonis.Win32.Filesystem.File.SetAttributes(File.FullName, FileAttributes.Normal); File.Delete(); } }); if (DirectoryList != null) { Parallel.ForEach(DirectoryList, currentDirectory => { DirectoryInfo Directory = new DirectoryInfo(currentDirectory); if (Directory.Exists) { if (CurrentTask != null) { CurrentTask.TaskStatusInfo = Framework.StringFormat.Format(SLM.Translate(nameof(Properties.Resources.TaskStatus_DeletingDirectory)), new { DirectoryName = Directory.Name }); } Directory.Delete(); } }); } if (CurrentTask != null) { CurrentTask.TaskStatusInfo = ""; } } catch (DirectoryNotFoundException ex) { logger.Error(ex); } catch (IOException ex) { logger.Error(ex); } catch (AggregateException ex) { logger.Error(ex); } catch (UnauthorizedAccessException ex) { logger.Error(ex); } catch (Exception ex) { logger.Fatal(ex); } }
public IActionResult WordCloud(WordCloudModel model) { if (!string.IsNullOrWhiteSpace(model.Text)) { try { string[] words = model.Text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); // اگر به جای لیست کلمات متن وارد کرده بود if (words.Length < 20 && words.Average(w => w.Length) > 20) { var model2 = new KeywordExtractionModel { MinWordLength = 3, MaxWordCount = 3, MinKeywordFrequency = 1, ResultKeywordCount = 500, Method = "FNG", Text = model.Text }; try { var apiOutput = CallApi($"{_urlPath}InformationRetrieval/KeywordExtraction", model2); if (apiOutput.Item2) { var viewModel = JsonConvert.DeserializeObject <Dictionary <string, double> >(apiOutput.Item1); words = viewModel.Keys.ToArray(); } } catch (Exception ex) { _logger.Error(ex); ShowError("خطا در استخراج کلمات کلیدی"); return(new EmptyResult()); } } string jsonStr = JsonConvert.SerializeObject(new { Words = words, model.Theme, //FontName = "Samim" } ); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GetJWTToken()); var response = client.PostAsync($"{_urlPath}InformationRetrieval/WordCloudGeneration", new StringContent(jsonStr, Encoding.UTF8, "application/json")).Result; var bytesArray = response.Content.ReadAsByteArrayAsync().Result; using (var ms = new MemoryStream(bytesArray)) { Image image = Image.FromStream(ms); string fileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".jpg"; image.Save(Path.Combine(_currentPath, "wordcloud", fileName)); return(PartialView("_WordCloudOutput", "~/wordcloud/" + fileName)); } } catch (Exception ex) { _logger.Error(ex); ShowError("خطا در ترسیم ابر کلمات"); } } return(new EmptyResult()); }
/// <summary> /// Looks for newer versions of the software than the currently known version. /// </summary> /// <returns>Returns an AvailableSoftware instance with the information /// that was retrieved from the net.</returns> public override AvailableSoftware searchForNewer() { logger.Debug("Searching for newer version of GIMP..."); string htmlCode = null; using (var client = new WebClient()) { try { htmlCode = client.DownloadString("https://www.gimp.org/downloads/"); } catch (Exception ex) { logger.Error("Exception occurred while checking for newer version of GIMP: " + ex.Message); return(null); } client.Dispose(); } // using const string stableRelease = "The current stable release of GIMP is"; int idx = htmlCode.IndexOf(stableRelease); if (idx < 0) { return(null); } htmlCode = htmlCode.Remove(0, idx); Regex reVersion = new Regex("[0-9]+\\.[0-9]+\\.[0-9]+"); Match matchVersion = reVersion.Match(htmlCode); if (!matchVersion.Success) { return(null); } string version = matchVersion.Value; // SHA-256 checksum is in a file like // https://download.gimp.org/pub/gimp/v2.8/windows/gimp-2.8.20-setup.exe.sha256 string shortVersion = string.Join(".", version.Split(new char[] { '.' }), 0, 2); htmlCode = null; using (var client = new WebClient()) { try { string sha256Url = "https://download.gimp.org/pub/gimp/v" + shortVersion + "/windows/gimp-" + version + "-setup.exe.sha256"; htmlCode = client.DownloadString(sha256Url); } catch (WebException webEx) { if ((webEx.Response is HttpWebResponse) && ((webEx.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound)) { // try SHA256 file for whole directory instead try { string sha256Url = "https://download.gimp.org/pub/gimp/v" + shortVersion + "/windows/SHA256SUMS"; htmlCode = client.DownloadString(sha256Url); } catch (Exception ex) { logger.Warn("Exception occurred while checking for newer version of GIMP: " + ex.Message); return(null); } // try-catch (inner) } // if 404 Not Found // Other web exceptions are still errors. else { logger.Warn("Exception occurred while checking for newer version of GIMP: " + webEx.Message); return(null); } } // catch WebException catch (Exception ex) { logger.Warn("Exception occurred while checking for newer version of GIMP: " + ex.Message); return(null); } client.Dispose(); } // using Regex reChecksum = new Regex("[0-9a-f]{64} gimp\\-" + Regex.Escape(version) + "\\-setup\\.exe"); Match m = reChecksum.Match(htmlCode); if (!m.Success) { return(null); } string checksum = m.Value.Substring(0, 64); // construct new information var newInfo = knownInfo(); string oldVersion = newInfo.newestVersion; string oldShortVersion = string.Join(".", oldVersion.Split(new char[] { '.' }), 0, 2); newInfo.newestVersion = version; // 32 bit newInfo.install32Bit.downloadUrl = newInfo.install32Bit.downloadUrl.Replace(oldVersion, version).Replace(oldShortVersion, shortVersion); newInfo.install32Bit.checksum = checksum; // 64 bit - same installer, same checksum newInfo.install64Bit.downloadUrl = newInfo.install32Bit.downloadUrl; newInfo.install64Bit.checksum = checksum; return(newInfo); }
public static void ErrorLog(Exception e, string msg) { logger.Error(e, msg); }