Exemple #1
0
        public async static Task <IImmutableList <SyntaxNode> > GenerateMocksAsync(
            ILogSink logSink,
            Language language,
            string solutionPath,
            string xmlPath)
        {
            if (!File.Exists(xmlPath))
            {
                var message = $"XML input file '{xmlPath}' no found.";
                logSink.Error(logSource, message);
                throw new IOException(message);
            }

            logSink.Info(logSource, "Loading XML input file '{0}'.", xmlPath);

            var document      = XDocument.Load(xmlPath);
            var configuration = Configuration.FromXDocument(logSink, document);

            return(await Generator.GenerateMocksAsync(
                       logSink,
                       language,
                       solutionPath,
                       configuration.GetInterfacePredicate(),
                       configuration.GetNamespaceSelector(),
                       configuration.GetNameSelector(),
                       configuration.GetPlugins()));
        }
Exemple #2
0
 private static void LogMessage(MessageLevel level, string text, ILogSink logger)
 {
     if (!string.IsNullOrWhiteSpace(text))
     {
         logger.Log(level, text);
     }
 }
Exemple #3
0
        public async Task WriteAsync(ILog log, byte[] logData)
        {
            List <Exception> exceptions    = new List <Exception>();
            ILogSink         activeLogSink = null;

            foreach (var logSink in _logSinks)
            {
                try
                {
                    activeLogSink = logSink;
                    await activeLogSink.WriteAsync(log, logData);

                    break;
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }
            }

            if (exceptions.Count > 0 && activeLogSink != null)
            {
                await WriteExceptionsAsync(activeLogSink, log, exceptions);
            }
        }
Exemple #4
0
 private static void ValidateLogger(ILogSink logger)
 {
     if (logger == null)
     {
         throw new ArgumentNullException("logger");
     }
 }
        public EpoxyTransport(
            ILayerStackProvider layerStackProvider,
            Func <string, Task <IPAddress> > resolver,
            EpoxyServerTlsConfig serverTlsConfig,
            EpoxyClientTlsConfig clientTlsConfig,
            TimeoutConfig timeoutConfig,
            ILogSink logSink, bool enableDebugLogs,
            IMetricsSink metricsSink)
        {
            // Layer stack provider may be null
            this.layerStackProvider = layerStackProvider;

            // Always need a resolver, so substitute in default if given null
            this.resolver = resolver ?? ResolveViaDnsAsync;

            // may be null - indicates no TLS for listeners
            this.serverTlsConfig = serverTlsConfig;

            // Client-side TLS is determined by how the connection is
            // established, so we substitute in the Default TLS config if we
            // happened to get null
            this.clientTlsConfig = clientTlsConfig ?? EpoxyClientTlsConfig.Default;

            this.timeoutConfig = timeoutConfig;

            // Log sink may be null
            logger = new Logger(logSink, enableDebugLogs);
            // Metrics sink may be null
            metrics = new Metrics(metricsSink);

            connections = new CleanupCollection <EpoxyConnection>();
            listeners   = new CleanupCollection <EpoxyListener>();
        }
Exemple #6
0
        private void SinkFromFactory(SinkData sink)
        {
            LogSinkFactory factory = new LogSinkFactory(Context);
            ILogSink       output  = factory.CreateSink(sink.Name);

            Assert.IsNotNull(output);
        }
Exemple #7
0
 private static IEnumerable <SyntaxNode> GetMemberDeclarations(
     ILogSink logSink,
     SyntaxGenerator syntaxGenerator,
     SemanticModel semanticModel,
     string name,
     INamedTypeSymbol interfaceSymbol,
     Language language,
     IImmutableList <IPlugin> plugins)
 {
     return
         (new SyntaxNode[]
     {
         GetConstructorDeclarationSyntax(syntaxGenerator, semanticModel, name),
         GetConfigureBehaviorGeneratedSyntax(logSink, syntaxGenerator, semanticModel, interfaceSymbol, plugins),
         GetConfigureLooseBehaviorGeneratedSyntax(logSink, syntaxGenerator, semanticModel, interfaceSymbol, plugins),
         GetConfigureBehaviorMethodSyntax(language, syntaxGenerator, semanticModel),
         GetConfigureLooseBehaviorMethodSyntax(language, syntaxGenerator, semanticModel)
     }
          .Concat(
              GetMembersRecursive(interfaceSymbol)
              .Select(x => GetMemberDeclarationSyntax(syntaxGenerator, semanticModel, x))
              .Where(x => x != null)
              .GroupBy(x => x, SyntaxNodeEqualityComparer.Instance)
              .Where(group => group.Count() == 1)
              .SelectMany(group => group)
              .Select(x => syntaxGenerator.AsPublicInterfaceImplementation(x, syntaxGenerator.TypeExpression(interfaceSymbol)))));
 }
