public static void ApplyDacpac(Stream dacpac, string connectionString, string databaseName, ILogger log) { var options = new DacDeployOptions() { BlockOnPossibleDataLoss = true, IncludeTransactionalScripts = true, DropConstraintsNotInSource = false, DropIndexesNotInSource = false, DropDmlTriggersNotInSource = false, DropObjectsNotInSource = false, DropExtendedPropertiesNotInSource = false, DropPermissionsNotInSource = false, DropStatisticsNotInSource = false, DropRoleMembersNotInSource = false, }; var service = new DacServices(connectionString); service.Message += (x, y) => { log.Log(y.Message.Message); }; try { using (var package = DacPackage.Load(dacpac)) { service.Deploy(package, databaseName, true, options); } } catch (Exception e) { log.Log(e.Message, true); } }
public bool Execute(string installPath, string scriptFileName, IPackage package, Project project, FrameworkName targetFramework, ILogger logger) { string scriptPath, fullPath; if (package.FindCompatibleToolFiles(scriptFileName, targetFramework, out scriptPath)) { fullPath = Path.Combine(installPath, scriptPath); } else { return false; } if (File.Exists(fullPath)) { string toolsPath = Path.GetDirectoryName(fullPath); string logMessage = String.Format(CultureInfo.CurrentCulture, VsResources.ExecutingScript, fullPath); // logging to both the Output window and progress window. logger.Log(MessageLevel.Info, logMessage); IConsole console = OutputConsoleProvider.CreateOutputConsole(requirePowerShellHost: true); Host.Execute(console, "$__pc_args=@(); $input|%{$__pc_args+=$_}; & " + PathHelper.EscapePSPath(fullPath) + " $__pc_args[0] $__pc_args[1] $__pc_args[2] $__pc_args[3]; Remove-Variable __pc_args -Scope 0", new object[] { installPath, toolsPath, package, project }); return true; } return false; }
private static async Task InvokeProcessor(string message, Func <Task> action, ILogger logger) { var timer = new Stopwatch(); timer.Start(); try { logger?.Log(message); await action.Invoke(); } catch (AggregateException e) { foreach (var exception in e.InnerExceptions) { logger?.Log(exception, string.Empty); logger?.Log(); } } catch (Exception e) { logger?.Log(e, string.Empty); } logger?.Log(LogType.Info, Messages.ElapsedTimeMessageFormat, timer.Elapsed); }
/// <summary> /// Generates formatted Q# code for the file with the given uri based on the syntax tree in the given compilation. /// If the id of the file is consistent with the one assigned to a code snippet, /// logs the generated code using the given logger. /// Creates a file containing the generated code in the given output folder otherwise. /// Returns true if the generation succeeded, and false if an exception was thrown. /// Throws an ArgumentNullException if the given compilation, the file uri or its absolute path are null. /// </summary> private static bool GenerateFormattedQsFile(Compilation compilation, NonNullable <string> fileName, string outputFolder, ILogger logger) { if (compilation == null) { throw new ArgumentNullException(nameof(compilation)); } var code = Enumerable.Empty <string>(); try { code = code.Concat(GenerateQsCode(compilation, fileName, logger).Where(c => !String.IsNullOrWhiteSpace(c))); } catch (Exception ex) { logger?.Log(ErrorCode.QsGenerationFailed, Enumerable.Empty <string>(), fileName.Value); logger?.Log(ex); return(false); } if (Options.IsCodeSnippet(fileName)) { code = new string[] { "" }.Concat(Formatting.Indent(code.ToArray())); logger?.Log(InformationCode.GeneratedQsCode, Enumerable.Empty <string>(), messageParam: code.ToArray()); } else { var content = String.Join(Environment.NewLine, code.Select(block => $"{block}{Environment.NewLine}{Environment.NewLine}")); CompilationLoader.GeneratedFile(fileName, outputFolder ?? "FormattedFiles", ".qs", content); } return(true); }
private static void TestGetLocalGridEntities(Character me, EVE.ISXEVE.EVE eve, ILogger logger) { //var entities = EntityRepository.GetLocalGridEntities(me, eve); eve.RefreshStandings(); var entities = eve.QueryEntities().Where(x => x.IsPC); //var anObj = LavishScript.Objects.GetObject("Local", "Romvex"); //logger.Log(anObj.ToString()); var pilot = new Pilot("Romvex "); logger.Log(pilot.ToString()); foreach (var entity in entities) { logger.Log(entity.Name); logger.Log(LavishScriptObject.IsNullOrInvalid(entity.Owner.ToFleetMember).ToString()); logger.Log(entity.Owner.CharID.ToString()); logger.Log(entity.Owner.Corp.ID.ToString()); logger.Log(entity.AllianceID.ToString()); var standing = me.StandingTo(entity.CharID, entity.Corp.ID, entity.AllianceID); logger.Log(standing.AllianceToAlliance.ToString()); logger.Log(standing.AllianceToCorp.ToString()); logger.Log(standing.AllianceToPilot.ToString()); logger.Log(standing.CorpToAlliance.ToString()); logger.Log(standing.CorpToCorp.ToString()); logger.Log(standing.CorpToPilot.ToString()); logger.Log(standing.MeToAlliance.ToString()); logger.Log(standing.MeToCorp.ToString()); logger.Log(standing.MeToPilot.ToString()); } }
private async Task <HttpResponseMessage> Response(string dest, string method, HttpContent data) { using var httpClient = new HttpClient(); await _bucketRpm.TokenRequest(); await _bucketRps.TokenRequest(); _logger?.Log(LogLevel.Debug, $"REQUEST {dest}"); var request = new HttpRequestMessage(new HttpMethod(method), dest); request.Headers.TryAddWithoutValidation("User-Agent", _settings.ClientName); request.Content = data; if (!(_token is null)) { request.Headers.TryAddWithoutValidation("Authorization", $"{_token.TokenType} {_token.Access_Token}"); } var ret = await httpClient.SendAsync(request); _logger?.Log(LogLevel.Debug, $"RESPONSE {ret.ReasonPhrase}"); if (ret.StatusCode != HttpStatusCode.BadRequest && ret.StatusCode != HttpStatusCode.Unauthorized) { return(ret); } if (_refresh is null) { throw new Exception($"An error occured while token refreshing: {ret.StatusCode}"); } _logger?.Log(LogLevel.Warning, "REFRESHING TOKEN"); _token = await _refresh(_token); throw new HttpRequestException($"{ret.StatusCode}"); }
public async Task Consume(ConsumeContext <OrderCreateRequest> context) { _logger?.Log(LogLevel.Debug, $" Getting order from {context.Message.CustomerName}"); if (context.Message.FoodName.Contains("rabbit", StringComparison.OrdinalIgnoreCase)) { if (context.RequestId != null) { _logger?.Log(LogLevel.Debug, $"Ignorant waiter don't want people to eat Rabbit. So he reject any order"); await context.RespondAsync <OrderCreationRejected>(new { OrderId = context.Message.OrderId, Reason = "Rabbit is not for eating" }); } } if (context.RequestId != null) { _logger?.Log(LogLevel.Debug, $"This guy now took an order "); await context.RespondAsync <OrderCreationAccepted>(new { OrderId = context.Message.OrderId, CustomerName = context.Message.CustomerName, ReadyTime = _random.Next(5, 10), OrderTaker = this.Name }); } }
public static void LogTeamSelection(TeamSelection teamSelection, int gameweek, List<PredictedPlayerScore> predictedPlayerPoints, ILogger logger, bool important = false) { logger.Log(Tag.Prediction, string.Format("Selected team for gameweek {0}", gameweek), important); logger.Log(Tag.Prediction, string.Format("Predicted points: {0}", teamSelection.PredictedTotalTeamScore.ToFormatted()), important); LogTeamFormation(teamSelection.Team, logger); for (var i = 0; i < teamSelection.Team.Players.Count; i++) { if (i == 11) { logger.Log(Tag.Team, "---"); } var player = teamSelection.Team.Players[i]; var fixtures = player.FutureFixtures.Where(x => x.GameWeek == gameweek); var extraData = new StringBuilder(" "); foreach (var fixture in fixtures) { extraData.Append(fixture.OppositionClubCode); extraData.Append(fixture.Home ? "(H) " : "(A) "); } var playerGameweekPoints = predictedPlayerPoints.Single(p => p.Player == player).PredictedScore; extraData.Append(playerGameweekPoints.ToFormatted()); if (teamSelection.Team.Captain == player) { extraData.Append("("); extraData.Append((playerGameweekPoints * 2).ToFormatted()); extraData.Append(")"); } LogPlayer(player, teamSelection.Team, logger, extraData.ToString(), important); } LogTeamCost(teamSelection.Team, logger, important); }
private async Task <HttpResponseMessage> PostDataAsync(string url, Dictionary <string, string> data) { data["username"] = _username; data["password"] = _password; data["system"] = _system; string json = JsonConvert.SerializeObject(data); var stringContent = new StringContent(json, Encoding.UTF8, "application/json"); var uri = $"{_apiUrl}{url}.{_format}"; _logger?.Log($"Request content:{json}", EventLevel.Verbose); using (var client = new HttpClient()) { var response = await client.PostAsync(uri, stringContent).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { _logger?.Log($"Response received - StatusCode:{response.StatusCode}", EventLevel.Error); throw new Exception($"Request failed. Response StatusCode:{response.StatusCode}"); } _logger?.Log($"Response received - StatusCode:{response.StatusCode}", EventLevel.Informational); return(response); } }
/// <summary> /// Performs analysis of the document. Returns document global scope /// with declared variables and inner scopes. Does not analyze chain /// of dependencies, it is intended for the single file analysis. /// </summary> private async Task <IDocumentAnalysis> AnalyzeAsync(IDependencyChainNode node, CancellationToken cancellationToken) { var _startTime = DateTime.Now; _log?.Log(TraceEventType.Verbose, $"Analysis begins: {node.Document.Name}({node.Document.ModuleType})"); // Store current expected version so we can see if it still // the same at the time the analysis completes. var analysisVersion = node.Analyzable.ExpectedAnalysisVersion; // Make sure the file is parsed ans the AST is up to date. var ast = await node.Document.GetAstAsync(cancellationToken); _log?.Log(TraceEventType.Verbose, $"Parse of {node.Document.Name}({node.Document.ModuleType}) complete in {(DateTime.Now - _startTime).TotalMilliseconds} ms."); // Now run the analysis. var walker = new ModuleWalker(_services, node.Document, ast); await ast.WalkAsync(walker, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); // Note that we do not set the new analysis here and rather let // Python analyzer to call NotifyAnalysisComplete. await walker.CompleteAsync(cancellationToken); _log?.Log(TraceEventType.Verbose, $"Analysis of {node.Document.Name}({node.Document.ModuleType}) complete in {(DateTime.Now - _startTime).TotalMilliseconds} ms."); return(new DocumentAnalysis(node.Document, analysisVersion, walker.GlobalScope, walker.Ast)); }
private static string GetHidString(SafeFileHandle safeFileHandle, GetString getString, ILogger logger, [CallerMemberName] string callMemberName = null) { try { var pointerToBuffer = Marshal.AllocHGlobal(126); var isSuccess = getString(safeFileHandle, pointerToBuffer, 126); Marshal.FreeHGlobal(pointerToBuffer); if (!isSuccess) { logger?.Log($"Could not get Hid string. Caller: {callMemberName}", nameof(HidAPICalls), null, LogLevel.Warning); } return(Marshal.PtrToStringUni(pointerToBuffer)); } catch (Exception ex) { logger?.Log($"Could not get Hid string. Message: {ex.Message}", nameof(HidAPICalls), ex, LogLevel.Error); return(null); } finally { //TODO: Shouldn't this pointer be released? //Marshal.Release(pointerToBuffer); } }
private async Task <WebItem> GetOrCreateFileAsync(StateSyncEntry entry, SyncGetEntryOptions options) { WebItem item; if (entry.Id == null) { // temporary files are used to move content if (!options.IsTemporary) { return(null); } // get parent path; Guid parentId; var parent = options.JobChange.Change.FilePathSegments.Parent; if (parent == null) { // root parentId = Guid.Empty; } else { // check entry exists. // it should since we init the endpoint synchronizer with UploadsWaitForParents = true var parentEntry = EndPointSynchronizer.StateProvider.GetEntryByFilePath(options.JobChange.DestinationSynchronizer, parent.ToString()); parentId = ToId(parentEntry.Id); } item = await WebApi.GetChildAsync(parentId, entry.Name).ConfigureAwait(false); if (item != null) { return(item); } Logger?.Log(TraceLevel.Warning, "Cannot find temp entry '" + entry.Name + "' with parent id '" + parentId + "'."); if (!options.CanCreate) { return(null); } // create temp files as hidden files return(await WebApi.CreateAsync(parentId, entry.Name, FileAttributes.Hidden).ConfigureAwait(false)); } item = await WebApi.GetAsync(ToId(entry.Id)).ConfigureAwait(false); if (item != null) { return(item); } Logger?.Log(TraceLevel.Warning, "Cannot find entry with id '" + entry.Id + "' name '" + entry.Name + "'."); if (!options.CanCreate) { return(null); } return(await CreateEntryAsync(entry).ConfigureAwait(false)); }
public static INodeViewCustomizations LoadCustomizations(Assembly assem, ILogger logger) { if (cache.ContainsKey(assem)) return cache[assem]; var types = new Dictionary<Type, IEnumerable<Type>>(); try { var customizerType = typeof (INodeViewCustomization<>); var customizerImps = assem.GetTypes().Where(t => !t.IsAbstract && ImplementsGeneric(customizerType, t)); foreach (var customizerImp in customizerImps) { var nodeModelType = GetCustomizerTypeParameters(customizerImp); if (nodeModelType == null) continue; if (types.ContainsKey(nodeModelType)) { types[nodeModelType] = types[nodeModelType].Concat(new[] {customizerImp}); } else { types.Add(nodeModelType, new[] {customizerImp}); } } } catch (Exception ex) { logger.Log(string.Format(Resources.NodeViewCustomizationFindErrorMessage, assem.FullName)); logger.Log(ex.Message); } return new NodeViewCustomizations(types); }
public string GetCacheFilePath(string filePath) { var name = PathUtils.GetFileName(filePath); if (!PathEqualityComparer.IsValidPath(name)) { _log?.Log(TraceEventType.Warning, $"Invalid cache name: {name}"); return(null); } try { var candidate = Path.ChangeExtension(Path.Combine(StubCacheFolder, name), ".pyi"); if (_fs.FileExists(candidate)) { return(candidate); } } catch (ArgumentException) { return(null); } var dir = Path.GetDirectoryName(filePath) ?? string.Empty; if (_fs.StringComparison == StringComparison.OrdinalIgnoreCase) { dir = dir.ToLowerInvariant(); } var dirHash = _cfs.GetFileNameFromContent(dir); var stubFile = Path.Combine(StubCacheFolder, Path.Combine(dirHash, name)); return(Path.ChangeExtension(stubFile, ".pyi")); }
public RemoteConfigManager(IResourceLoader loader, IStorage storage, ILogger logger, RuntimePlatform platform) { this.storage = storage; logger.prefix = "Unibill.RemoteConfigManager"; this.XML = loader.openTextFile ("unibillInventory.json").ReadToEnd (); Config = new UnibillConfiguration(XML, platform, logger); if (Config.UseHostedConfig) { string val = storage.GetString (CACHED_CONFIG_PATH, string.Empty); if (string.IsNullOrEmpty (val)) { logger.Log ("No cached config available. Using bundled"); } else { logger.Log ("Cached config found, attempting to parse"); try { Config = new UnibillConfiguration(val, platform, logger); if (Config.inventory.Count == 0) { logger.LogError ("No purchasable items in cached config, ignoring."); Config = new UnibillConfiguration (XML, platform, logger); } else { logger.Log (string.Format ("Using cached config with {0} purchasable items", Config.inventory.Count)); XML = val; } } catch (Exception e) { logger.LogError ("Error parsing inventory: {0}", e.Message); Config = new UnibillConfiguration(XML, platform, logger); } } refreshCachedConfig (Config.HostedConfigUrl, logger); } else { logger.Log ("Not using cached inventory, using bundled."); Config = new UnibillConfiguration(XML, platform, logger); } }
public void Setup(ILogger logger = null) { logger?.Log($"{ nameof(Injector) } | Configure DI container..."); if (wasCalled) { logger?.Log($"{ nameof(Injector) } | DI container has been already configured, canceling..."); return; } wasCalled = true; container = new StructureMap.Container(); container.Configure(config => { config.Scan(scanner => { logger?.LogToStatusLine($"{ nameof(Injector) } | DI configurator: { scanner.Description }"); scanner.TheCallingAssembly(); scanner.WithDefaultConventions(); scanner.LookForRegistries(); scanner.AssembliesAndExecutablesFromApplicationBaseDirectory(); }); }); // logger?.Log(container.WhatDidIScan()); logger?.Log($"{ nameof(Injector) } | DI container has been configured successfully"); }
private static void LogValidationErrors(ILogger logger, Exception exception) { //Try to find inner validation exception if (exception is AggregateException && exception.InnerException != null) { var aggException = exception as AggregateException; if (aggException.InnerException is AbpValidationException) { exception = aggException.InnerException; } } if (!(exception is AbpValidationException)) { return; } var validationException = exception as AbpValidationException; if (validationException.ValidationErrors.IsNullOrEmpty()) { return; } logger.Log(validationException.Severity, "There are " + validationException.ValidationErrors.Count + " validation errors:"); foreach (var validationResult in validationException.ValidationErrors) { var memberNames = ""; if (validationResult.MemberNames != null && validationResult.MemberNames.Any()) { memberNames = " (" + string.Join(", ", validationResult.MemberNames) + ")"; } logger.Log(validationException.Severity, validationResult.ErrorMessage + memberNames); } }
/// <summary> /// Executes a powershell script /// </summary> /// <param name="folder">Folder where to execute the script</param> /// <param name="file">Script to execute</param> /// <param name="configuration">Configuration used</param> /// <param name="log">Logger to use</param> /// <param name="parameters">Parameters for the script</param> public static void Execute(string folder, string file, string configuration, ILogger log, Dictionary<string, string> parameters) { RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(new Host(), runspaceConfiguration); runspace.Open(); runspace.SessionStateProxy.Path.SetLocation(folder); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); Pipeline pipeline = runspace.CreatePipeline(); Command myCommand = new Command(Path.Combine(folder, file)); foreach (var param in parameters.Keys) { myCommand.Parameters.Add(new CommandParameter("-" + param, parameters[param])); } myCommand.Parameters.Add(new CommandParameter("-Verb", "RunAs")); pipeline.Commands.Add(myCommand); Collection<PSObject> results = new Collection<PSObject>(); try { results = pipeline.Invoke(); } catch (RuntimeException e) { log.Log(String.Join("\r\n", results.Select(x => x.ToString())) + "\r\n" + e.Message.ToString(), true); return; } log.Log(String.Join("\r\n", results.Select(x => x.ToString())), pipeline.Error.Count > 0); }
public int ExecuteDataPlan(nDumpOptions nDumpOptions, ILogger logger, DataPlan dataPlan) { if (nDumpOptions.Export) { var queryExecutor = new QueryExecutor(nDumpOptions.SourceConnectionString); ISelectionFilteringStrategy filteringStrategy = nDumpOptions.ApplyFilters ? (ISelectionFilteringStrategy) new UseFilterIfPresentStrategy(queryExecutor, logger) : new IgnoreFilterStrategy(); var exporter = new SqlDataExporter(logger, nDumpOptions.CsvDirectory, queryExecutor, filteringStrategy); try { exporter.ExportToCsv(dataPlan.SetupScripts, dataPlan.DataSelects); } catch (nDumpApplicationException ex) { logger.Log("Export To Csv Failed.\n" + ex.StackTrace); return -1; } } if (nDumpOptions.Transform) { var transformer = new DataTransformer(nDumpOptions.SqlDirectory, nDumpOptions.CsvDirectory, logger); try { transformer.ConvertCsvToSql(dataPlan.DataSelects); } catch (nDumpApplicationException ex) { logger.Log("Export To Csv Failed.\n" + ex.StackTrace); return -1; } } if (nDumpOptions.Import) { var importer = new SqlDataImporter(logger, new QueryExecutor(nDumpOptions.TargetConnectionString), new IncrementingNumberSqlScriptFileStrategy(nDumpOptions.SqlDirectory)); try { importer.RemoveDataAndImportFromSqlFiles(dataPlan.DataSelects); } catch (nDumpApplicationException ex) { logger.Log("Import Of Sql Failed.\n" + ex.Message + "\n" + ex.StackTrace); return -1; } } return 0; }
public static Dictionary <string, short> GetMappings(string fileName, ILogger?logger) { logger?.Log(LogLevel.Information, $"Creating mappings from file - {fileName}"); var mappings = new NbtFile(fileName); var dictionary = new Dictionary <string, short>(); var mappingCount = (mappings.RootTag["FML"]["ItemData"] as NbtList).Count; for (var index = 0; index < mappingCount; index++) { var tag = (mappings.RootTag["FML"]["ItemData"] as NbtList)[index]; try { dictionary.Add((tag as NbtCompound)["K"].StringValue.Substring(1), (short)(tag as NbtCompound)["V"].IntValue); } catch (Exception) { // ignored } if (index % 500 == 0) { logger?.Log(LogLevel.Information, $"Completed {(int)(index / (double)mappingCount * 100)}%: {index} of {mappingCount}"); } } logger?.Log(LogLevel.Information, "Completed"); return(dictionary); }
public OrdersWatcherManager(IOrdersWatcher ordersWatcher, IInstrumentsNameMapper instrumentsNameMapper, Func <DbContext> contextCreator, IOrderCancelationWatcher orderCancelationWatcher, ILogger logger, IDictionaryModelsMapper dictionaryModelsMapper) { _ordersWatcher = ordersWatcher; _instrumentsNameMapper = instrumentsNameMapper; _contextCreator = contextCreator; _orderCancelationWatcher = orderCancelationWatcher; _dictionaryModelsMapper = dictionaryModelsMapper; _logger = logger ?? new DefaultLogger(); _allOrders = new ConcurrentDictionary <string, OpenOrderModel>(); _ordersWatcher.OnOrderStatusUpdated += (sender, args) => { try { var openOrderStatusUpdateArgs = new OpenOrderStatusUpdateArgs { OrderIdentifier = new OrderIdentifier(args.OrderIdentifier.Value, _instrumentsNameMapper.GetGeneralInstrument(args.OrderIdentifier.Instrument.Name, args.Exchange)), OrderStatus = args.OrderStatus, OpenOrderModel = _allOrders[args.OrderIdentifier.Value] }; Volatile.Read(ref OnOrderStatusUpdated)?.Invoke(this, openOrderStatusUpdateArgs); } catch (Exception e) { _logger?.Log(SeverityLevel.Error, $"Failed to start send update event for Order {args.OrderIdentifier}"); _logger?.Log(SeverityLevel.Error, e); } }; Task.Run(async() => await StartTrackingAllOpenOrders()).Wait(); }
/// <summary> /// Returns null if TargetPackage is null or empty, and /// returns the path to the assembly containing target specific implementations otherwise. /// If a logger is specified, logs suitable diagnostics if a TargetPackages is not null or empty, /// but no path to the target package assembly could be determined. /// This may be the case if no directory at the TargetPackage location exists, or if its files can't be accessed, /// or more than one dll matches the pattern by which the target package assembly is identified. /// </summary> public string GetTargetPackageAssemblyPath(ILogger logger = null) { if (String.IsNullOrEmpty(this.TargetPackage)) { return(null); } try { // Disclaimer: we may revise that in the future. var targetPackageAssembly = Directory.GetFiles(this.TargetPackage, "*Intrinsics.dll", SearchOption.AllDirectories).SingleOrDefault(); if (targetPackageAssembly != null) { return(targetPackageAssembly); } } catch (Exception ex) { if (Directory.Exists(this.TargetPackage)) { logger?.Log(ex); } else { logger?.Log(ErrorCode.CouldNotFindTargetPackage, new[] { this.TargetPackage }); } } logger?.Log(ErrorCode.CouldNotFindTargetPackageAssembly, new[] { this.TargetPackage }); return(null); }
/// <summary> /// Solves system of linear equations Ax=b with Gauss elimination. Leading element is chosen by column /// </summary> /// <param name="systemMatrix">Matrix of the system: A</param> /// <param name="constantVector">Constant vector (right part): b</param> /// <param name="logger">Logger to write messages</param> /// <returns>Solution vector: x</returns> public static Vector Gauss(Matrix systemMatrix, Vector constantVector, ILogger logger = null) { if (systemMatrix.Height != systemMatrix.Width) { throw new ArgumentException("System matrix must be square"); } if (systemMatrix.Height != constantVector.Height) { throw new ArgumentException("Constant vector must have length equal to system matrix size"); } var augmented = CreateAugmentedMatrix(systemMatrix, constantVector); logger?.Log(augmented.Format()); for (var i = 0; i < augmented.GetLength(0); ++i) { MoveMaxValueSubmatrixRowToTop(augmented, i); logger?.Log(augmented.Format()); var divisor = augmented[i, i]; for (var j = i; j < augmented.GetLength(1); ++j) { augmented[i, j] /= divisor; } for (var j = i + 1; j < augmented.GetLength(0); ++j) { var elementToReduce = augmented[j, i]; for (var k = i; k < augmented.GetLength(1); ++k) { augmented[j, k] -= augmented[i, k] * elementToReduce; } } logger?.Log(augmented.Format()); } var solution = new double[systemMatrix.Height]; solution[systemMatrix.Height - 1] = augmented[systemMatrix.Height - 1, systemMatrix.Width]; for (var i = systemMatrix.Height - 2; i >= 0; --i) { var sum = augmented[i, systemMatrix.Width]; for (var j = i + 1; j < systemMatrix.Width; ++j) { sum -= augmented[i, j] * solution[j]; } solution[i] = sum; } return(new Vector(solution)); }
public Task Build(string outputPath, ILogger logger) { var tcs = new TaskCompletionSource<object>(); try { logger.Log("Building solution {0}.", Path.GetFileName(SolutionPath)); string propertyString = GetPropertyString(); if (!String.IsNullOrEmpty(propertyString)) { propertyString = " /p:" + propertyString; } // Build the solution first string log = ExecuteMSBuild(@"""{0}"" /verbosity:m /nologo{1}", SolutionPath, propertyString); logger.Log(log); } catch (Exception ex) { logger.Log("Building solution failed.", LogEntryType.Error); logger.Log(ex); tcs.TrySetException(ex); return tcs.Task; } return BuildProject(outputPath, logger); }
public Task OnReceiveAssociationRequestAsync(FoDicomNetwork.DicomAssociation association) { _associationDataProvider = UserState as IApplicationEntityManager; if (_associationDataProvider is null) { throw new ArgumentNullException("userState must be an instance of IAssociationDataProvider"); } _logger = _associationDataProvider.GetLogger <ScpServiceInternal>(Association.CalledAE); _associationId = _associationDataProvider.NextAssociationNumber(); _associationIdStr = $"#{_associationId} {association.RemoteHost}:{association.RemotePort}"; _loggerScope = _logger?.BeginScope(new Dictionary <string, object> { { "Association", _associationIdStr } }); _logger?.Log(LogLevel.Information, "Association received from {0}:{1}", association.RemoteHost, association.RemotePort); if (!IsValidSourceAe(association.CallingAE)) { return(SendAssociationRejectAsync( FoDicomNetwork.DicomRejectResult.Permanent, FoDicomNetwork.DicomRejectSource.ServiceUser, FoDicomNetwork.DicomRejectReason.CallingAENotRecognized)); } if (!IsValidCalledAe(association.CalledAE)) { return(SendAssociationRejectAsync( FoDicomNetwork.DicomRejectResult.Permanent, FoDicomNetwork.DicomRejectSource.ServiceUser, FoDicomNetwork.DicomRejectReason.CalledAENotRecognized)); } foreach (var pc in association.PresentationContexts) { if (pc.AbstractSyntax == FoDicom.DicomUID.Verification) { if (!_associationDataProvider.Configuration.Value.Dicom.Scp.Verification.Enabled) { _logger?.Log(LogLevel.Warning, "Verification service is disabled: rejecting association"); return(SendAssociationRejectAsync( FoDicomNetwork.DicomRejectResult.Permanent, FoDicomNetwork.DicomRejectSource.ServiceUser, FoDicomNetwork.DicomRejectReason.ApplicationContextNotSupported )); } pc.AcceptTransferSyntaxes(_associationDataProvider.Configuration.Value.Dicom.Scp.Verification.TransferSyntaxes.ToDicomTransferSyntaxArray()); } else if (pc.AbstractSyntax.StorageCategory != FoDicom.DicomStorageCategory.None) { // Accept any proposed TS pc.AcceptTransferSyntaxes(pc.GetTransferSyntaxes().ToArray()); } } return(SendAssociationAcceptAsync(association)); }
/// <summary> /// Solves systems of linear equations AX=B (matrix equation) with Jordan elimination. Leading element is chosen by column /// </summary> /// <param name="systemMatrix">Matrix of the system: A</param> /// <param name="constantMatrix">Constant matrix (right part): B</param> /// <param name="logger">Logger to write messages</param> /// <returns>Solution matrix: X</returns> public static Matrix Jordan(Matrix systemMatrix, Matrix constantMatrix, ILogger logger = null) { if (systemMatrix.Height != systemMatrix.Width) { throw new ArgumentException("System matrix must be square"); } if (systemMatrix.Height != constantMatrix.Height) { throw new ArgumentException("Constant matrix must have height equal to system matrix size"); } var augmented = CreateAugmentedMatrix(systemMatrix, constantMatrix); logger?.Log(augmented.Format()); for (var i = 0; i < augmented.GetLength(0); ++i) { MoveMaxValueSubmatrixRowToTop(augmented, i); logger?.Log(augmented.Format()); var divisor = augmented[i, i]; for (var j = i; j < augmented.GetLength(1); ++j) { augmented[i, j] /= divisor; } for (var j = 0; j < augmented.GetLength(0); ++j) { if (j == i) { continue; } var elementToReduce = augmented[j, i]; for (var k = i; k < augmented.GetLength(1); ++k) { augmented[j, k] -= augmented[i, k] * elementToReduce; } } logger?.Log(augmented.Format()); } var solution = new double[constantMatrix.Height, constantMatrix.Width]; for (var i = 0; i < constantMatrix.Height; ++i) { for (var j = systemMatrix.Width; j < augmented.GetLength(1); ++j) { solution[i, j - systemMatrix.Width] = augmented[i, j]; } } return(new Matrix(solution)); }
public static void ShowResults(this List <Tuple> agendas, ILogger logger) { foreach (var item in agendas.OrderBy(x => x.Wins)) { logger?.Log(item.ToString()); } logger?.Log(""); }
protected override void Run(Workbench workbench, ILogger logger) { string mapFmtName = FindUnnamedParameter(0).Values[0].ToString(); int baseTile = FindNamedParameter("--base-tile").Values[0].ToInt32(); long offset = FindNamedParameter("--offset").Values[0].ToInt64(); int tileCount = FindNamedParameter("--tile-count").Values[0].ToInt32(); if (!(BitmapFormat.GetFormat(mapFmtName) is BitmapFormat mapFmt)) { logger?.Log("Unknown bitmap format \"" + mapFmtName + "\".", LogLevel.Error); return; } if (offset < 0) { logger?.Log("Invalid offset.", LogLevel.Error); return; } if (tileCount < 0) { logger?.Log("Invalid tile count.", LogLevel.Error); return; } workbench.Stream.Position = Math.Min(offset, workbench.Stream.Length); // Bytes per tile entry. int bpe = (mapFmt.Bits + 7) / 8; byte[] buffer = new byte[bpe]; int tn = 0; while (tileCount > 0 && workbench.Stream.Read(buffer, 0, bpe) == bpe) { int scrn = 0; for (int i = 0; i < bpe; i++) { scrn |= buffer[i] << i * 8; } TileEntry te = new TileEntry( tileNumber: mapFmt.BitmapEncoding switch { BitmapEncoding.NintendoDSTexture => tn, _ => ((scrn & mapFmt.TileNumberMask) >> mapFmt.TileNumberShift) } -baseTile, hFlip: mapFmt.CanFlipHorizontal && (scrn & mapFmt.FlipHorizontalMask) != 0, vFlip: mapFmt.CanFlipVertical && (scrn & mapFmt.FlipVerticalMask) != 0, paletteNumber: (scrn & mapFmt.PaletteMask) >> mapFmt.PaletteShift, mode: (scrn & mapFmt.ModeMask) >> mapFmt.ModeShift ); workbench.Tilemap.Add(te); tileCount--; tn++; } workbench.Tilemap.BitmapFormat = mapFmt; }
/// Takes a consumptionTempResults file and converts to csv file /// Each info contains the <ScenarioName, Metric Key, Metric value> public static bool ConvertConsumptionToCsv(string source, string destination, string requiredMetricKey, ILogger logger) { logger.Log("Entering ConvertConsumptionToCsv"); if (!File.Exists(source)) { logger.Log($"File {source} does not exist"); return false; } try { var result = new List<string>(); string currentScenarioName = null; using (XmlReader xmlReader = XmlReader.Create(source)) { while (xmlReader.Read()) { if ((xmlReader.NodeType == XmlNodeType.Element)) { if (xmlReader.Name.Equals("ScenarioResult")) { currentScenarioName = xmlReader.GetAttribute("Name"); // These are not test results if (string.Equals(currentScenarioName, "..TestDiagnostics..")) { currentScenarioName = null; } } else if (currentScenarioName != null && xmlReader.Name.Equals("CounterResult")) { var metricKey = xmlReader.GetAttribute("Name"); if (string.Equals(metricKey, requiredMetricKey)) { var metricScale = xmlReader.GetAttribute("Units"); xmlReader.Read(); var metricvalue = xmlReader.Value; result.Add($"{currentScenarioName}, {metricKey} ({metricScale}), {metricvalue}"); } } } } } File.WriteAllLines(destination, result); } catch (System.Exception e) { System.Console.WriteLine(e.Message); System.Console.WriteLine(e.StackTrace); return false; } return true; }
private async Task StartAsync() { _progress.ReportRemaining(_walker.Remaining); lock (_syncObj) { var notAnalyzed = _walker.AffectedValues.Count(e => e.NotAnalyzed); if (_isCanceled && notAnalyzed < _maxTaskRunning) { _state = State.Completed; return; } } var stopWatch = Stopwatch.StartNew(); foreach (var affectedEntry in _walker.AffectedValues) { affectedEntry.Invalidate(Version); } var originalRemaining = _walker.Remaining; var remaining = originalRemaining; try { _log?.Log(TraceEventType.Verbose, $"Analysis version {Version} of {originalRemaining} entries has started."); remaining = await AnalyzeAffectedEntriesAsync(stopWatch); } finally { stopWatch.Stop(); bool isCanceled; bool isFinal; lock (_syncObj) { isCanceled = _isCanceled; _state = State.Completed; isFinal = _walker.MissingKeys.Count == 0 && !isCanceled && remaining == 0; _walker = null; } if (!isCanceled) { _progress.ReportRemaining(remaining); if (isFinal) { var(modulesCount, totalMilliseconds) = ActivityTracker.EndTracking(); (_analyzer as PythonAnalyzer)?.RaiseAnalysisComplete(modulesCount, totalMilliseconds); _log?.Log(TraceEventType.Verbose, $"Analysis complete: {modulesCount} modules in {totalMilliseconds} ms."); } } } var elapsed = stopWatch.Elapsed.TotalMilliseconds; LogResults(_log, elapsed, originalRemaining, remaining, Version); ForceGCIfNeeded(originalRemaining, remaining); }
protected override bool FileExists(string fullPath) { var result = base.FileExists(fullPath); if (!result) { logger?.Log($"File \"{fullPath}\" doesn't exist!"); } return(result); }
public async Task <ContentResult> Get(string filter = null, string option = null) { bool allowedAccess = await Semaphore.WaitAsync(3000); if (!allowedAccess) { return(Content("Semaphore failed")); } try { var prefix = Prefix; bool isResetFilter = filter == ResetFilterName; bool isJsonFilter = filter == JsonFilterName; if (isResetFilter) { Prefix = null; ServiceProcessor = null; _logger?.Log(LogLevel.Information, "Cache Reset"); return(Content("Resetted")); } if (ServiceProcessor == null) { await initServiceCache(); } ContentResult content = null; if (isJsonFilter) { content = await getJsonContent(option); } else { content = await getPrometheusContent(filter); } return(content); } catch (Exception ex) { ServiceProcessor = null; Prefix = null; _logger.LogCritical(ex, "Unhandled error"); if (filter == DebugFilterName) { var content = Content(ex.ToString()); return(content); } throw; } finally { Semaphore.Release(); } }
private async Task StartAsync() { _progress.ReportRemaining(_walker.Remaining); lock (_syncObj) { var notAnalyzed = _walker.AffectedValues.Count(e => e.NotAnalyzed); if (_isCanceled && notAnalyzed < _maxTaskRunning) { _state = State.Completed; return; } } var stopWatch = Stopwatch.StartNew(); var originalRemaining = _walker.Remaining; var remaining = originalRemaining; try { _log?.Log(TraceEventType.Verbose, $"Analysis version {Version} of {originalRemaining} entries has started."); remaining = await AnalyzeAffectedEntriesAsync(stopWatch); } finally { stopWatch.Stop(); bool isCanceled; bool isFinal; lock (_syncObj) { isCanceled = _isCanceled; _state = State.Completed; isFinal = _walker.MissingKeys.Count == 0 && !isCanceled && remaining == 0; _walker = null; } if (!isCanceled) { _progress.ReportRemaining(remaining); if (isFinal) { var(modulesCount, totalMilliseconds) = ActivityTracker.EndTracking(); totalMilliseconds = Math.Round(totalMilliseconds, 2); (_analyzer as PythonAnalyzer)?.RaiseAnalysisComplete(modulesCount, totalMilliseconds); _log?.Log(TraceEventType.Verbose, $"Analysis complete: {modulesCount} modules in {totalMilliseconds} ms."); //#if DEBUG // var notReady = _analyzer.LoadedModules.Where(m => (m.ModuleType == ModuleType.Library || m.ModuleType == ModuleType.Stub) && m.Analysis is EmptyAnalysis).ToArray(); // Debug.Assert(notReady.Length == 0); //#endif } } } var elapsed = stopWatch.Elapsed.TotalMilliseconds; LogResults(_log, elapsed, originalRemaining, remaining, Version); ForceGCIfNeeded(_log, originalRemaining, remaining, _forceGC); }
public void Print(Printer printer) { logger?.Log("Print started"); var o = new OpenFileDialog(); o.ShowDialog(); var f = File.OpenRead(o.FileName); printer.Print(f); logger?.Log("Print finished"); }
/// <summary> /// Logs the change of the IsBusy state of the database context. /// </summary> /// <param name="logger">The logger.</param> /// <param name="level">The level.</param> /// <param name="isBusy">if set to <c>true</c> [is busy].</param> public static void LogDbCtxIsBusyChanged(this ILogger logger, LogLevel level, bool isBusy) { if (isBusy) { logger?.Log(level, LogEvents.DbCtxIsBusyChanged, "Database context is busy."); } else { logger?.Log(level, LogEvents.DbCtxIsBusyChanged, "Database context is idle."); } }
internal void Log(LogLevel logLevel, string message, Exception exception = default) { if (exception is not null) { logger?.Log(logLevel, message); } else { logger?.Log(logLevel, exception, message); } }
/// <summary> /// Largely synchronous, unfortunately /// </summary> public async Task ConnectAsync(ILogger logger) { logger = logger ?? new StubLogger(); await this.connectLock.WaitAsync(); { logger.Log("Establishing connection with {0}@{1}", this.User, this.Host); if (this.client == null) this.client = new SshClient(this.Host, this.User, new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(this.Key)))); Exception lastException = null; for (int i = 0; i < Retries && !this.client.IsConnected; i++) { try { await Task.Run(() => this.client.Connect()); } catch (SshAuthenticationException e) { var msg = "SSH Authentication error:\n" + e.Format() + "\nMake sure you entered the right SSH user"; logger.Log(msg); throw new Exception(msg, e); } catch (System.Net.Sockets.SocketException e) { lastException = e; } catch (SshException e) { lastException = e; } if (!this.client.IsConnected) logger.Log("Connection attempt failed. Retrying..."); await Task.Delay(5000); } if (this.client.IsConnected) { this.IsConnected = true; logger.Log("Connected"); } else { var msg = "SSH connection failure: " + lastException.Message; logger.Log(msg); throw new Exception(msg, lastException); } } this.connectLock.Release(); }
private async Task StartAsync() { _progress.ReportRemaining(_walker.Remaining); lock (_syncObj) { var notAnalyzed = _walker.AffectedValues.Count(e => e.NotAnalyzed); if (_isCanceled && notAnalyzed < _maxTaskRunning) { _state = State.Completed; return; } } var stopWatch = Stopwatch.StartNew(); var originalRemaining = _walker.Remaining; var remaining = originalRemaining; try { _log?.Log(TraceEventType.Verbose, $"Analysis version {Version} of {originalRemaining} entries has started."); remaining = await AnalyzeAffectedEntriesAsync(stopWatch); Debug.Assert(_ace.Count == 0); } finally { stopWatch.Stop(); var isFinal = false; lock (_syncObj) { if (!_isCanceled) { _progress.ReportRemaining(remaining); } _state = State.Completed; isFinal = _walker.MissingKeys.Count == 0 && !_isCanceled && remaining == 0; _walker = null; } if (isFinal) { var(modulesCount, totalMilliseconds) = ActivityTracker.EndTracking(); totalMilliseconds = Math.Round(totalMilliseconds, 2); if (await _analyzer.RaiseAnalysisCompleteAsync(modulesCount, totalMilliseconds)) { _log?.Log(TraceEventType.Verbose, $"Analysis complete: {modulesCount} modules in {totalMilliseconds} ms."); } } } var elapsed = stopWatch.Elapsed.TotalMilliseconds; LogResults(_log, elapsed, originalRemaining, remaining, Version); ForceGCIfNeeded(_log, originalRemaining, remaining, _forceGC); }
protected override void Run(Workbench workbench, ILogger logger) { string fmtName = FindUnnamedParameter(0).Values[0].ToString(); bool sloppy = FindNamedParameter("--sloppy").IsPresent; if (!(ColorFormat.GetFormat(fmtName) is ColorFormat fmt)) { logger?.Log("Unknown color format \"" + fmtName + "\".", LogLevel.Error); return; } BitmapData bmpData = workbench.Bitmap.LockBits( new Rectangle(0, 0, workbench.Bitmap.Width, workbench.Bitmap.Height), ImageLockMode.ReadWrite, workbench.Bitmap.PixelFormat ); byte[] buffer = new byte[bmpData.Stride * workbench.Bitmap.Height]; Marshal.Copy(bmpData.Scan0, buffer, 0, buffer.Length); int mayNeedSloppy = 0; for (int i = 0; i < buffer.Length; i += 4) { int cb = BitConverter.ToInt32(buffer, i); int ca = fmt.Convert(cb, workbench.BitmapFormat, sloppy); if (!sloppy && fmt.Bits < workbench.BitmapFormat.Bits) { // Convert sloppy and back. int csa = fmt.Convert(cb, workbench.BitmapFormat, true); int csb = workbench.BitmapFormat.Convert(csa, fmt, true); // Check if original color may be sloppy, and this would change the output. if (cb == csb && ca != csa) { mayNeedSloppy++; } } buffer[i + 0] = (byte)(ca >> 0); buffer[i + 1] = (byte)(ca >> 8); buffer[i + 2] = (byte)(ca >> 16); buffer[i + 3] = (byte)(ca >> 24); } Marshal.Copy(buffer, 0, bmpData.Scan0, buffer.Length); workbench.Bitmap.UnlockBits(bmpData); workbench.BitmapFormat = fmt; if (mayNeedSloppy >= workbench.Bitmap.Width * workbench.Bitmap.Height) { logger?.Log("This bitmap appears to be improperly scaled. The --sloppy flag may be required.", LogLevel.Warning); } logger?.Log("Converted bitmap to color format " + fmtName + "."); }
/// <summary> /// Returns a function that given a routine for loading files from disk, /// return an enumerable with all text document identifiers and the corresponding file content /// for the source code or Q# snippet specified by the given options. /// If both the Input and the CodeSnippet property are set, or none of these properties is set in the given options, /// logs a suitable error and returns and empty dictionary. /// </summary> internal CompilationLoader.SourceLoader LoadSourcesOrSnippet (ILogger logger) => loadFromDisk => { bool inputIsEmptyOrNull = this.Input == null || !this.Input.Any(); if (this.CodeSnippet == null && !inputIsEmptyOrNull) { return loadFromDisk(this.Input); } else if (this.CodeSnippet != null && inputIsEmptyOrNull) { return new Dictionary<Uri, string> { { SNIPPET_FILE_URI, AsSnippet(this.CodeSnippet, this.WithinFunction) } }.ToImmutableDictionary(); } if (inputIsEmptyOrNull) logger?.Log(ErrorCode.MissingInputFileOrSnippet, Enumerable.Empty<string>()); else logger?.Log(ErrorCode.SnippetAndInputArguments, Enumerable.Empty<string>()); return ImmutableDictionary<Uri, string>.Empty; };
public void Log(int iteration) { StringBuilder sb = new StringBuilder($"Iteration {iteration}"); foreach (Node node in Nodes) { sb.Append($",{node.Position}"); } _logger?.Log(sb.ToString()); _wsLogger?.Log(this); }
/// <summary> /// Loads the tracks specified by the <paramref name="query"/> asynchronously. /// </summary> /// <param name="query">the search query</param> /// <param name="mode">the track search mode</param> /// <param name="noCache"> /// a value indicating whether the track should be returned from cache, if it is cached. /// Note this parameter does only take any effect is a cache provider is specified in constructor. /// </param> /// <param name="cancellationToken"> /// a cancellation token that can be used by other objects or threads to receive notice /// of cancellation. /// </param> /// <returns> /// a task that represents the asynchronous operation. The task result is the request /// response for the specified <paramref name="query"/>. /// </returns> public async Task <TrackLoadResponsePayload> LoadTracksAsync(string query, SearchMode mode = SearchMode.None, bool noCache = false, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var isUrl = query.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) || query.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase); if (!isUrl) { if (mode == SearchMode.SoundCloud) { query = "scsearch:" + query; } else if (mode == SearchMode.YouTube) { query = "ytsearch:" + query; } } // escape query for passing via URI query = Uri.EscapeDataString(query); // check if a cache provider is specified in constructor and the track request is cached // and caching is wanted (see: "noCache" method parameter) if (_cache != null && !noCache && _cache.TryGetItem <TrackLoadResponsePayload>("track-" + query, out var track)) { _logger?.Log(this, string.Format("Loaded track from cache `{0}`.", query), LogLevel.Debug); return(track); } _logger?.Log(this, string.Format("Loading track '{0}'...", query), LogLevel.Debug); using (var response = await _httpClient.GetAsync($"loadtracks?identifier={query}", cancellationToken)) { VerifyResponse(response); var responseContent = await response.Content.ReadAsStringAsync(); if (_debugPayloads) { _logger?.Log(this, string.Format("Got response for track load: `{0}`: {1}.", query, responseContent), LogLevel.Debug); } var trackLoad = JsonConvert.DeserializeObject <TrackLoadResponsePayload>(responseContent); // cache (if a cache provider is specified) _cache?.AddItem("track-" + query, trackLoad, DateTimeOffset.UtcNow + _cacheTime); return(trackLoad); } }
public static Stream GetResponseStreamWrapped(this WebResponse resp, ILogger logger) { Stream nextStream = resp.GetResponseStream(); using (var rdr = new StreamReader(nextStream)) { var respConent = rdr.ReadToEnd(); if (logger != null ) logger.Log("Response: "); if (logger != null) logger.Log(respConent); return new MemoryStream(Encoding.Default.GetBytes(respConent)); } }
public PowerShellTestContainerDiscoverer( [Import(typeof (SVsServiceProvider))] IServiceProvider serviceProvider, ILogger logger, ISolutionEventsListener solutionListener, ITestFilesUpdateWatcher testFilesUpdateWatcher, ITestFileAddRemoveListener testFilesAddRemoveListener) { _initialContainerSearch = true; _cachedContainers = new List<ITestContainer>(); _serviceProvider = serviceProvider; _logger = logger; _solutionListener = solutionListener; _testFilesUpdateWatcher = testFilesUpdateWatcher; _testFilesAddRemoveListener = testFilesAddRemoveListener; logger.Log(MessageLevel.Diagnostic, "PowerShellTestContainerDiscoverer Constructor Entering"); _testFilesAddRemoveListener.TestFileChanged += OnProjectItemChanged; _testFilesAddRemoveListener.StartListeningForTestFileChanges(); _solutionListener.SolutionUnloaded += SolutionListenerOnSolutionUnloaded; _solutionListener.SolutionProjectChanged += OnSolutionProjectChanged; _solutionListener.StartListeningForChanges(); _testFilesUpdateWatcher.FileChangedEvent += OnProjectItemChanged; }
private static void CalculatePlayerForm(IUnityContainer container, ILogger logger) { logger.Log(Tag.Progress, "Calculating player form (Points per game)"); var playerFormCalculator = container.Resolve<IPlayerFormCalculator>(); var playerPoolReducer = container.Resolve<IPlayerPoolReducer>(); var allPlayers = GetAllPlayers(container, 1); var playerForms = (from player in allPlayers let playerForm = playerFormCalculator.CalculateCurrentPlayerForm(player, allPlayers) select new Tuple<Player, PlayerForm>(player, playerForm)).ToList(); var reducedPlayers = playerPoolReducer.ReducePlayerPool(allPlayers); logger.Log(Tag.Prediction, string.Format("Displaying {0} players considered for initial team selection", reducedPlayers.Count)); foreach (var playerForm in playerForms.Where(pf => reducedPlayers.Contains(pf.Item1)).OrderByDescending(kvp => kvp.Item2.NormalisedPointsPerGame)) { LogPlayerForm(playerForm.Item1, playerForm.Item2, logger); } var ignoredPlayers = allPlayers.Except(reducedPlayers).ToList(); logger.Log(Tag.Prediction, string.Format("Displaying {0} players NOT considered for initial team selection", ignoredPlayers.Count)); foreach (var playerForm in playerForms.Where(pf => ignoredPlayers.Contains(pf.Item1)).OrderByDescending(kvp => kvp.Item2.NormalisedPointsPerGame)) { LogPlayerForm(playerForm.Item1, playerForm.Item2, logger); } }
public static void RunSimulations(SeasonSimulationOptions simulationOptions, IUnityContainer container, ILogger logger) { var stopwatch = new Stopwatch(); stopwatch.Start(); if (!string.IsNullOrWhiteSpace(simulationOptions.StrategyName)) { RegisterStrategyByName(container, simulationOptions.StrategyName); } if(simulationOptions.ListUsage) { ListUsage(); } else if (simulationOptions.CalculateTeamStrengthOnly) { CalculateTeamStrengths(container, logger); } else if (simulationOptions.CalculateHomeAdvantageRatioOnly) { CalculateHomeAdvantageRatio(container, logger); } else if (simulationOptions.CalculatePlayerFormOnly) { CalculatePlayerForm(container, logger); } else { RunSeasonSimulation(container, logger, simulationOptions); } stopwatch.Stop(); logger.Log(Tag.Progress, string.Format("Simulation time: {0}", stopwatch.Elapsed.ToFormatted())); }
private static void Log(ILogger logger, LogLevel logLevel, Func<string> message) { if (logger.IsLoggable(logLevel)) { logger.Log(logLevel, message()); } }
public void Log(string message) { logger = LoggerService.getLoggerService(); logger.OpenLog(); logger.Log(message); logger.CloseLog(); }
public void Log(ILoggerInject loggerInject, string message) { logger = loggerInject.Construct(); logger.OpenLog(); logger.Log(message); logger.CloseLog(); }
public PlaygroundPresenter(IPlaygroundView view) { _view = view; try { //// try some manual detection // ...does not work in Sharepoint integrated mode!!! //var cpa = (IContainerProviderAccessor) HttpContext.Current.ApplicationInstance; //IContainerProvider cp = cpa.ContainerProvider; //_logger = cp.RequestLifetime.Resolve<ILogger>(); // an easier way is: this._logger = SPServiceLocator.GetRequestLifetime().Resolve<ILogger>(); if (!_view.IsPostback) { _logger.Log(typeof (PlaygroundPresenter), "Let's play (now with autofac loaded singleton)"); _view.SuccessMessage = "Let's play!!"; } } catch (Exception ex) { _view.ErrorMessage = "Playground is under construction: " + ex.Message; } }
public MainMenuViewModel(IMenuRegisterService registerService, IMenuFactory menuFactory, ILogger logger) { MenuRegisterService = registerService; _menuFactory = menuFactory; _logger = logger; _logger.Log("Initialized {ClassName:l}", Category.Info, null, GetType().FullName); }
public WurmCharacters([NotNull] IWurmCharacterDirectories characterDirectories, [NotNull] IWurmConfigs wurmConfigs, [NotNull] IWurmServers wurmServers, [NotNull] IWurmServerHistory wurmServerHistory, [NotNull] ILogger logger, [NotNull] TaskManager taskManager) { this.characterDirectories = characterDirectories; this.wurmConfigs = wurmConfigs; this.wurmServers = wurmServers; this.wurmServerHistory = wurmServerHistory; this.logger = logger; this.taskManager = taskManager; if (characterDirectories == null) throw new ArgumentNullException("characterDirectories"); if (wurmConfigs == null) throw new ArgumentNullException("wurmConfigs"); if (wurmServers == null) throw new ArgumentNullException("wurmServers"); if (wurmServerHistory == null) throw new ArgumentNullException("wurmServerHistory"); if (logger == null) throw new ArgumentNullException("logger"); if (taskManager == null) throw new ArgumentNullException("taskManager"); var allChars = characterDirectories.GetAllCharacters(); foreach (var characterName in allChars) { try { Create(characterName); } catch (Exception exception) { logger.Log(LogLevel.Error, "Could not initialize character for name {0}", this, exception); } } }
public void ValidateFileOutput() { logger = FileLogger.Instance(); logger.Log("test"); var isFileExists = File.Exists(AppDomain.CurrentDomain.BaseDirectory + "log.txt"); Assert.IsTrue(isFileExists); }
public string GetEventName(ILogger logger) { if (logger.IsLoggerEnabled) logger.Log("GetEventName method is called"); return "Sample Event"; }
public void Start(string name, ILogger logger) { this.logger = logger; logger.Log("Starting a new stopwatch"); Lap(name); stopwatch.Start(); }
public static void LogException(ILogger logger, Exception ex) { IHasLogSeverity hasLogSeverity = ex as IHasLogSeverity; LogSeverity logSeverity = hasLogSeverity != null ? hasLogSeverity.Severity : LogSeverity.Error; logger.Log(logSeverity, ex.Message, ex); LogValidationErrors(logger, ex); }
public AdvancedCalculatorService(ILogger logger) { if (logger == null) throw new ArgumentNullException("logger"); _logger = logger; _logger.Log("Created instance of AdvancedCalculatorService"); }
protected override void Initialize() { base.Initialize(); logger = Services.GetService<ILogger>(); logger.Log(LogLevels.Standard, "Loaded Components"); }
public MainApplication(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { _logger = new Logger(); Insights.Initialize(Settings.XamarinInsightsApiKey, ApplicationContext); AndroidEnvironment.UnhandledExceptionRaiser += (sender, args) => { args.Handled = false; _logger.Log(args.Exception as Exception, LogType.ERROR); }; AppDomain.CurrentDomain.UnhandledException += (s, e) => { _logger.Log(e.ExceptionObject as Exception, LogType.ERROR); }; }
public async Task HandleAutoSwap(string currentDeploymetId, ILogger logger, ITracer tracer) { if (!IsAutoSwapEnabled()) { tracer.Trace("AutoSwap is not enabled"); return; } string jwtToken = System.Environment.GetEnvironmentVariable(Constants.SiteRestrictedJWT); if (string.IsNullOrWhiteSpace(jwtToken)) { tracer.Trace("Jwt token is null"); return; } try { FileSystemHelpers.WriteAllTextToFile(_autoSwapLockFilePath, String.Empty); } catch (Exception ex) { tracer.TraceError(ex); } string operationId = "AUTOSWAP" + Guid.NewGuid(); var queryStrings = HttpUtility.ParseQueryString(string.Empty); queryStrings["slot"] = _autoSwapSlotName; queryStrings["operationId"] = operationId; var client = new OperationClient(tracer); await client.PostAsync<string>("/operations/autoswap?" + queryStrings.ToString()); logger.Log("Requesting auto swap to slot - '{0}' operation id - '{1}' deployment id - '{2}'".FormatInvariant(_autoSwapSlotName, operationId, currentDeploymetId)); }