/// <summary> /// Starts the request dispatcher. /// </summary> /// <param name="relayNamespace">The ServiceBus namespace that hosts this Relay. E.g. BCDemoAgent.servicebus.windows.net</param> /// <param name="hybridConnectionName"></param> /// <param name="keyName">The name of your Shared Access Policies key, which is RootManageSharedAccessKey by default</param> /// <param name="sharedAccessKey"></param> /// <param name="pluginFolder"></param> /// <param name="logger">Logger implementation</param> /// <param name="cancellationToken">Cancellation Tokan</param> public static async void Start( string relayNamespace, string hybridConnectionName, string keyName, string sharedAccessKey, string pluginFolder, ILogger logger, CancellationToken cancellationToken ) { logger?.LogMessage(LogLevel.Verbose, $"Loading plugins from: {pluginFolder}"); CompositionContext compositionContext = CompositionHelper.CreateCompositionHost(pluginFolder); ImmutableDictionary <string, AgentPlugin> plugins = compositionContext.TryGetExports <IAgentPlugin, AgentPluginMetadata>() .Select(exp => AgentPlugin.Create(exp.Metadata, exp.Value, logger)) .Where(p => p != null) .ToImmutableDictionary(p => p.RootPath); if (plugins.IsEmpty) { logger?.LogMessage(LogLevel.Error, $"No valid plugins. Exiting..."); return; } HybridConnectionListener listener = CreateHybridConnectionListener(relayNamespace, hybridConnectionName, keyName, sharedAccessKey, logger); await new RequestDispatcher(listener, plugins, logger).RunAsync(cancellationToken); }
public void Check(string url, ILogger logger) { using (var ping = new Ping()) { PingReply pingReply = null; try { pingReply = ping.Send(url); } catch (PingException ex) { logger.LogMessage(String.Format("Ping error: {0}", ex.Message)); return; } var result = String.Empty; switch (pingReply.Status) { case IPStatus.Success: result = "Available"; break; case IPStatus.TimedOut: result = "NotAvailable"; break; default: result = String.Format("Ping failed: {0}", pingReply.Status.ToString()); break; } logger.LogMessage(result); } }
public DependencyAnalyzerResult Analyze(ILogger logger) { var result = new DependencyAnalyzerResult(); result.AnalyzedFiles = GetLibrariesAndExecutables().ToArray(); if (result.AnalyzedFiles.Length <= 0) { return result; } result.Assemblies = new Dictionary<string, AssemblyReferenceInfo>(StringComparer.OrdinalIgnoreCase); foreach (var fileInfo in result.AnalyzedFiles.OrderBy(asm => asm.Name)) { logger.LogMessage(string.Format("Checking file {0}", fileInfo.Name)); Assembly assembly; try { if (!fileInfo.IsAssembly()) { continue; } assembly = Assembly.ReflectionOnlyLoadFrom(fileInfo.FullName); } catch (Exception ex) { logger.LogWarning(string.Format("Failed to load assembly '{0}': {1}", fileInfo.FullName, ex.Message)); continue; } var assemblyReferenceInfo = GetAssemblyReferenceInfo(result.Assemblies, assembly.GetName()); assemblyReferenceInfo.ReflectionOnlyAssembly = assembly; assemblyReferenceInfo.AssemblySource = AssemblySource.Local; foreach (var referencedAssembly in assembly.GetReferencedAssemblies()) { var referencedAssemblyReferenceInfo = GetAssemblyReferenceInfo(result.Assemblies, referencedAssembly); ; assemblyReferenceInfo.AddReference(referencedAssemblyReferenceInfo); referencedAssemblyReferenceInfo.AddReferencedBy(assemblyReferenceInfo); } } foreach (var assembly in result.Assemblies.Values) { if (assembly.ReflectionOnlyAssembly != null) { continue; } logger.LogMessage(string.Format("Checking reference {0}", assembly.AssemblyName.Name)); try { assembly.ReflectionOnlyAssembly = Assembly.ReflectionOnlyLoad(assembly.AssemblyName.FullName); assembly.AssemblySource = assembly.ReflectionOnlyAssembly.GlobalAssemblyCache ? AssemblySource.GAC : AssemblySource.Unknown; } catch (Exception ex) { // TODO: Show message? } } return result; }
/// <summary> /// Creates new instance of <see cref="PlaybackManager"/> /// </summary> /// <param name="logger"><see cref="ILogger"/> instance</param> /// <param name="applicationSettingsHelper"><see cref="IApplicationSettingsHelper"/> instance</param> public PlaybackManager(ILogger logger, IApplicationSettingsHelper applicationSettingsHelper) { backgroundAudioInitializedEvent = new AutoResetEvent(false); this.logger = logger; this.applicationSettingsHelper = applicationSettingsHelper; // Ensure that Background Audio is initialized by accessing BackgroundMediaPlayer.Current var state = MediaPlayer.CurrentState; logger.LogMessage($"Foreground playback manager: Current media player state is {state}.", LoggingLevel.Information); BackgroundMediaPlayer.MessageReceivedFromBackground += onMessageReceivedFromBackground; logger.LogMessage("Foreground playback manager initialized.", LoggingLevel.Information); }
/// <summary> /// Creates new instance of <see cref="AudioManager"/> /// </summary> /// <param name="logger">The logger instance</param> /// <param name="applicationSettingsHelper">The application settings helper instance</param> /// <param name="smtc">Instance of <see cref="SystemMediaTransportControls"/></param> public AudioManager( ILogger logger, IApplicationSettingsHelper applicationSettingsHelper, SystemMediaTransportControls smtc) { this.logger = logger; this.applicationSettingsHelper = applicationSettingsHelper; this.smtc = smtc; logger.LogMessage("Initializing Background Audio Manager..."); setupSmtc(); subscribeToMediaEvents(); playlistLoading = new TaskCompletionSource<bool>(); playlistLoading.SetResult(true); logger.LogMessage("BackgroundAudio: Background Audio Manager has been initialized.", LoggingLevel.Information); }
public void Kill(ILogger logger) { logger.LogMessage(string.Format("Killing device: {0}", FullName())); TcpClient client = new TcpClient("localhost", Port); using (var stream = client.GetStream()) { byte[] results = new byte[100]; var readCount = stream.Read(results, 0, 100); var resultText = Encoding.ASCII.GetString(results, 0, readCount); logger.LogMessage("Connected to device console."); logger.LogMessage(resultText); logger.LogMessage("Sending kill command."); var command = Encoding.ASCII.GetBytes("kill" + Environment.NewLine); stream.Write(command, 0, command.Length); stream.Flush(); readCount = stream.Read(results, 0, 100); resultText = Encoding.ASCII.GetString(results, 0, readCount); logger.LogMessage(resultText); if (string.IsNullOrWhiteSpace(resultText) || !resultText.Contains("OK")) { throw new Exception(string.Format("Unable to kill emulator. Expected OK Response from kill command, but was: {0}", resultText)); } logger.LogMessage("Emulated device killed."); TimeSpan timeout = new TimeSpan(0, 0, 30); stream.Close((int)timeout.TotalMilliseconds); } client.Close(); }
public async void Run(IBackgroundTaskInstance taskInstance) { deferral = taskInstance.GetDeferral(); Services.IoC.Register(); var container = Container.Instance; logger = container.Resolve<ILogger>(); taskInstance.Task.Completed += onTaskCompleted; taskInstance.Canceled += onTaskCanceled; logger.LogMessage("BackgroundUpdater: Task initialized.", LoggingLevel.Information); var episodeListManager = container.Resolve<IEpisodeListManager>(); await episodeListManager.Initialization; var oldEpisodeList = EpisodeList.Instance.ToList(); await episodeListManager.LoadEpisodeListFromServerAsync(); var diff = EpisodeList.Instance.Except(oldEpisodeList).ToList(); if (diff.Any()) { var downloadManager = container.Resolve<IDownloadManager>(); await downloadManager.Initialization; foreach (var episode in diff) { await downloadManager.DownloadEpisode(episode); } } deferral.Complete(); }
public RlmFileRepository() { string environmentVariableName = "LocalAppData"; if (Environment.OSVersion.Platform == PlatformID.Unix) { _logger?.LogMessage(this, "Platform is Unix"); environmentVariableName = "HOME"; } string rootPath = Environment.GetEnvironmentVariable(environmentVariableName); _logger?.LogMessage(this, $"RlmFileRepository: Using environment variable {environmentVariableName}: {rootPath}"); CreateTournamentsDirectory(rootPath); }
public SecondWindow(ILogger someLogger = null) { InitializeComponent(); myLogger = someLogger; myLogger?.LogMessage("Second Window was created! "); }
private void Button_Click(object sender, RoutedEventArgs e) { try { int getal1 = int.Parse(txtGetal1.Text); int getal2 = int.Parse(txtGetal2.Text); int antwoord = getal1 / getal2; MessageBox.Show($"Het antwoord is {antwoord}."); } catch (Exception ex) { // Hier log ik een message. De logger kan null zijn daarom de ?. myLogger?.LogMessage(ex.Message); } }
/// <summary> /// Run the Abathur framework with the settings specified in the data directory. /// </summary> /// <param name="dataPath">The absolute path for a directory where Abathur may place setting files</param> /// <param name="logPath">The absolute directory path for log files, no log files will be generated if left empty</param> public void Run(string dataPath, string logPath = null) { // ConsoleLogger prints in pretty colors... ILogger log = ConsoleLogger.Instance; // Check that the directory exist, or create it. log?.LogMessage("Checking data directory:"); FileService.ValidateOrCreateDirectory(dataPath, log); // Check that the game settings file exist, or create it a default template. log?.LogMessage("Checking game settings file:"); FileService.ValidateOrCreateJsonFile(dataPath + "gamesettings.json", Defaults.GameSettings, log); GameSettings gameSettings = FileService.ReadFromJson <GameSettings>(dataPath + "gamesettings.json", log); // Load the Abathur setup file, this file is used to add/remove modules to the framework log?.LogMessage("Checking setup file:"); FileService.ValidateOrCreateJsonFile(dataPath + "setup.json", Defaults.AbathurSetup, log); AbathurSetup abathurSetup = FileService.ReadFromJson <AbathurSetup>(dataPath + "setup.json", log); // Load or create the 'essence file' - a file containing UnitTypeData, AbilityTypeData, BuffData, UpgradeData and manually coded tech-trees for each race. var essence = EssenceService.LoadOrCreate(dataPath, log); // If a log path have been specified, check the directory and change add a filelogger (writes to files) if (logPath != null) { log?.LogMessage("Checking log directory:"); FileService.ValidateOrCreateDirectory(logPath, log); log = new MultiLogger(ConsoleLogger.Instance, new FileLogger(logPath, "abathur")); } // Check if gamesettings specify more than one participant (1 = Participant, 2 = Computer, 3 = Observer (not implemented)) IClient player1 = null; IClient player2 = null; player1 = new AbathurClient(abathurSetup, gameSettings, essence, log); if (gameSettings.IsMultiplayer()) { player2 = new AbathurClient(abathurSetup, gameSettings, essence, log); } // Start the game already! var game = new Game(gameSettings, player1, player2); game.ExecuteMatch(); }
public static void Monitor(string portName, int baudRate, int tournamentID, int raceNum, bool simulate = false) { if (_random == null) { _random = new Random(); } if (!simulate) { // Open the serial port _logger?.LogMessage($"Opening serial port {portName}"); _serialPort = new SerialPort(portName, baudRate); _serialPort.ReadTimeout = 100; _serialPort.Open(); } // Start the monitor thread _stopMonitoring = false; if (simulate) { _monitorThread = new Thread(() => SimulateRace(tournamentID, raceNum)); } else { _monitorThread = new Thread(() => MonitorFunction(_serialPort, tournamentID, raceNum)); } _monitorThread.Start(); }
public void Check(String url, ILogger logger) { var request = HttpWebRequest.Create(url); try { using (var response = (HttpWebResponse)request.GetResponse()) { if (response != null || response.StatusCode == HttpStatusCode.OK) logger.LogMessage("Available"); else logger.LogMessage("NotAvailable"); } } catch { logger.LogMessage("Web request error"); } }
private static HybridConnectionListener CreateHybridConnectionListener(string relayNamespace, string hybridConnectionName, string keyName, string sharedAccessKey, ILogger logger) { Uri address = new Uri($"sb://{relayNamespace}/{hybridConnectionName}"); logger?.LogMessage(LogLevel.Verbose, $"Connection to: {address}"); TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, sharedAccessKey); return(new HybridConnectionListener(address, tokenProvider)); }
/// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { IoC.Register(); InitializeComponent(); UnhandledException -= onUnhandledException; UnhandledException += onUnhandledException; logger = container.Resolve<ILogger>(); logger.LogMessage("Application initialized."); }
/// <summary> /// Creates instance of <see cref="Loader"/> /// </summary> /// <param name="logger">The logger instance</param> /// <param name="parser">The <see cref="IParser"/> instance</param> public Loader(ILogger logger, IParser parser) { this.parser = parser; this.logger = logger; httpClient = new HttpClient(); httpClient.Timeout = TimeSpan.FromSeconds(connectionTimeoutSeconds); logger.LogMessage("Loader initialized.", LoggingLevel.Information); }
private int Build(ILogger logger, string projectPath, string configuration, NuGetFramework frameworkToUse, string buildBasePath) { logger.LogMessage(Resources.BuildingProject); var buildResult = DotNetBuildCommandHelper.Build( projectPath, configuration, frameworkToUse, buildBasePath); if (buildResult.Result.ExitCode != 0) { //Build failed. // Stop the process here. logger.LogMessage(Resources.BuildFailed); logger.LogMessage(string.Join(Environment.NewLine, buildResult.StdOut), LogMessageLevel.Error); logger.LogMessage(string.Join(Environment.NewLine, buildResult.StdErr), LogMessageLevel.Error); } return(buildResult.Result.ExitCode); }
public void Commit(ChangeScript[] scripts) { _logger.LogMessage("Starting to commit the changes directly to SQL Server."); using (SqlConnection connection = new SqlConnection(this.ConnectionString)) { connection.Open(); StringBuilder builder = new StringBuilder(); ScriptType[] scriptTypeOrder = new ScriptType[] { ScriptType.Schema, ScriptType.Table, ScriptType.View, ScriptType.Trigger }; foreach (var scriptType in scriptTypeOrder) { //Tables first foreach (var script in scripts.Where(s => s.ScriptType == scriptType)) { builder.AppendLine(script.ScriptText); } } //Other types foreach (var script in scripts.Where(s => !scriptTypeOrder.Contains(s.ScriptType))) { builder.AppendLine(script.ScriptText); } Server server = new Server(new ServerConnection(connection)); try { server.ConnectionContext.BeginTransaction(); server.ConnectionContext.ExecuteNonQuery(builder.ToString()); server.ConnectionContext.CommitTransaction(); } catch { _logger.LogMessage("Transaction rolled back due to exception."); server.ConnectionContext.RollBackTransaction(); throw; } } _logger.LogMessage("Changes have been committed."); }
/// <summary> /// Executes the specified operation with the specified retry policy. /// </summary> /// <typeparam name="T">Returns an arbitrary type.</typeparam> /// <param name="function">The function to execute.</param> /// <param name="policy">The retry policy to apply to the function.</param> /// <param name="context">The abstraction context to use.</param> /// <param name="logger">An ILogger object to log retry attempts.</param> /// <returns> /// Returns the value received from the execution of the function. /// </returns> public static async Task <OperationExecutionResult <T> > ExecuteOperationWithRetry <T>(Func <Task <T> > function, IRetryPolicy policy, IAbstractionContext context, ILogger logger) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int attempt = 0; attempt < policy.MaxAttemptCount;) { try { if (attempt > 0) { logger.LogMessage(string.Format(CultureInfo.InvariantCulture, "\r\nRetrying Operation because previous attempt resulted in error. Current Retry attempt: {0}\r\n\r\n", attempt), Severity.Informational, Verbosity.Detailed); } context.CancellationToken.ThrowIfCancellationRequested(); T result = await function(); attempt++; return(new OperationExecutionResult <T>(result, stopwatch.Elapsed, attempt)); } catch (Exception e) { attempt++; var retryParams = policy.GetRetryParameters(attempt, e); //Log if (retryParams.ShouldRetry) { context.CancellationToken.WaitForInterval(retryParams.WaitTime); } else { logger.LogMessage(string.Format(CultureInfo.InvariantCulture, "\r\nOperation attempt failed because of the following error:: {0}\r\n\r\n", e.Message), Severity.Informational, Verbosity.Detailed); return(new OperationExecutionResult <T>(e, stopwatch.Elapsed, attempt)); } } } throw new InvalidOperationException("Should not reach here. Bug in retry policy implementation"); }
public bool AddUser(AppUser user) { try { lock (x) { bool retVal = manager.AddUser(user); log.LogMessage(LOG_TYPE.INFO, "Add User executed succesfuly."); return(retVal); } } catch { log.LogMessage(LOG_TYPE.ERROR, "Add User executed unsuccesfuly."); return(false); } }
/// <summary> /// Compares two assemblies. /// </summary> /// <param name="assembly1">The first assembly.</param> /// <param name="assembly2">The second assembly.</param> /// <param name="logger">The logger.</param> /// <returns>True if the assemblies match, otherwise false.</returns> private static bool CompareAssemblies(Assembly assembly1, Assembly assembly2, ILogger logger) { Type[] assembly1Types = assembly1.GetTypes(); Type[] assembly2Types = assembly2.GetTypes(); bool areSame = true; if (assembly1Types.Length != assembly2Types.Length) { logger.LogMessage(LogLevel.Warning, "Assemblies have a different number of types."); } if (areSame) { foreach (Type type1 in assembly1Types) { if (!type1.FullName.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)) { bool typeFound = false; for (int typeIndex = 0; typeIndex < assembly2Types.Length; typeIndex++) { Type type2 = assembly2Types[typeIndex]; if (type2.FullName == type1.FullName) { typeFound = true; areSame = CompareType(type1, type2, logger); } } if (!typeFound) { logger.LogMessage(LogLevel.Warning, "Assembly is missing type {0}.", type1.FullName); areSame = false; } } } } return(areSame); }
public async Task TestInitialize() { logger = new Logger(new TestContextWrapper(TestContext)); _VSHandler = new VSHandler(logger); await _VSHandler.StartVSAsync(); logger.LogMessage($"TestInit starting VS pid= {_VSHandler.vsProc.Id}"); await _VSHandler.EnsureGotDTE(TimeSpan.FromSeconds(60)); await _VSHandler.DteExecuteCommand("View.ErrorList"); }
public async Task GenerateCode([NotNull] ViewGeneratorModel viewGeneratorModel) { if (string.IsNullOrEmpty(viewGeneratorModel.ViewName)) { throw new ArgumentException("The ViewName cannot be empty"); } if (string.IsNullOrEmpty(viewGeneratorModel.TemplateName)) { throw new ArgumentException("The TemplateName cannot be empty"); } var outputPath = ValidateAndGetOutputPath(viewGeneratorModel, outputFileName: viewGeneratorModel.ViewName + Constants.ViewExtension); var modelTypeAndContextModel = await ValidateModelAndGetMetadata(viewGeneratorModel); var layoutDependencyInstaller = ActivatorUtilities.CreateInstance <MvcLayoutDependencyInstaller>(_serviceProvider); await layoutDependencyInstaller.Execute(); if (viewGeneratorModel.ViewName.EndsWith(Constants.ViewExtension, StringComparison.OrdinalIgnoreCase)) { int viewNameLength = viewGeneratorModel.ViewName.Length - Constants.ViewExtension.Length; viewGeneratorModel.ViewName = viewGeneratorModel.ViewName.Substring(0, viewNameLength); } bool isLayoutSelected = !viewGeneratorModel.PartialView && (viewGeneratorModel.UseDefaultLayout || !String.IsNullOrEmpty(viewGeneratorModel.LayoutPage)); var templateModel = new ViewGeneratorTemplateModel() { ViewDataTypeName = modelTypeAndContextModel.ModelType.FullName, ViewDataTypeShortName = modelTypeAndContextModel.ModelType.Name, ViewName = viewGeneratorModel.ViewName, LayoutPageFile = viewGeneratorModel.LayoutPage, IsLayoutPageSelected = isLayoutSelected, IsPartialView = viewGeneratorModel.PartialView, ReferenceScriptLibraries = viewGeneratorModel.ReferenceScriptLibraries, ModelMetadata = modelTypeAndContextModel.ContextProcessingResult.ModelMetadata, JQueryVersion = "1.10.2" //Todo }; var templateName = viewGeneratorModel.TemplateName + Constants.RazorTemplateExtension; await _codeGeneratorActionsService.AddFileFromTemplateAsync(outputPath, templateName, TemplateFolders, templateModel); _logger.LogMessage("Added View : " + outputPath.Substring(ApplicationEnvironment.ApplicationBasePath.Length)); await layoutDependencyInstaller.InstallDependencies(); if (modelTypeAndContextModel.ContextProcessingResult.ContextProcessingStatus == ContextProcessingStatus.ContextAddedButRequiresConfig) { throw new Exception("Scaffolding generated all the code but the new context created could be registered using dependency injection." + "There may be additional steps required for the generated code to work. Refer to <forward-link>"); } }
public void Update(Monkey monkey, Trick trick) { if (monkey == null) { throw new ArgumentNullException(nameof(monkey)); } if (trick == null) { throw new ArgumentNullException(nameof(trick)); } switch ((int)trick.trickType) { case 0: logger.LogMessage($"Spectateur applaudit pendant le tour {trick.trickType} '{trick.trickName}' du {monkey.Name}"); break; case 1: logger.LogMessage($"spectateur siffle pendant le tour {trick.trickType} '{trick.trickName}' du {monkey.Name}"); break; } }
public void Copy(string aSrcPathname, string aDestPathname, bool aClearReadonly = true) { _logger.LogMessage("Copy"); string xSrc = Path.Combine(_srcPath, aSrcPathname); _logger.LogMessage(" From: " + xSrc); string xDest = Path.Combine(_destPath, aDestPathname); _logger.LogMessage(" To: " + xDest); // Copying files that are in TFS often they will be read only, so need to kill this file before copy // We don't use TFS any more.. but left the code. if (aClearReadonly && File.Exists(xDest)) { ResetReadOnly(xDest); } File.Copy(xSrc, xDest, true); ResetReadOnly(xDest); }
public virtual DbHistorySchemaController Build(IDbSchemaReader reader, IScriptDestinationWriter writer) { _logger.LogMessage("Building Db History Schema Controller using the following configuration {0}", GetConfigurationLogString()); return(new DbHistorySchemaController( reader, new HistoryTableInspector(this.Configuration, _logger), new HistoryPerTableChangeScriptGenerator(this.Configuration, _logger), writer, _logger )); }
public ViewResult List(string category, int page = 1) { Stopwatch timeSpan = Stopwatch.StartNew(); ViewBag.currentCategory = category; var productsList = _productRepository.Products.Where(p => category == null ? true : p.Category == category).OrderBy(p => p.ProductId); var productsListViewModel = new ProductsListViewModel { Products = productsList.Skip((page - 1) * _pageSize) .Take(_pageSize), GPager = new GPager(productsList.Count(), page, _pageSize), CurrentCategory = category }; timeSpan.Stop(); _logger.LogMessage("ProductController", "List", timeSpan.Elapsed, "Getting 4 Records at a time and doing Paging"); return(View(productsListViewModel)); #region Without Category //Stopwatch timeSpan = Stopwatch.StartNew(); //var productsList = _productRepository.Products.OrderBy(p => p.ProductId); //var productsListViewModel = new ProductsListViewModel //{ // Products = productsList.Skip((page - 1) * _pageSize) // .Take(_pageSize), // GPager = new GPager(productsList.Count(), page, _pageSize) //}; //timeSpan.Stop(); //_logger.LogMessage("ProductController", "List", timeSpan.Elapsed, "Getting 4 Records at a time and doing Paging"); //return View(productsListViewModel); #endregion #region Raw Paging //Stopwatch timeSpan = Stopwatch.StartNew(); //var productsList = _productRepository.Products // .OrderBy(p=>p.ProductId) // .Skip((page -1) * _pageSize) // .Take(_pageSize); //timeSpan.Stop(); //_logger.LogMessage("ProductController", "List", timeSpan.Elapsed, "Getting 4 Records at a time from the products"); //return View(productsList); #endregion #region Without Paging //Stopwatch timeSpan = Stopwatch.StartNew(); //var result = _productRepository.Products; //timeSpan.Stop(); //_logger.LogMessage("ProductController", "List", timeSpan.Elapsed, "Getting all the products"); //return View(result); #endregion }
private async Task CommandExecutedAsync(Optional <CommandInfo> command, ICommandContext context, IResult result) { var commandName = command.IsSpecified ? command.Value.Name : "A command"; await _logger.LogMessage(new LogMessage(LogSeverity.Info, "CommandExecution", $"{commandName} was executed at {DateTime.UtcNow}.")); if (!string.IsNullOrEmpty(result?.ErrorReason)) { await context.Channel.SendMessageAndDeleteAsync($":x: {result.ErrorReason}", alsoDelete : context.Message); } }
/// <summary> /// Initializes a new instance of the <see cref="BaseTestObject" /> class /// </summary> /// <param name="logger">The test's logger</param> /// <param name="softAssert">The test's soft assert</param> /// <param name="collection">The test's performance timer collection</param> /// <param name="fullyQualifiedTestName">The test's fully qualified test name</param> public BaseTestObject(ILogger logger, ISoftAssert softAssert, IPerfTimerCollection collection, string fullyQualifiedTestName) { this.Log = logger; this.SoftAssert = softAssert; this.PerfTimerCollection = collection; this.Values = new Dictionary <string, string>(); this.Objects = new Dictionary <string, object>(); this.ManagerStore = new ManagerStore(); this.AssociatedFiles = new HashSet <string>(); logger.LogMessage(MessageType.INFORMATION, "Setup test object for " + fullyQualifiedTestName); }
private void InstallPluginIfRequired(Lifetime lifetime, [NotNull] IProject project) { if (!IsPluginNeeded(project)) { return; } myLogger.LogMessage(LoggingLevel.INFO, "Unity -> Rider plugin missing, installing"); if (TryInstall(project)) { myLogger.LogMessage(LoggingLevel.INFO, "Plugin installed"); var notification = new RdNotificationEntry("Plugin installed", "Unity -> Rider plugin was added to Unity project", true, RdNotificationEntryType.INFO); myNotifications.Notification.Fire(notification); } else { myLogger.LogMessage(LoggingLevel.WARN, "Plugin was not installed"); } }
void LoggerThreadProc() { for (; ;) { LogMessageRecord rec = m_queue.Get(); if (rec == null) { return; } m_target.LogMessage(rec); } }
public bool Send(Message message) { lock (_writer) { try { if (message.MessageType == MessageTypes.Terminate.Value) { TerminateSessionRequested = true; } _writer.Write(JsonConvert.SerializeObject(message)); } catch (Exception ex) { _logger.LogMessage(ex.Message, LogMessageLevel.Error); throw ex; } } return(true); }
public async Task <IActionResult> Create([FromBody] SavedProductResource savedProductResources) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var product = _mapper.Map <SavedProductResource, Product>(savedProductResources); await _unitOfWork.ProductRepository.AddAsync(product); if (!await _unitOfWork.CompleteAsync()) { _logger.LogMessage(LoggingEvents.SavedFail, ApplicationConstants.ControllerName.Product, product.Id); return(FailedToSave(product.Id)); } product = await _unitOfWork.ProductRepository.GetProduct(product.Id); var result = _mapper.Map <Product, ProductResource>(product); _logger.LogMessage(LoggingEvents.Created, ApplicationConstants.ControllerName.Product, product.Id); return(CreatedAtRoute(ApplicationConstants.ControllerName.Product, new { id = product.Id }, result)); }
public async Task <IActionResult> Create([FromBody] CategoryResource categoryResources) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var category = _mapper.Map <CategoryResource, Category>(categoryResources); await _unitOfWork.CategoryRepository.AddAsync(category); // if something happens and the new item can not be saved, return the error if (!await _unitOfWork.CompleteAsync()) { _logger.LogMessage(LoggingEvents.SavedFail, ApplicationConstants.ControllerName.Category, category.Id); return(FailedToSave(category.Id)); } category = await _unitOfWork.CategoryRepository.GetCategory(category.Id); var result = _mapper.Map <Category, CategoryResource>(category); _logger.LogMessage(LoggingEvents.Created, ApplicationConstants.ControllerName.Category, category.Id); return(CreatedAtRoute(ApplicationConstants.ControllerName.Category, new { id = category.Id }, result)); }
public async Task <IActionResult> Create([FromBody] SavedOrderResource resource) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var order = _mapper.Map <SavedOrderResource, Order>(resource); await _unitOfWork.OrderRepository.AddAsync(order); if (!await _unitOfWork.CompleteAsync()) { _logger.LogMessage(LoggingEvents.SavedFail, ApplicationConstants.ControllerName.Order, order.Id); return(FailedToSave(order.Id)); } order = await _unitOfWork.OrderRepository.GetOrder(order.Id, false); _logger.LogMessage(LoggingEvents.Created, ApplicationConstants.ControllerName.Order, order.Id); return(Ok(order.Id)); }
public async Task <IActionResult> Create([FromBody] ShippingResource shippingResource) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var shipping = _mapper.Map <ShippingResource, Shipping>(shippingResource); await _unitOfWork.ShippingRepository.AddAsync(shipping); // if something happens and the new item can not be saved, return the error if (!await _unitOfWork.CompleteAsync()) { _logger.LogMessage(LoggingEvents.SavedFail, ApplicationConstants.ControllerName.Shipping, shipping.Id); return(FailedToSave(shipping.Id)); } shipping = await _unitOfWork.ShippingRepository.GetShipping(shipping.Id); var result = _mapper.Map <Shipping, ShippingResource>(shipping); _logger.LogMessage(LoggingEvents.Created, ApplicationConstants.ControllerName.Shipping, shipping.Id); return(CreatedAtRoute(ApplicationConstants.ControllerName.Shipping, new { id = shipping.Id }, result)); }
public void Process() { // setup long running task var task = Task.Run(() => { // note: Task.Run() should only be used to run asyncronous methods! // uncomment to simulate error handling //throw new Exception("who knew?"); _logger.LogMessage("AsyncProcessorTask.Process() started"); Thread.Sleep(2000); _logger.LogMessage("AsyncProcessorTask.Process() completed"); return("all done"); }); /* * // setup continuation task, executed after long running task completes * task.ContinueWith((t) => * { * * if (t.IsFaulted) * { * _logger.LogMessage($"Exception caught: { t.Exception.Message }"); * return; * } * * _logger.LogMessage($"Continuation received result: {t.Result}"); * }); */ task .ConfigureAwait(true) .GetAwaiter() .OnCompleted(() => { _logger.LogMessage($"Continuation received result: {task.Result}"); }); }
private KMSResponse CreateKMSResponse(KMSRequest kmsRequest, IKMSServerSettings serverSettings, ILogger logger) { KMSResponse response = new KMSResponse { Version = kmsRequest.Version }; string kmsPID; if (serverSettings.GenerateRandomKMSPID) { KMSPIDGenerator generator = new KMSPIDGenerator(); kmsPID = generator.CreateKMSPID(kmsRequest); logger.LogMessage("KMS PID: " + kmsPID); logger.LogMessage("Application ID: " + kmsRequest.ApplicationId); logger.LogMessage("Client Machine ID: " + kmsRequest.ClientMachineId); logger.LogMessage("KMS Counted ID: " + kmsRequest.KmsCountedId); logger.LogMessage("SKUID ID: " + kmsRequest.SkuId); logger.LogMessage("KMS Activation Response (KMS V" + kmsRequest.MajorVersion + "." + kmsRequest.MinorVersion + ") sent." + Environment.NewLine); } else { kmsPID = serverSettings.DefaultKMSPID; } response.KMSPID = kmsPID; response.ClientMachineId = kmsRequest.ClientMachineId; response.RequestTime = kmsRequest.RequestTime; response.CurrentClientCount = serverSettings.CurrentClientCount; response.VLActivationInterval = serverSettings.VLActivationInterval; response.VLRenewalInterval = serverSettings.VLRenewalInterval; return(response); }
public Place[] GetNearbyPlaces(double?latitude, double?longitude, string languageCode, bool sensor, int radius, string pipedTypeList = null) { pipedTypeList = pipedTypeList ?? new PlaceTypes(_settings.Data.PlacesTypes).GetPipedTypeList(); var client = new JsonServiceClient(PlacesServiceUrl); var @params = new Dictionary <string, string> { { "sensor", sensor.ToString(CultureInfo.InvariantCulture).ToLowerInvariant() }, { "key", PlacesApiKey }, { "radius", radius.ToString(CultureInfo.InvariantCulture) }, { "language", languageCode }, { "types", pipedTypeList }, }; if (latitude != null && longitude != null) { @params.Add("location", string.Join(",", latitude.Value.ToString(CultureInfo.InvariantCulture), longitude.Value.ToString(CultureInfo.InvariantCulture))); } var r = "json" + BuildQueryString(@params); _logger.LogMessage("Nearby Places API : " + PlacesServiceUrl + r); return(client.Get <PlacesResponse>(r).Results.ToArray()); }
/// <summary> /// The Run method is the entry point of a background task. /// </summary> /// <param name="taskInstance"></param> public async void Run(IBackgroundTaskInstance taskInstance) { deferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnCanceled; taskInstance.Task.Completed += Taskcompleted; IContainer container = Container.Instance; Services.IoC.Register(); logger = container.Resolve<ILogger>(); logger.LogMessage($"BackgroundAudioTask {taskInstance.Task.Name} starting..."); try { // Ensure that Background Audio is initialized by accessing BackgroundMediaPlayer.Current var state = BackgroundMediaPlayer.Current.CurrentState; logger.LogMessage($"BackgroundAudioTask BackgroundMediaPlayer state is {state}.", LoggingLevel.Information); applicationSettingsHelper = container.Resolve<IApplicationSettingsHelper>(); await applicationSettingsHelper.LoadPlaylist(); audioManager = new AudioManager( logger, applicationSettingsHelper, SystemMediaTransportControls.GetForCurrentView()); BackgroundMediaPlayer.MessageReceivedFromForeground -= onMessageReceivedFromForeground; BackgroundMediaPlayer.MessageReceivedFromForeground += onMessageReceivedFromForeground; applicationSettingsHelper.SaveSettingsValue(Keys.IsBackgroundTaskRunning, true); BackgroundMediaPlayer.SendMessageToForeground(new ValueSet { { Keys.IsBackgroundTaskRunning, null } }); logger.LogMessage($"BackgroundAudioTask initialized.", LoggingLevel.Information); } catch (Exception ex) { logger.LogMessage($"Unhandled exception in BackgroundAudioTask. {ex.Message}", LoggingLevel.Critical); Dispose(); } }
/// <summary> /// Creates ne instance of <see cref="VoiceCommandsHandler"/> /// </summary> /// <param name="logger">Instance of <see cref="ILogger"/></param> /// <param name="applicationSettingsHelper">Instance of <see cref="IApplicationSettingsHelper"/></param> /// <param name="episodeListManager">Instance of <see cref="IEpisodeListManager"/></param> /// <param name="playbackManager">Instance of <see cref="IPlaybackManager"/></param> /// <param name="textSpeaker">Instance of <see cref="ITextSpeaker"/></param> public VoiceCommandsHandler( ILogger logger, IApplicationSettingsHelper applicationSettingsHelper, IEpisodeListManager episodeListManager, IPlaybackManager playbackManager, ITextSpeaker textSpeaker) { this.textSpeaker = textSpeaker; this.playbackManager = playbackManager; this.episodeListManager = episodeListManager; this.applicationSettingsHelper = applicationSettingsHelper; this.logger = logger; Initialization = initializeAsync(); logger.LogMessage("Voice commands handler initialized.", LoggingLevel.Information); }
/// <summary> /// Creates new instance of <see cref="DownloadManager"/> /// </summary> /// <param name="logger">Instance of <see cref="ILogger"/></param> /// <param name="playlist">Instance of <see cref="IPlayList"/></param> /// <param name="loaderFactory">Instance of <see cref="ILoaderFactory"/></param> /// <param name="parser">Instance of <see cref="IParser"/></param> /// <param name="fileUtils">Instance of <see cref="IFileUtils"/></param> public DownloadManager( ILogger logger, ILoaderFactory loaderFactory, IParser parser, IApplicationSettingsHelper applicationSettingsHelper, IFileUtils fileUtils) { this.logger = logger; this.loaderFactory = loaderFactory; this.parser = parser; this.applicationSettingsHelper = applicationSettingsHelper; this.fileUtils = fileUtils; Initialization = RetrieveActiveDownloads(); logger.LogMessage("DownloadManager: Initialized.", LoggingLevel.Information); }
/// <summary> /// Creates new instance of <see cref="MainPage"/> /// </summary> public MainPage() { // TODO: Think about using static properties IContainer container = Container.Instance; logger = container.Resolve<ILogger>(); applicationSettingsHelper = container.Resolve<IApplicationSettingsHelper>(); mainPageViewModel = container.Resolve<MainPageViewModel>(); NavigationCacheMode = NavigationCacheMode.Required; InitializeComponent(); Loaded += onPageLoaded; Unloaded += onPageUnloaded; logger.LogMessage("MainPage has been created."); }
/// <summary> /// Standard implementation of <see cref="Assembly.GetExportedTypes()"/> /// with autorecovery and logging of common error conditions. /// </summary> /// <param name="assembly">The assembly whose exported types are needed</param> /// <param name="logger">Optional logger to use to report problems.</param> /// <returns>The collection of types. It may be empty but it will not be null.</returns> internal static IEnumerable<Type> GetExportedTypes(Assembly assembly, ILogger logger) { Type[] types = null; try { types = assembly.GetExportedTypes(); } catch (Exception ex) { if (ex.IsFatal()) { throw; } // Some common exceptions log a warning and return an empty collection if (ex is TypeLoadException || ex is FileNotFoundException || ex is FileLoadException || ex is BadImageFormatException) { // We log only if we have a logger and this is not MSCORLIB // MSCORLIB.GetExportedTypes will throw TypeLoadException when used // in a Reflection-Only load. Yet that is not fatal because the // real MSCORLIB is loaded and the user would be distracted by // any warnings of this nature. if (logger != null && !IsAssemblyMsCorlib(assembly.GetName())) { logger.LogMessage(string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Assembly_Load_Type_Error, assembly.FullName, ex.Message)); } return new Type[0]; } // This particular exception may have loaded at least some types. Capture what we can. ReflectionTypeLoadException rtle = ex as ReflectionTypeLoadException; if (rtle != null) { // They tell us the types they loaded -- but the array could have nulls where they failed types = rtle.Types; // Show a warning message so user knows we have an issue if (logger != null) { StringBuilder sb = new StringBuilder(); Exception[] loadExceptions = rtle.LoaderExceptions; foreach (Exception e in loadExceptions) { sb.AppendLine(e.Message); } logger.LogMessage(string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Failed_To_Load, assembly.FullName, sb.ToString())); } // Return collection without nulls return types.Where(t => t != null); } // All other exceptions rethrow throw; } // Successful return return types; }
/// <summary> /// Compares two assemblies. /// </summary> /// <param name="assembly1">The first assembly.</param> /// <param name="assembly2">The second assembly.</param> /// <param name="logger">The logger.</param> /// <returns>True if the assemblies match, otherwise false.</returns> private static bool CompareAssemblies(Assembly assembly1, Assembly assembly2, ILogger logger) { Type[] assembly1Types = assembly1.GetTypes(); Type[] assembly2Types = assembly2.GetTypes(); bool areSame = true; if (assembly1Types.Length != assembly2Types.Length) { logger.LogMessage(LogLevel.Warning, "Assemblies have a different number of types."); } if (areSame) { foreach (Type type1 in assembly1Types) { if (!type1.FullName.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)) { bool typeFound = false; for (int typeIndex = 0; typeIndex < assembly2Types.Length; typeIndex++) { Type type2 = assembly2Types[typeIndex]; if (type2.FullName == type1.FullName) { typeFound = true; areSame = CompareType(type1, type2, logger); } } if (!typeFound) { logger.LogMessage(LogLevel.Warning, "Assembly is missing type {0}.", type1.FullName); areSame = false; } } } } return areSame; }
/// <summary> /// Creates new instance of <see cref="EpisodesViewModel"/> /// </summary> /// <param name="logger">Instance of <see cref="ILogger"/></param> /// <param name="playlist">Instance of <see cref="IPlayList"/></param> /// <param name="loaderFactory">Instance of <see cref="ILoaderFactory"/></param> /// <param name="navigationService">Instance of <see cref="INavigationService"/></param> /// <param name="applicationSettingsHelper">Instance of <see cref="IApplicationSettingsHelper"/></param> /// <param name="downloadManager">Instance of <see cref="IDownloadManager"/></param> public EpisodesViewModel( ILogger logger, INavigationService navigationService, IApplicationSettingsHelper applicationSettingsHelper, IDownloadManager downloadManager, IEpisodeListManager episodeListManager) { this.logger = logger; this.navigationService = navigationService; this.applicationSettingsHelper = applicationSettingsHelper; this.downloadManager = downloadManager; this.episodeListManager = episodeListManager; RefreshCommand = new RelayCommand(loadEpisodeListFromServer); DownloadCommand = new RelayCommand(downloadEpisode); CancelDownloadCommand = new RelayCommand((Action<object>)cancelDownload); DeleteCommand = new RelayCommand((Action<object>)deleteEpisodeFromStorage); PlayCommand = new RelayCommand((Action<object>)playEpisode); AddToPlaylistCommand = new RelayCommand((Action<object>)addToPlaylistCommand); ClearPlaylistCommand = new RelayCommand((Action)clearPlaylistCommand); Application.Current.Resuming += onAppResuming; Application.Current.Suspending += (_, __) => unregisterUpdaterCompletionHandler(); Application.Current.UnhandledException += (_, __) => unregisterUpdaterCompletionHandler(); backgroundUpdaterTask = BackgroundTaskRegistration.AllTasks .Where(t => t.Value.Name == Constants.BackgroundUpdaterTaskName) .Select(t => t.Value) .FirstOrDefault(); Initialization = initializeAsync(); logger.LogMessage("EpisodesViewModel: Initialized.", LoggingLevel.Information); }
/// <summary> /// Creates new instance of <see cref="Parser"/> /// </summary> /// <param name="logger">The logger instance</param> public Parser(ILogger logger) { this.logger = logger; logger.LogMessage("Parser initialized.", LoggingLevel.Information); }
/// <summary> /// Does a "reflection only load" from the given assembly file. /// </summary> /// <param name="assemblyFileName">The full path to the file of the assembly to load.</param> /// <param name="logger">The optional logger to use to report known load failures.</param> /// <returns>The loaded <see cref="Assembly"/> if successful, null if it could not be loaded for a known reason /// (and an error message will have been logged). /// </returns> internal static Assembly ReflectionOnlyLoadFrom(string assemblyFileName, ILogger logger) { System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(assemblyFileName), "assemblyFileName is required"); Assembly assembly = null; try { assembly = Assembly.ReflectionOnlyLoadFrom(assemblyFileName); } catch (Exception ex) { // Some common exceptions log a warning and keep running if (ex is System.IO.FileNotFoundException || ex is System.IO.FileLoadException || ex is System.IO.PathTooLongException || ex is BadImageFormatException || ex is System.Security.SecurityException) { if (logger != null) { logger.LogMessage(string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Assembly_Load_Error, assemblyFileName, ex.Message)); } } else { throw; } } return assembly; }
internal static Assembly LoadAssembly(string assemblyFileName, ILogger logger) { System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(assemblyFileName), "assemblyFileName is required"); Assembly assembly = null; // TODO: [roncain] Dev10 temp workaround. // Reference assemblies will fail by file path, so try to load via name // and silently accept that result. If fail, let normal file load try. try { AssemblyName asmName = AssemblyName.GetAssemblyName(assemblyFileName); assembly = LoadAssembly(asmName, null); if (assembly != null) { return assembly; } // Otherwise attempt to load from file assembly = Assembly.LoadFrom(assemblyFileName); } catch (Exception ex) { // Some common exceptions log a warning and keep running if (ex is System.IO.FileNotFoundException || ex is System.IO.FileLoadException || ex is System.IO.PathTooLongException || ex is BadImageFormatException || ex is System.Security.SecurityException) { if (logger != null) { logger.LogMessage(string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Assembly_Load_Error, assemblyFileName, ex.Message)); } } else { throw; } } return assembly; }
/// <summary> /// Initializes new instance of <see cref="MainPageViewModel"/> /// </summary> /// <param name="playerModel">Instance of <see cref="PlayerViewModel"/></param> /// <param name="episodesViewModel">Instance of <see cref="EpisodesViewModel"/></param> /// <param name="logger"></param> public MainPageViewModel(PlayerViewModel playerModel, EpisodesViewModel episodesViewModel, ILogger logger) { PlayerModel = playerModel; EpisodesModel = episodesViewModel; logger.LogMessage("Main page view model created."); }
/// <summary> /// Compares two Types. /// </summary> /// <param name="type1">Type to compare 1.</param> /// <param name="type2">Type to compare 2.</param> /// <param name="logger">The logger to write messages to.</param> /// <returns>True if the Types match, otherwise false.</returns> private static bool CompareType(Type type1, Type type2, ILogger logger) { bool areSame = true; MemberInfo[] type1Members = type1.GetMembers(); MemberInfo[] type2Members = type2.GetMembers(); if (type1Members.Length == type2Members.Length) { // If the type has a StructLayout attribute, make sure that the order // of fields match up. object[] structLayoutAttributes = type1.GetCustomAttributes( typeof(StructLayoutAttribute), false); if (structLayoutAttributes.Length > 0) { BindingFlags fieldBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; FieldInfo[] type1Fields = type1.GetFields(fieldBindingFlags); FieldInfo[] type2Fields = type2.GetFields(fieldBindingFlags); if (type1Fields.Length == type2Fields.Length) { for (int fieldIndex = 0; fieldIndex < type1Fields.Length; fieldIndex++) { FieldInfo type1Field = type1Fields[fieldIndex]; FieldInfo type2Field = type2Fields[fieldIndex]; if (type1Field.Name != type2Field.Name || type1Field.FieldType != type2Field.FieldType) { logger.LogMessage( LogLevel.Warning, "Type {0} has a different ordering of fields when StructLayoutAttribute is present.", type1.FullName); areSame = false; break; } } } else { logger.LogMessage( LogLevel.Warning, "Type {0} has a different number of fields.", type1.FullName); areSame = false; } } //// TODO: Compare all members } else { logger.LogMessage( LogLevel.Warning, "Type {0} has a different number of members.", type1.FullName); areSame = false; } return areSame; }
/// <summary> /// Tests the files. /// </summary> /// <param name="inputDir">The input dir.</param> /// <param name="logger">The logger.</param> private static void TestFiles(string inputDir, ILogger logger) { if (!Directory.Exists(inputDir)) { logger.LogMessage(LogLevel.Error, "Test directory {0} does not exist", inputDir); Environment.Exit(Fail); } string arrangedDir = Path.Combine(inputDir, "Arranged"); if (Directory.Exists(arrangedDir)) { Directory.Delete(arrangedDir, true); } Directory.CreateDirectory(arrangedDir); FileInfo[] allSourceFiles = GetSourceFileNames(inputDir); logger.LogMessage(LogLevel.Info, "Testing with {0} source files...", allSourceFiles.Length); int preprocessorCount = 0; int uncompiledCount = 0; int successCount = 0; int failedCount = 0; TestLogger testLogger = new TestLogger(); FileArranger fileArranger = new FileArranger(null, testLogger); foreach (FileInfo sourceFile in allSourceFiles) { string initialSource = File.ReadAllText(sourceFile.FullName, Encoding.Default); CompilerResults initialResults = CompileSourceFile(sourceFile, initialSource); CompilerError error = TestUtilities.GetCompilerError(initialResults); if (error == null) { logger.LogMessage(LogLevel.Trace, "Succesfully compiled {0}", sourceFile.FullName); // // Arrange the source code file // testLogger.Clear(); string outputFile = Path.Combine(arrangedDir, sourceFile.Name); bool success = false; try { success = fileArranger.Arrange(sourceFile.FullName, outputFile); } catch (Exception ex) { logger.LogMessage( LogLevel.Error, "Unable to arrange {0}. {1}", sourceFile.Name, ex.Message); failedCount++; } if (success) { logger.LogMessage(LogLevel.Info, "Arrange successful."); } else if (testLogger.HasPartialMessage(LogLevel.Warning, "preprocessor")) { logger.LogMessage(LogLevel.Trace, "File is unhandled."); preprocessorCount++; } else { foreach (TestLogger.TestLogEvent logEvent in testLogger.Events) { logger.LogMessage(logEvent.Level, logEvent.Message); } logger.LogMessage(LogLevel.Error, "Unable to arrange {0}.", sourceFile.Name); failedCount++; } if (success) { string arrangedSource = File.ReadAllText(outputFile, Encoding.Default); CompilerResults arrangedResults = CompileSourceFile( new FileInfo(outputFile), arrangedSource); CompilerError arrangedError = TestUtilities.GetCompilerError(arrangedResults); if (arrangedError == null) { logger.LogMessage(LogLevel.Trace, "Succesfully compiled arranged file {0}", outputFile); try { bool assembliesMatch = CompareAssemblies( initialResults.CompiledAssembly, arrangedResults.CompiledAssembly, logger); if (assembliesMatch) { successCount++; } else { logger.LogMessage(LogLevel.Error, "Arranged assembly differs."); failedCount++; } } catch (ReflectionTypeLoadException ex) { logger.LogMessage( LogLevel.Error, "Failed to load one or more types. {0}, {1}", outputFile, ex.ToString()); failedCount++; } } else { logger.LogMessage( LogLevel.Error, "Failed to compile arranged file {0}, {1}", outputFile, arrangedError.ToString()); failedCount++; } } } else { logger.LogMessage(LogLevel.Error, "Failed to compile {0}", sourceFile.FullName); uncompiledCount++; } } logger.LogMessage(LogLevel.Info, "Unsupported - preprocessor: " + preprocessorCount.ToString()); logger.LogMessage(LogLevel.Info, "Uncompiled: " + uncompiledCount.ToString()); logger.LogMessage(LogLevel.Info, "Success: " + successCount.ToString()); logger.LogMessage(LogLevel.Info, "Failed: " + failedCount.ToString()); }
/// <summary> /// Runs NArrange using the specified arguments. /// </summary> /// <param name="logger">Logger for messages.</param> /// <param name="commandArgs">Command arguments.</param> /// <returns>True if succesful, otherwise false.</returns> public static bool Run(ILogger logger, CommandArguments commandArgs) { bool success = true; if (logger == null) { throw new ArgumentNullException("logger"); } else if (commandArgs == null) { throw new ArgumentNullException("commandArgs"); } if (commandArgs.Restore) { logger.LogMessage(LogLevel.Verbose, "Restoring {0}...", commandArgs.Input); string key = BackupUtilities.CreateFileNameKey(commandArgs.Input); try { success = BackupUtilities.RestoreFiles(BackupUtilities.BackupRoot, key); } catch (Exception ex) { logger.LogMessage(LogLevel.Warning, ex.Message); success = false; } if (success) { logger.LogMessage(LogLevel.Info, "Restored"); } else { logger.LogMessage(LogLevel.Error, "Restore failed"); } } else { // // Arrange the source code file // FileArranger fileArranger = new FileArranger(commandArgs.Configuration, logger); success = fileArranger.Arrange(commandArgs.Input, commandArgs.Output, commandArgs.Backup); if (!success) { logger.LogMessage(LogLevel.Error, "Unable to arrange {0}.", commandArgs.Input); } else { logger.LogMessage(LogLevel.Info, "Arrange successful."); } } return success; }
/// <summary> /// Does a "reflection only load" of the given <paramref name="assemblyName"/>. /// </summary> /// <param name="assemblyName">The name of the assembly to load.</param> /// <param name="assemblySearchPaths">Optional list of folders to search for assembly references.</param> /// <param name="loadedAssemblies">Dictionary to track already loaded assemblies.</param> /// <param name="logger">The optional logger to use to report known load failures.</param> /// <returns>The loaded <see cref="Assembly"/> if successful, null if it could not be loaded for a known reason /// (and a warning message will have been logged). /// </returns> internal static Assembly ReflectionOnlyLoad(AssemblyName assemblyName, IEnumerable<string> assemblySearchPaths, IDictionary<string, Assembly> loadedAssemblies, ILogger logger) { System.Diagnostics.Debug.Assert(assemblyName != null, "assemblyName is required"); Assembly assembly = null; string errorMessage = null; try { assembly = Assembly.ReflectionOnlyLoad(assemblyName.FullName); } catch (Exception ex) { // Some common exceptions log a warning and keep running if (ex is System.IO.FileNotFoundException || ex is System.IO.FileLoadException || ex is System.IO.PathTooLongException || ex is BadImageFormatException || ex is System.Security.SecurityException) { errorMessage = ex.Message; } else { throw; } } // If we fail but were provided search paths, go search for it. No warnings are logged. if (assembly == null && assemblySearchPaths != null) { assembly = ReflectionOnlyLoadFromSearchPaths(assemblyName, assemblySearchPaths); } // If the assembly is still not loaded, try once again against loaded assemblies, this can // happen for system PCL which are not in search paths but may be of a different version // than the actual assembly used at runtime. // Most have the Retargetable flag set, but a pair distributed via Microsoft.BCL* nuget packages are missing this if(assembly == null && assemblyName.Flags.HasFlag(AssemblyNameFlags.Retargetable)) { assembly = loadedAssemblies.Values.FirstOrDefault(a => a.GetName().Name == assemblyName.Name); } // If we failed, log a warning with the original load failure if (assembly == null && !string.IsNullOrEmpty(errorMessage) && logger != null) { logger.LogMessage(string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Assembly_Load_Error, assemblyName, errorMessage)); } return assembly; }
/// <summary> /// Creates instance of <see cref="PlayerViewModel"/> /// </summary> /// <param name="logger">Instance of <see cref="ILogger"/></param> /// <param name="playlist">Instance of <see cref="IPlayList"/></param> /// <param name="applicationSettingsHelper">Instance of <see cref="IApplicationSettingsHelper"/></param> /// <param name="navigationService">Instance of <see cref="INavigationService"/></param> public PlayerViewModel( ILogger logger, IApplicationSettingsHelper applicationSettingsHelper, INavigationService navigationService, IPlaybackManager playbackManager) { this.logger = logger; this.navigationService = navigationService; this.applicationSettingsHelper = applicationSettingsHelper; this.playbackManager = playbackManager; pauseIcon = new SymbolIcon(Symbol.Pause); playIcon = new SymbolIcon(Symbol.Play); PlayButtonIcon = playIcon; progressUpdateTimer = new DispatcherTimer(); // Using explicit casts here because of http://stackoverflow.com/questions/2057146/compiler-ambiguous-invocation-error-anonymous-method-and-method-group-with-fun PreviousTrackCommand = new RelayCommand((Action)onPreviousTrackAction); NextTrackCommand = new RelayCommand((Action)onNextTrackAction); PlayPauseCommand = new RelayCommand((Action)onPlayPauseAction); Application.Current.Suspending += onAppSuspending; Application.Current.Resuming += onAppResuming; Initialization = initializeAsync(); logger.LogMessage("Foreground audio player initialized.", LoggingLevel.Information); }
/// <summary> /// Creates instance of <see cref="LoaderFactory"/> /// </summary> /// <param name="logger">The <see cref="ILogger"/> instance</param> /// <param name="parser">The <see cref="IParser"/> instance</param> public LoaderFactory(ILogger logger, IParser parser) { this.parser = parser; this.logger = logger; logger.LogMessage("LoaderFactory initialized.", LoggingLevel.Information); }