Exemple #8
0
        public static void LogException <TIn1>(this ILogSink logger, string areaMethodName, TIn1 source, Type errorType, params object[] areaMethodParams)
        {
            string messageTemplate = GetMessageTemplate(areaMethodParams);

            logger.Log(LogEventLevel.Error, areaMethodName, source, messageTemplate,
                       errorType.Name, string.Join(Environment.NewLine, areaMethodParams.ToJsonStrings()));
        }
        public static void RedirectLogs(ILogSink logSink, out IReadOnlyDictionary <Type, LogSourceNameCompositionLogSink> redirectionLogSinks)
        {
            var redirectionSinks = new Dictionary <Type, LogSourceNameCompositionLogSink>(capacity: 2);

            {
                Type         loggerType = typeof(global::Samples.WindowsService01.Log);
                const string logComponentGroupMoniker = "Samples.WindowsService01";

                if (logSink == null)
                {
                    redirectionSinks[loggerType] = null;
                    global::Samples.WindowsService01.Log.Configure.EventHandlers.Error(null);
                    global::Samples.WindowsService01.Log.Configure.EventHandlers.Info(null);
                    global::Samples.WindowsService01.Log.Configure.EventHandlers.Debug(null);
                }
                else
                {
                    var redirectionLogSink = new LogSourceNameCompositionLogSink(logComponentGroupMoniker, logSink);
                    var logToSinkAdapter   = new LogEventHandlersToLogSinkAdapter(redirectionLogSink);
                    redirectionSinks[loggerType] = redirectionLogSink;
                    global::Samples.WindowsService01.Log.Configure.EventHandlers.Error(logToSinkAdapter.Error);
                    global::Samples.WindowsService01.Log.Configure.EventHandlers.Info(logToSinkAdapter.Info);
                    global::Samples.WindowsService01.Log.Configure.EventHandlers.Debug(logToSinkAdapter.Debug);
                }

                Samples.WindowsService01.Log.Configure.DebugLoggingEnabled(IsDebugLoggingEnabled);
            }

            redirectionLogSinks = redirectionSinks;
        }
Exemple #10
0
        private static bool TryGetReturnValueSyntaxForImmutableStackReturnType(
            ILogSink logSink,
            SyntaxGenerator syntaxGenerator,
            SemanticModel semanticModel,
            INamedTypeSymbol returnType,
            out SyntaxNode returnValueSyntax)
        {
            var immutableStackInterfaceType = semanticModel
                                              .Compilation
                                              .GetTypeByMetadataName("System.Collections.Immutable.IImmutableStack`1");

            if (returnType.ConstructedFrom != immutableStackInterfaceType)
            {
                returnValueSyntax = null;
                return(false);
            }

            var immutableStackType = semanticModel
                                     .Compilation
                                     .GetTypeByMetadataName("System.Collections.Immutable.ImmutableStack");

            if (immutableStackType == null)
            {
                logSink.Warn(logSource, "Failed to resolve ImmutableStack class.");
                returnValueSyntax = null;
                return(false);
            }

            returnValueSyntax = syntaxGenerator.MemberAccessExpression(
                syntaxGenerator.WithTypeArguments(
                    syntaxGenerator.TypeExpression(immutableStackType),
                    syntaxGenerator.TypeExpression(returnType.TypeArguments[0])),
                "Empty");
            return(true);
        }
Exemple #11
0
        public TfsSourceControlClient(string projectCollectionUrl, string userName, string password, string domain, ILogSink log)
        {
            var uri = new Uri(projectCollectionUrl, UriKind.Absolute);

            if (string.IsNullOrEmpty(userName))
            {
                this.collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(uri);
            }
            else
            {
                TfsClientCredentials credentials;
                if (string.IsNullOrEmpty(domain))
                {
                    credentials = new TfsClientCredentials(new BasicAuthCredential(new NetworkCredential(userName, password)));
                }
                else
                {
                    credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(userName, password, domain)));
                }

                this.collection = new TfsTeamProjectCollection(uri, credentials);
            }

            this.log = log;
        }
