public static void InjectDependecies(IWebUIFactory webUIFactory, ITokenCachePlugin tokenCachePlugin, LoggerBase logger, PlatformInformationBase platformInformation, ICryptographyHelper cryptographyHelper, IDeviceAuthHelper deviceAuthHelper, IBrokerHelper brokerHelper, IPlatformParameters platformParameters) { WebUIFactory = webUIFactory; TokenCachePlugin = tokenCachePlugin; Logger = logger; PlatformInformation = platformInformation; CryptographyHelper = cryptographyHelper; DeviceAuthHelper = deviceAuthHelper; BrokerHelper = brokerHelper; DefaultPlatformParameters = platformParameters; }
public async Task <IActionResult> Login(LoginViewModel model) { var id = LoggerBase.ObtenerIdTransaccion(); try { var respuesta = await zohoApis.Login(model.Email, model.Password); HttpContext.Session.SetString("IdEstablecimiento", respuesta.vendorId); LoggerBase.WriteLog("LoginController", id, "Iniciosesion", respuesta, TypeError.Info); this.TempData["Mensaje"] = $"{Mensaje.MensajeSatisfactorio}|{"Bienvenido"}"; return(RedirectToAction("Index", "Home"));// RedirectToAction("Index", "Home"); } catch (Exception ex) { LoggerBase.WriteLog("LoginController", id, "Iniciosesion", ex, TypeError.Error); ModelState.AddModelError(string.Empty, ex.Message); return(View(model)); } }
public AspNetCoreMiddlewareTests(WebApplicationFactory <Startup> factory, ITestOutputHelper xUnitOutputHelper) : base(xUnitOutputHelper) { _logger = LoggerBase.Scoped(ThisClassName); _factory = factory; _agent = new ApmAgent(new TestAgentComponents( _logger, new MockConfigSnapshot(_logger, captureBody: ConfigConsts.SupportedValues.CaptureBodyAll), // _agent needs to share CurrentExecutionSegmentsContainer with Agent.Instance // because the sample application used by the tests (SampleAspNetCoreApp) uses Agent.Instance.Tracer.CurrentTransaction/CurrentSpan currentExecutionSegmentsContainer: Agent.Instance.TracerInternal.CurrentExecutionSegmentsContainer) ); ApmMiddlewareExtension.UpdateServiceInformation(_agent.Service); _capturedPayload = _agent.PayloadSender as MockPayloadSender; _client = Helper.GetClient(_agent, _factory); #if NETCOREAPP3_0 || NETCOREAPP3_1 _client.DefaultRequestVersion = new Version(2, 0); #endif }
public async Task <JsonResult> ProcesarPedidoEnvio(string id, string tipo) { var sesionExpirada = false; try { var usuario = HttpContext.Session.GetString("IdEstablecimiento"); LoggerBase.WriteLog("Home-ProcesarPedidoEnvio-POST", "Usuario", "IdEstablecimiento", usuario, TypeError.Info); if (string.IsNullOrEmpty(usuario)) { sesionExpirada = true; throw new Exception("IdEstablecimiento no encontrado"); } var pedido = new SolicitudProcesarPedido { Id = id, Proceso = tipo, }; var respuestaPedido = await zohoApis.ProcesarPedido(pedido); return(Json(new { estado = respuestaPedido, sesionExpirada, mensaje = string.Empty, })); } catch (Exception ex) { LoggerBase.WriteLog("Home-ProcesarPedidoEnvio", "Usuario", "ProcesarPedidoEnvio", ex.Message, TypeError.Error); return(Json(new { estado = false, sesionExpirada, lista = string.Empty, mensaje = ex.Message, })); } }
public async Task <JsonResult> PedidosHistoricos(DateTime fecha) { var sesionExpirada = false; try { var usuario = HttpContext.Session.GetString("IdEstablecimiento"); LoggerBase.WriteLog("Home-PedidosHistoricos-POST", "Usuario", "IdEstablecimiento", usuario, TypeError.Info); if (string.IsNullOrEmpty(usuario)) { sesionExpirada = true; throw new Exception("IdEstablecimiento no encontrado"); } var listaPedidosActuales = await zohoApis.ObtenerPedidos(usuario, fecha.Date); return(Json(new { estado = true, lista = listaPedidosActuales.Select(x => { x.date = $"{x.date:yyyy-MM-dd}"; x.valorEnvio = x.valorEnvio ?? 0.00; return x; }), sesionExpirada, mensaje = string.Empty, })); } catch (Exception ex) { LoggerBase.WriteLog("Home-PedidosActuales", "Usuario", "PedidosActuales", ex.Message, TypeError.Error); return(Json(new { estado = false, sesionExpirada, lista = string.Empty, mensaje = ex.Message, })); } }
private async Task <T> InterpretarRespuesta <T>(HttpResponseMessage httpResponse, string idLog) { try { var respuesta = await httpResponse.Content.ReadAsAsync <T>(); switch (httpResponse.StatusCode) { case HttpStatusCode.OK: LoggerBase.WriteLog(GetType().ToString(), $"{idLog} - RespuestaServicio: ({respuesta.Serializar()})", TypeError.Trace); return(respuesta); case HttpStatusCode.BadRequest: LoggerBase.WriteLog(GetType().ToString(), $"{idLog} - RespuestaServicio: ({respuesta.Serializar()})", TypeError.Error); return(respuesta); case HttpStatusCode.InternalServerError: LoggerBase.WriteLog(GetType().ToString(), $"{idLog} - Exception: ({respuesta.Serializar()})", TypeError.Error); throw new Exception("Error interno del servidor"); default: LoggerBase.WriteLog(GetType().ToString(), $"{idLog} - Exception: ({respuesta.Serializar()})", TypeError.Error); throw new Exception("No se puede obtener respuesta del servicio"); } } catch (Exception e) { LoggerBase.WriteLog(GetType().ToString(), $"{idLog} - Exception: ({e?.Message})", TypeError.Error); throw new Exception("Error interno del servidor"); } }
/// <summary> /// Loads Propeller settings from the appropriate location. Using this method ensures that settings are loaded in /// exactly the same way and from the same place as the Propeller engine would load them.</summary> /// <param name="settingsPath"> /// Path and filename of the settings to load.</param> /// <param name="log"> /// Information about how the settings were loaded is logged here. Must not be <c>null</c>.</param> /// <param name="firstRunEver"> /// Adjusts the log messages for improved human readability.</param> public static PropellerSettings LoadSettings(string settingsPath, LoggerBase log, bool firstRunEver) { settingsPath = settingsPath ?? SettingsUtil.GetAttribute <PropellerSettings>().GetFileName(); log.Info((firstRunEver ? "Loading settings file: " : "Reloading settings file: ") + settingsPath); PropellerSettings settings; var success = false; try { success = SettingsUtil.LoadSettings(out settings, settingsPath); if (success) { settings.SaveQuiet(settingsPath); return(settings); } } catch (Exception e) { settings = new PropellerSettings(); log.Error("Settings file could not be loaded: {0} ({1}). Using default settings.".Fmt(e.Message, e.GetType().FullName)); } if (!success) { if (!File.Exists(settingsPath)) { try { settings.Save(settingsPath); log.Info("Default settings saved to {0}.".Fmt(settingsPath)); } catch (Exception ex) { log.Warn("Attempt to save default settings to {0} failed: {1} ({2})".Fmt(settingsPath, ex.Message, ex.GetType().FullName)); } } } return(settings); }
public virtual bool CreateLogger() { List <LoggerBase> loggers = new List <LoggerBase>(); LoggerBase mainLogger = null; if (ExecuteType == ServerExecuteType.Service) { LoggerBase logger = new WindowEventLogger { ApplicationName = string.Format("{0} - {1}", ModuleName, Version) }; loggers.Add(logger); } else { LoggerBase logger = new ConsoleLogger(); loggers.Add(logger); mainLogger = logger; } Logger.Init(mainLogger, loggers); return(true); }
public async Task <JsonResult> ObtenerAnunciosPorVendedorAnuncios() { var sesionExpirada = false; try { var usuario = HttpContext.Session.GetString("IdEstablecimiento"); LoggerBase.WriteLog("Home-ObtenerAnunciosPorVendedorAnuncios-GET", "Usuario", "IdEstablecimiento", usuario, TypeError.Info); if (string.IsNullOrEmpty(usuario)) { sesionExpirada = true; throw new Exception("IdEstablecimiento no encontrado"); } var listaAnuncios = await zohoApis.ObtenerAnunciosPorVendedor(usuario); listaAnuncios = listaAnuncios.OrderByDescending(x => x.isActive).ThenByDescending(x => x.advertTime).ThenBy(x => x.advertType).ToList(); return(Json(new { estado = true, lista = listaAnuncios, sesionExpirada, mensaje = string.Empty, })); } catch (Exception ex) { LoggerBase.WriteLog("Home-ObtenerAnunciosPorVendedorAnuncios", "Usuario", "ObtenerAnunciosPorVendedorAnuncios", ex.Message, TypeError.Error); return(Json(new { estado = false, sesionExpirada, lista = string.Empty, mensaje = ex.Message, })); } }
public async Task <RespuestaDetallePedido> DetallePedido(string pedidoId) { var transaccion = LoggerBase.ObtenerIdTransaccion(); var nombreMetodo = "DetallePedido"; try { var request = $"{LoggerBase.urlBase}api/orders/GetOrder?Id={pedidoId}"; LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, null, TypeError.Info, request); var response = await _clienteZoho.GetAsync(request); var resultado = await response.Content.ReadAsStringAsync(); LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, resultado, TypeError.Info); var listaPedidos = JsonConvert.DeserializeObject <RespuestaDetallePedido>(resultado); return(listaPedidos); } catch (Exception ex) { LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, ex, TypeError.Error); throw new Exception(ex.Message); } }
public async Task <string> EditarProducto(ProductoViewModel producto) { var transaccion = LoggerBase.ObtenerIdTransaccion(); var nombreMetodo = "EditarProducto"; try { var request = JsonConvert.SerializeObject(producto); var content = new StringContent(request, Encoding.UTF8, "application/json"); LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, content, TypeError.Info, request); var response = await _clienteZoho.PostAsync($"{LoggerBase.urlBase}/api/vendor/PostItem", content); var resultado = await response.Content.ReadAsStringAsync(); LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, resultado, TypeError.Info); return(resultado); } catch (Exception ex) { LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, ex, TypeError.Error); throw new Exception(ex.Message); } }
internal ProviderSqlite(Configurations.DataSource config, LoggerBase logger) : base(config, logger) { if (_config == null) { return; } // assume the last path component is the filter _directorySourceFilter = Path.GetFileName(_config.Source); // if not, clear it if (!_directorySourceFilter.Contains("*")) { _directorySourceFilter = null; } // get the directory of the source // its either the source itself, or if the source is a file or a filter, the parent of the source-path _directorySource = _config.Source; if (!Directory.Exists(_directorySource)) { _directorySource = Path.GetDirectoryName(_directorySource); } }
public async Task <List <ProductoDto> > ObtenerProductosPorVendedor(string user) { var transaccion = LoggerBase.ObtenerIdTransaccion(); var nombreMetodo = "ObtenerProductosPorVendedor"; try { var request = $"{LoggerBase.urlBase}/api/vendor/GetItemsByVendor?vendorId={user}"; LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, null, TypeError.Info, request); var response = await _clienteZoho.GetAsync(request); var resultado = await response.Content.ReadAsStringAsync(); LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, resultado, TypeError.Info); var listaProducto = JsonConvert.DeserializeObject <List <ProductoDto> >(resultado); return(listaProducto); } catch (Exception ex) { LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, ex, TypeError.Error); throw new Exception(ex.Message); } }
public async Task <List <RespuestaPedidoActual> > ObtenerPedidos(string user, DateTime fecha) { var transaccion = LoggerBase.ObtenerIdTransaccion(); var nombreMetodo = "ObtenerPedidos"; try { var request = $"{LoggerBase.urlBase}api/orders/GetOrdersByVendor?vendorId={user}&date={fecha:yyyy-MM-dd}"; LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, null, TypeError.Info, request); var response = await _clienteZoho.GetAsync(request); var resultado = await response.Content.ReadAsStringAsync(); LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, resultado, TypeError.Info); var listaPedidos = JsonConvert.DeserializeObject <List <RespuestaPedidoActual> >(resultado); return(listaPedidos); } catch (Exception ex) { LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, ex, TypeError.Error); throw new Exception(ex.Message); } }
internal ProviderBase(DataSource config, LoggerBase logger) { _logger = logger; _logger.Log(config.Name, LoggerPriorities.Verbose, "Initializing"); if (string.IsNullOrEmpty(config.Source)) { _logger.Log(config.Name, LoggerPriorities.Error, "No source specified."); return; } _config = config; // get excluded databases if (!string.IsNullOrEmpty(_config.Exclude)) { _excluded = new List <string>(); foreach (var database in _config.Exclude.Split(',')) { _excluded.Add(database.Trim()); } } // get included databases if (!string.IsNullOrEmpty(_config.Include)) { _included = new List <string>(); foreach (var database in _config.Include.Split(',')) { _included.Add(database.Trim()); } } }
internal ProviderFtp(Configurations.DataTarget config, LoggerBase logger) : base(config, logger) { _connection = new Configuration(config.Target); // add path to host and ensure a trailing / _host = _connection.GetValue <string>("host"); if (!_host.EndsWith("/")) { _host += "/"; } var path = _connection.GetValue <string>("path"); if (path != null) { _host += path; if (!_host.EndsWith("/")) { _host += "/"; } } }
public async Task <bool> ProcesarAnuncio(SolicitudProcesarAnuncio anuncio) { var transaccion = LoggerBase.ObtenerIdTransaccion(); var nombreMetodo = "ProcesarAnuncio"; try { var request = JsonConvert.SerializeObject(anuncio); var content = new StringContent(request, Encoding.UTF8, "application/json"); LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, content, TypeError.Info, request); var response = await _clienteZoho.PostAsync($"{LoggerBase.urlBase}api/vendor/PostAdvert", content); var resultado = await response.Content.ReadAsStringAsync(); LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, resultado, TypeError.Info); var respuesta = JsonConvert.DeserializeObject <bool>(resultado); return(respuesta); } catch (Exception ex) { LoggerBase.WriteLog(nombreMetodo, transaccion, LoggerBase.urlBase, ex, TypeError.Error); throw new Exception(ex.Message); } }
/// <summary> /// Applies the database update, be that automatic or manual according to the configuration class. /// </summary> /// <param name="criteria"></param> public void UpdateDatabase(UpdateDatabaseCriteria criteria) { var status = GetMigrationConfigurationStatus(criteria.ProjectFilePath, criteria.RepoName); if (!status.Enabled) { LoggerBase.Log("Migrations are not enabled"); return; } switch (status.MigrationType) { case MigrationToUse.Automatic: UpdateDatabaseAutomatically(new AutomaticUpdateCriteria { ProjectFilePath = criteria.ProjectFilePath, RepoName = criteria.RepoName }); break; case MigrationToUse.Manual: ApplyMigrations(new ApplyMigrationCriteria { ProjectPath = criteria.ProjectFilePath, RepoName = criteria.RepoName }); break; default: throw new ArgumentOutOfRangeException(); } //clean up ProjectEvalutionHelper.FinishedWithProject(criteria.ProjectFilePath); }
public async Task <JsonResult> ProcesarAnuncio(SolicitudProcesarAnuncio anuncio) { var sesionExpirada = false; try { var usuario = HttpContext.Session.GetString("IdEstablecimiento"); LoggerBase.WriteLog("Home-ProcesarAnuncio-POST", "Usuario", "IdEstablecimiento", usuario, TypeError.Info); if (string.IsNullOrEmpty(usuario)) { sesionExpirada = true; throw new Exception("IdEstablecimiento no encontrado"); } anuncio.VendorId = usuario; anuncio.IsActive = true; var respuestaAnuncio = await zohoApis.ProcesarAnuncio(anuncio); return(Json(new { estado = respuestaAnuncio, sesionExpirada, mensaje = string.Empty, })); } catch (Exception ex) { LoggerBase.WriteLog("Home-ProcesarAnuncio", "Usuario", "ProcesarAnuncio", ex.Message, TypeError.Error); return(Json(new { estado = false, sesionExpirada, mensaje = ex.Message, })); } }
public override void Init(LoggerBase log) { #if DEBUG if (string.IsNullOrWhiteSpace(Settings.ConfigFile)) { var config = new KtaneWebConfig(); Console.WriteLine(); ConsoleUtil.WriteLine("It appears that you are running KtaneWeb for the first time.".Color(ConsoleColor.White)); tryAgain1: ConsoleUtil.WriteLine(@"Please provide a location for the JSON settings file (for example: {0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(@"C:\Path\KtaneWeb.settings.json")); var path = Console.ReadLine(); try { ClassifyJson.SerializeToFile(config, path); } catch (Exception e) { ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null); goto tryAgain1; } Console.WriteLine(); tryAgain2: ConsoleUtil.WriteLine("Do you already have a local clone of the KtaneContent repository that you want the website to use?".Color(ConsoleColor.White)); Console.WriteLine("If yes, please type the full path to that repository. If no, just press Enter."); var ktaneContent = Console.ReadLine(); var expectedSubfolders = "HTML,More,JSON,Icons".Split(','); if (string.IsNullOrWhiteSpace(ktaneContent)) { ConsoleUtil.WriteLine(@"In that case we will create a new clone. I can do that automatically if you have git installed (if you don’t, please abort now).".Color(ConsoleColor.White)); ConsoleUtil.WriteLine("This will take a long time as the repository is large.".Color(ConsoleColor.White)); Console.WriteLine(); tryAgain3: ConsoleUtil.WriteLine("Please choose a path where you would like all the data stored (for example: {0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(@"C:\Path\KtaneContent")); var cloneFolder = Console.ReadLine(); try { Directory.CreateDirectory(cloneFolder); } catch (Exception e) { ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null); goto tryAgain3; } try { config.BaseDir = Path.Combine(cloneFolder, "Public"); CommandRunner.Run("git", "clone", "https://github.com/Timwi/KtaneContent.git", config.BaseDir).Go(); config.MergedPdfsDir = Path.Combine(cloneFolder, "MergedPdfs"); Directory.CreateDirectory(config.MergedPdfsDir); config.LogfilesDir = Path.Combine(cloneFolder, "Logfiles"); Directory.CreateDirectory(config.LogfilesDir); } catch (Exception e) { ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null); goto tryAgain2; } } else if (expectedSubfolders.Any(s => !Directory.Exists(Path.Combine(ktaneContent, s)))) { ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {"That folder does not appear to contain KtaneContent.".Color(ConsoleColor.Red)}", null); ConsoleUtil.WriteLine("(We’re looking for a folder that contains subfolders named: {0/DarkMagenta})".Color(ConsoleColor.Magenta).Fmt(expectedSubfolders.JoinString(", "))); goto tryAgain2; } else { var p = ktaneContent; while (p.EndsWith("\"")) { p = Path.GetDirectoryName(p); } config.BaseDir = p; p = Path.GetDirectoryName(p); Console.WriteLine(); tryAgain4: var logfiles = Path.Combine(p, "Logfiles"); ConsoleUtil.WriteLine("Please choose a path where you would like KtaneWeb to store logfiles uploaded through the Logfile Analyzer, or just press Enter to use the default ({0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(logfiles)); config.LogfilesDir = Console.ReadLine(); if (string.IsNullOrWhiteSpace(config.LogfilesDir)) { ConsoleUtil.WriteLine("Using default: {0/DarkCyan}".Color(ConsoleColor.Gray).Fmt(logfiles)); config.LogfilesDir = logfiles; } try { Directory.CreateDirectory(config.LogfilesDir); } catch (Exception e) { ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null); goto tryAgain4; } Console.WriteLine(); tryAgain5: var mergedPdfs = Path.Combine(p, "MergedPdfs"); ConsoleUtil.WriteLine("Please choose a path where you would like KtaneWeb to store merged PDFs, or just press Enter to use the default ({0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(mergedPdfs)); config.MergedPdfsDir = Console.ReadLine(); if (string.IsNullOrWhiteSpace(config.MergedPdfsDir)) { ConsoleUtil.WriteLine("Using default: {0/DarkCyan}".Color(ConsoleColor.Gray).Fmt(mergedPdfs)); config.MergedPdfsDir = mergedPdfs; } try { Directory.CreateDirectory(config.MergedPdfsDir); } catch (Exception e) { ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null); goto tryAgain5; } var appPath = PathUtil.AppPathCombine(@"..\.."); config.JavaScriptFile = Path.Combine(appPath, @"Src\Resources\KtaneWeb.js"); config.CssFile = Path.Combine(appPath, @"Src\Resources\KtaneWeb.css"); if (!File.Exists(config.JavaScriptFile) || !File.Exists(config.CssFile)) { Console.WriteLine(); tryAgain6: ConsoleUtil.WriteLine("Finally, please let me know where you placed the KtaneWeb source code (what you’re running right now):".Color(ConsoleColor.Gray)); appPath = Console.ReadLine(); config.JavaScriptFile = Path.Combine(appPath, @"Src\Resources\KtaneWeb.js"); config.CssFile = Path.Combine(appPath, @"Src\Resources\KtaneWeb.css"); if (!File.Exists(config.JavaScriptFile) || !File.Exists(config.CssFile)) { ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {"That does not look like the KtaneWeb source code folder.".Color(ConsoleColor.Red)}", null); goto tryAgain6; } } } try { ClassifyJson.SerializeToFile(config, path); Settings.ConfigFile = path; SaveSettings(); } catch (Exception e) { ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null); goto tryAgain1; } Console.WriteLine(); ConsoleUtil.WriteLine("That should be all set up for you now!".Color(ConsoleColor.Green)); ConsoleUtil.WriteLine("Feel free to browse the settings file we just created if you’re curious.".Color(ConsoleColor.DarkGreen)); ConsoleUtil.WriteLine(@"For automatic PDF generation, we are assuming that Google Chrome is at its default location; if not, please change it manually in the JSON file.".Color(ConsoleColor.DarkGreen)); Console.WriteLine(); Console.WriteLine(); } #endif var original = File.ReadAllText(Settings.ConfigFile); _config = ClassifyJson.Deserialize <KtaneWebConfig>(JsonValue.Parse(original)); var rewrite = serializeConfig(); if (rewrite != original) { File.WriteAllText(Settings.ConfigFile, rewrite); } base.Init(log); _logger = log; }
public CreateProjectController(IProjectDataProvider dataProvider, LoggerBase logger) { _dataProvider = dataProvider; _logger = logger; }
public GetAllActivitiesController(IActivityDataProvider dataProvider, LoggerBase logger) { _dataProvider = dataProvider; _logger = logger; }
static Logger() { _loggerInstance = new FileLogger(); }
/// <summary> /// Tries to find the implementation of the base repo object from the given project. /// Will return NULL if more than one is found. The name can be passed in if the repo name is known, (required if multiple repos in same project). /// </summary> /// <param name="projectPath"></param> /// <param name="optionalRepoName"></param> /// <returns></returns> internal static RepoSearchResult FindSingleRepo(string projectPath, string optionalRepoName) { LoggerBase.Log(string.Format("Starting to find single Repo: '{0}, {1}", optionalRepoName, projectPath), isDebugMessage: true); var loadedProject = new ProjectEvalutionHelper().LoadEvalutionProject(projectPath); LoggerBase.Log("LoadedProject: " + loadedProject.FullName, isDebugMessage: true); var repoTypes = new Type[0]; try { repoTypes = loadedProject .GetTypes() .Where(t => t.IsSubclassOf(typeof(BaseRepo)) && !t.IsGenericType ) .ToArray(); } catch (ReflectionTypeLoadException ex) { LoggerBase.Log("Error whilst getting all classes that inherit from baserepo within loadedproject"); Exception[] loaderExceptions = ex.LoaderExceptions; LoggerBase.Log("Logger exceptions:", isDebugMessage: true); foreach (var exception in loaderExceptions) { LoggerBase.Log(exception, isDebugMessage: true); } LoggerBase.Log(ex, isDebugMessage: true); throw; } if (!string.IsNullOrWhiteSpace(optionalRepoName)) { var repos = repoTypes.Where(r => r.Name.Equals(optionalRepoName, StringComparison.InvariantCultureIgnoreCase)).ToArray(); if (!repos.Any()) { LoggerBase.Log("No repo class found with name: " + optionalRepoName); return(null); } if (repos.Count() > 1) { LoggerBase.Log("More than one repo with same name found, please ensure repo is uniquely named in repo project."); return(null); } return(new RepoSearchResult(loadedProject, repos.Single())); } if (!repoTypes.Any()) { LoggerBase.Log("No repo class found"); return(null); } if (repoTypes.Count() > 1) { LoggerBase.Log("More than one repo found, please specify which repo to use."); return(null); } return(new RepoSearchResult(loadedProject, repoTypes.Single())); }
private bool reinitialize() { // If we are already initialized and the settings file hasn’t changed, we don’t need to do anything. var firstRunEver = _server == null; if (_server != null && File.GetLastWriteTimeUtc(_settingsPath) <= _settingsLastChangedTime) { return(false); } // This may load *and re-write* the settings file... var newSettings = PropellerUtil.LoadSettings(_settingsPath, firstRunEver ? new ConsoleLogger() : _log, firstRunEver); // ... so remember the file date/time stamp *after* the writing _settingsLastChangedTime = File.GetLastWriteTimeUtc(_settingsPath); _log = PropellerUtil.GetLogger(true, newSettings.LogFile, newSettings.LogVerbosity); _log.Info(firstRunEver ? "Initializing Propeller" : "Reinitializing Propeller"); // If either port number or the bind-to address have changed, stop and restart the server’s listener. var startListening = false; if (_server == null || CurrentSettings == null || !CurrentSettings.ServerOptions.Endpoints.Values.SequenceEqual(newSettings.ServerOptions.Endpoints.Values)) { var removed = CurrentSettings == null ? new HttpEndpoint[0] : CurrentSettings.ServerOptions.Endpoints.Values.Except(newSettings.ServerOptions.Endpoints.Values).ToArray(); var added = CurrentSettings == null?newSettings.ServerOptions.Endpoints.Values.ToArray() : newSettings.ServerOptions.Endpoints.Values.Except(CurrentSettings.ServerOptions.Endpoints.Values).ToArray(); if (_server == null || removed.Length > 0 || added.Length > 0) { if (removed.Length > 0) { _log.Info("Disabling {0}".Fmt(removed.Select(ep => "HTTP{0} on port {1}".Fmt(ep.Secure ? "S" : null, ep.Port)).JoinString(", ", lastSeparator: " and "))); } if (added.Length > 0) { _log.Info("Enabling {0}".Fmt(added.Select(ep => "HTTP{0} on port {1}".Fmt(ep.Secure ? "S" : null, ep.Port)).JoinString(", ", lastSeparator: " and "))); } if (_server == null) { _server = new HttpServer { Options = newSettings.ServerOptions, ErrorHandler = errorHandler, ResponseExceptionHandler = responseExceptionHandler } } ; else { _server.StopListening(); } startListening = true; } } CurrentSettings = newSettings; // Create a new instance of all the modules var newAppDomains = new HashSet <AppDomainInfo>(); foreach (var module in newSettings.Modules) { _log.Info("Initializing module: " + module.ModuleName); try { var inf = new AppDomainInfo(_log, newSettings, module, new SettingsSaver(s => { module.Settings = s; _settingsSavedByModule = true; })); newAppDomains.Add(inf); } catch (Exception e) { _log.Error("Failed to initialize module {0}:".Fmt(module.ModuleName)); _log.Exception(e); } } // Switcheroo! lock (_lockObject) { _log.Info("AppDomain Switcheroo"); _inactiveAppDomains.AddRange(_activeAppDomains); _activeAppDomains = newAppDomains; _server.Options = newSettings.ServerOptions; _server.Handler = createResolver().Handle; _server.Log = PropellerUtil.GetLogger(newSettings.HttpAccessLogToConsole, newSettings.HttpAccessLogFile, newSettings.HttpAccessLogVerbosity); if (startListening) { _server.StartListening(); } } // Delete any remaining temp folders no longer in use HashSet <string> tempFoldersInUse; lock (_lockObject) tempFoldersInUse = _activeAppDomains.Concat(_inactiveAppDomains).Select(ad => ad.TempPathUsed).ToHashSet(); foreach (var tempFolder in Directory.EnumerateDirectories(CurrentSettings.TempFolder ?? Path.GetTempPath(), "propeller-tmp-*")) { if (tempFoldersInUse.Contains(tempFolder)) { continue; } try { Directory.Delete(tempFolder, recursive: true); } catch { } } return(true); }
public MetricsTests(ITestOutputHelper xUnitOutputHelper) : base(xUnitOutputHelper) { _output = xUnitOutputHelper; _logger = LoggerBase.Scoped(ThisClassName); }
public ProviderFile(Configurations.DataSource config, LoggerBase logger) : base(config, logger) { }
internal ProviderDropbox(Configurations.DataTarget config, LoggerBase logger) : base(config, logger) { // parse config // we assume the target is the token var token = _config.Target; // check for optional path var args = token.Split(';'); foreach (var arg in args) { var keyValue = arg.Split('='); if (keyValue.Length == 2) { switch (keyValue[0].Trim().ToLower()) { case "token": token = keyValue[1].Trim(); break; case "path": _path = keyValue[1].Trim(); break; } } } if (string.IsNullOrEmpty(token)) { _logger.Log(_config.Name, LoggerPriorities.Error, "Token is missing."); return; } // format path if (_path == null) { _path = string.Empty; } if (!_path.StartsWith("/")) { _path = "/" + _path; } if (!_path.EndsWith("/")) { _path += "/"; } // init client DropboxCertHelper.InitializeCertPinning(); _requestHandler = new WebRequestHandler { ReadWriteTimeout = 10 * 1000 }; // Specify socket level timeout which decides maximum waiting time when no bytes are // received by the socket. _httpClient = new HttpClient(_requestHandler) { // Specify request level timeout which decides maximum time that can be spent on // download/upload files. Timeout = TimeSpan.FromMinutes(20) }; var clientConfig = new DropboxClientConfig(_config.Name) { HttpClient = _httpClient }; _client = new DropboxClient(token, clientConfig); }
public DistributionService(LocalHostConfigBase localHostConfig, HttpClient client, LoggerBase logger) { this._config = localHostConfig.Config; this._client = client; this._logger = logger.Logger; }
public DocumentationLogger(LoggerBase loggerBaseImplementation) { this.loggerBaseImplementation = loggerBaseImplementation; }
public void File(string message, LoggerBase.Severity severity) { throw new NotImplementedException(); }
/// <summary> /// Default constructor, initializes the logger /// </summary> public LoggingController() : base() { Logger = LoggerFactory.GetLogger(this); }
public GetAllProjectsController(IProjectDataProvider dataProvider, LoggerBase logger) { _dataProvider = dataProvider; _logger = logger; }