Exemple #12
0
        private static bool TryGetReturnValueSyntaxForSetReturnType(
            ILogSink logSink,
            SyntaxGenerator syntaxGenerator,
            SemanticModel semanticModel,
            INamedTypeSymbol returnType,
            out SyntaxNode returnValueSyntax)
        {
            var setInterfaceType = semanticModel
                                   .Compilation
                                   .GetTypeByMetadataName("System.Collections.Generic.ISet`1");

            if (returnType.ConstructedFrom != setInterfaceType)
            {
                returnValueSyntax = null;
                return(false);
            }

            var dictionaryType = semanticModel
                                 .Compilation
                                 .GetTypeByMetadataName("System.Collections.Generic.HashSet`1");

            if (dictionaryType == null)
            {
                logSink.Warn(logSource, "Failed to resolve HashSet<T> class.");
                returnValueSyntax = null;
                return(false);
            }

            returnValueSyntax = syntaxGenerator.ObjectCreationExpression(
                dictionaryType.Construct(returnType.TypeArguments[0])).NormalizeWhitespace();
            return(true);
        }
Exemple #13
0
        internal static async Task WrapInVirtualEnv(ILogSink logger, IOperationExecutionContext context, RemoteProcessStartInfo startInfo, string pythonExePath, string virtualEnv)
        {
            if (string.IsNullOrEmpty(virtualEnv))
            {
                return;
            }

            var fileOps = await context.Agent.GetServiceAsync <IFileOperationsExecuter>();

            if (!await fileOps.DirectoryExistsAsync(virtualEnv))
            {
                var procExec = await context.Agent.GetServiceAsync <IRemoteProcessExecuter>();

                logger.LogDebug($"Virtual environment in {virtualEnv} is not present. Attempting venv (Python 3.3+)...");
                var success = false;
                using (var process = procExec.CreateProcess(new RemoteProcessStartInfo
                {
                    FileName = pythonExePath,
                    WorkingDirectory = context.WorkingDirectory,
                    Arguments = "-m venv -- " + virtualEnv,
                }))
                {
                    process.OutputDataReceived += (s, e) => logger.LogDebug("(venv) " + e.Data);
                    process.ErrorDataReceived  += (s, e) => logger.LogDebug("(venv) " + e.Data);
                    await process.WaitAsync(context.CancellationToken);

                    success = process.ExitCode == 0;
                }

                if (!success)
                {
                    logger.LogDebug("Attempting virtualenv (any Python version, but requires separate installation)...");
                    using var process = procExec.CreateProcess(
                              new RemoteProcessStartInfo
                    {
                        FileName             = "virtualenv",
                        WorkingDirectory     = context.WorkingDirectory,
                        Arguments            = "-- " + virtualEnv,
                        EnvironmentVariables =
                        {
                            ["VIRTUALENV_PYTHON"] = pythonExePath
                        }
                    }
                              );

                    process.OutputDataReceived += (s, e) => logger.LogDebug("(virtualenv) " + e.Data);
                    process.ErrorDataReceived  += (s, e) => logger.LogDebug("(virtualenv) " + e.Data);
                    await process.WaitAsync(context.CancellationToken);

                    success = process.ExitCode == 0;
                }

                if (!success)
                {
                    throw new ExecutionFailureException("Could not create a virtual environment. See debug logs from this operation for more information.");
                }
            }

            startInfo.FileName = (await fileOps.GetFileInfoAsync(fileOps.CombinePath(virtualEnv, "bin", "python"))).FullName;
        }
Exemple #14
0
 /// <summary>
 /// Replaces this context's log sink with <paramref name="logSink"/>.
 /// </summary>
 /// <param name="logSink">
 /// The new log sink.
 /// </param>
 /// <returns>
 /// The new context.
 /// </returns>
 public Context WithLogSink(ILogSink logSink) =>
 new Context(
     logSink,
     this.language,
     this.plugins,
     this.syntaxGenerator,
     this.semanticModel);
 /// <summary>
 /// Registers the provided log sink.
 /// </summary>
 /// <param name="sink">The log sink.</param>
 public void RegisterLogSink(ILogSink sink)
 {
     if (null != sink)
     {
         this.AttachedLoggers.Add(sink);
     }
 }
Exemple #16
0
 public static void RemoveLogSink(ILogSink logSink)
 {
     lock (m_lock)
     {
         m_logSinks.Remove(logSink);
     }
 }
Exemple #17
0
        public static IImmutableList <SyntaxNode> GenerateMocks(
            ILogSink logSink,
            Language language,
            IImmutableList <Compilation> compilations,
            string xmlPath)
        {
            logSink = logSink
                      .WithSource(typeof(XmlBasedGenerator));

            if (!File.Exists(xmlPath))
            {
                logSink.Error("XML input file '{0}' not found.", xmlPath);
                return(ImmutableList <SyntaxNode> .Empty);
            }

            logSink.Info("Loading XML input file '{0}'.", xmlPath);

            var document      = XDocument.Load(xmlPath);
            var configuration = Configuration.FromXDocument(logSink, document);

            return(Generator.GenerateMocks(
                       logSink,
                       language,
                       compilations,
                       configuration.GetPlugins(),
                       configuration.GetInterfacePredicate(),
                       configuration.GetNamespaceSelector(),
                       configuration.GetNameSelector()));
        }
Exemple #18
0
 private MappedWorkspace(Workspace workspace, string diskPath, bool deleteOnDispose, ILogSink log)
 {
     this.Workspace       = workspace;
     this.DiskPath        = diskPath;
     this.DeleteOnDispose = deleteOnDispose;
     this.log             = log;
 }
Exemple #19
0
 /// <inheritdoc />
 public SyntaxNode GenerateConfigureLooseBehavior(
     ILogSink logSink,
     SyntaxGenerator syntaxGenerator,
     SemanticModel semanticModel,
     ISymbol symbol)
 {
     return(null);
 }
Exemple #20
0
 public LogEvent(string ipAddress, string user, string topic, LogEventType type, ILogSink sink)
 {
     IP = ipAddress;
     User = user;
     Topic = topic;
     Type = type;
     Sink = sink;
 }
Exemple #21
0
        public LogEventHandlersToLogSinkAdapter(ILogSink targetLogSink)
        {
            if (targetLogSink == null)
            {
                throw new ArgumentNullException(nameof(targetLogSink));
            }

            _targetLogSink = targetLogSink;
        }
Exemple #22
0
 public SvnClient(UsernamePasswordCredentials credentials, Agent agent, string svnExePath, ILogSink log, CancellationToken?cancellationToken = null)
 {
     this.execOps           = new Lazy <IRemoteProcessExecuter>(() => agent.GetService <IRemoteProcessExecuter>());
     this.userName          = credentials?.UserName;
     this.password          = credentials?.Password;
     this.svnExePath        = AH.CoalesceString(svnExePath, RemoteMethods.GetEmbeddedSvnExePath(agent));
     this.log               = log ?? (ILogSink)Logger.Null;
     this.cancellationToken = cancellationToken ?? CancellationToken.None;
 }
Exemple #23
0
 internal SvnClient(UsernamePasswordCredentials credentials, IRemoteProcessExecuter execOps, string svnExePath, ILogSink log, CancellationToken?cancellationToken = null)
 {
     this.execOps           = new Lazy <IRemoteProcessExecuter>(() => execOps);
     this.userName          = credentials?.UserName;
     this.password          = credentials?.Password;
     this.svnExePath        = svnExePath;
     this.log               = log ?? (ILogSink)Logger.Null;
     this.cancellationToken = cancellationToken ?? CancellationToken.None;
 }
Exemple #24
0
        private static bool TryDisposeLogSink(ILogSink logSink)
        {
            if (logSink is IDisposable disposableLogSink)
            {
                disposableLogSink.Dispose();
            }

            return(true);
        }
Exemple #25
0
 public JenkinsClient(string username, SecureString password, string serverUrl, bool csrfProtectionEnabled, ILogSink logger = null, CancellationToken cancellationToken = default)
 {
     this.username              = username;
     this.password              = password;
     this.serverUrl             = serverUrl;
     this.csrfProtectionEnabled = csrfProtectionEnabled;
     this.logger            = logger;
     this.cancellationToken = cancellationToken;
 }
        public SimplerAsyncLog(ILogSink sink)
        {
            this._sink = sink;

            this._tokenSource = new CancellationTokenSource();
            this._mainLoop    = new Task(() => this.MainLoop(this._tokenSource.Token), this._tokenSource.Token);

            this._mainLoop.Start();
        }
Exemple #27
0
        public static IisVirtualDirectoryConfiguration FromMwaVirtualDirectory(ILogSink logger, string siteName, VirtualDirectory vdir, IisVirtualDirectoryConfiguration template = null)
        {
            var config = new IisVirtualDirectoryConfiguration();

            config.SiteName        = siteName;
            config.ApplicationPath = template?.ApplicationPath;
            config.SetPropertiesFromMwa(logger, vdir, template);
            return(config);
        }
 public ImportFilesService(
     IHostApplicationLifetime hostApplicationLifetime,
     IImportFilesWorker importFilesWorker,
     ILogSink logger)
 {
     _hostApplicationLifetime = hostApplicationLifetime;
     _importFilesWorker       = importFilesWorker;
     _logger = logger;
 }
Exemple #29
0
 public static void AddLogSink(ILogSink logSink)
 {
     lock (m_lock)
     {
         if (!m_logSinks.Contains(logSink))
         {
             m_logSinks.Add(logSink);
         }
     }
 }
        public static IisApplicationConfiguration FromMwaApplication(ILogSink logger, string siteName, Application app, IisApplicationConfiguration template = null)
        {
            var config = new IisApplicationConfiguration();

            config.SiteName            = siteName;
            config.ApplicationPath     = app.Path;
            config.ApplicationPoolName = app.ApplicationPoolName;
            config.SetPropertiesFromMwa(logger, app.VirtualDirectories["/"], template);
            return(config);
        }
            public RemoteTemporaryFile(IFileOperationsExecuter fileOps, ILogSink log)
            {
                this.fileOps = fileOps;
                this.log     = log;

                string workingDirectory = fileOps.GetBaseWorkingDirectory();
                string fileName         = Guid.NewGuid().ToString("n");

                this.Path = fileOps.CombinePath(workingDirectory, fileName);
            }
        private async Task<EpoxyTransport> Server(
            ILogSink logSink, IMetricsSink metricsSink,
            IPEndPoint endPoint)
        {
            var transport = new EpoxyTransportBuilder()
                .SetLogSink(logSink)
                .SetMetricsSink(metricsSink)
                .Construct();

            var service = new DummyTestService();
            var listener = transport.MakeListener(endPoint);
            listeners.Add(listener);
            listener.AddService(service);
            await listener.StartAsync();

            return transport;
        }
Exemple #33
0
 public Logger(ILogSink logSink)
 {
     _sinks.Add(logSink);
 }
		public LoggerFactory (ILogSink logSink)
		{
			_logSink = logSink;
		}
Exemple #35
0
 public void Add(ILogSink logSink)
 {
     _sinks.Add(logSink);
 }
		public LoggerMiddleware(AppFunc next, ILogSink logger, IEnvironmentFormatter formatter)
		{
			_next = next;
			_logger = logger;
			_formatter = formatter ?? new EnvironmentFormatter();
		}
Exemple #37
0
 public static void RemoveSink(ILogSink sink)
 {
     lock (Sinks)
         Sinks.Remove(sink);
 }
Exemple #38
0
		public Log (string name, ILogSink logSink)
		{
			_name = name;
			_logSink = logSink;
		}
		public LoggerOwinMiddleware(OwinMiddleware next, ILogSink logger) : this(next, logger, null)
		{
		}
Exemple #40
0
 public ExceptionHandler(ILogSink log)
 {
     this.log = log;
 }
		public LoggerOwinMiddleware(OwinMiddleware next, ILogSink logger, IOwinContextFormatter formatter)
			: base(next)
		{
			_logger = logger;
			_formatter = formatter ?? new OwinContextFormatter();
		}
Exemple #42
0
 public Logger(ILogSink sink, bool includeDebug)
 {
     Sink = sink;
     IncludeDebug = includeDebug;
 }
Exemple #43
0
 public static void AddSink(ILogSink sink)
 {
     lock (Sinks)
         Sinks.Add(sink);
 }
		public LoggerMiddleware(AppFunc next, ILogSink logger) : this(next, logger, null)
		{
		}
 public void AddLogSink(ILogSink logSink)
 {
 }