Ejemplo n.º 1
1
        public Connection(IMessageBus newMessageBus,
                          IJsonSerializer jsonSerializer,
                          string baseSignal,
                          string connectionId,
                          IList<string> signals,
                          IList<string> groups,
                          ITraceManager traceManager,
                          IAckHandler ackHandler,
                          IPerformanceCounterManager performanceCounterManager,
                          IProtectedData protectedData)
        {
            if (traceManager == null)
            {
                throw new ArgumentNullException("traceManager");
            }

            _bus = newMessageBus;
            _serializer = jsonSerializer;
            _baseSignal = baseSignal;
            _connectionId = connectionId;
            _signals = new List<string>(signals.Concat(groups));
            _groups = new DiffSet<string>(groups);
            _traceSource = traceManager["SignalR.Connection"];
            _ackHandler = ackHandler;
            _counters = performanceCounterManager;
            _protectedData = protectedData;
        }
Ejemplo n.º 2
0
        public ObservableDbOperation(string connectionString, string commandText, TraceSource traceSource, IDbProviderFactory dbProviderFactory, IDbBehavior dbBehavior)
            : base(connectionString, commandText, traceSource, dbProviderFactory)
        {
            _dbBehavior = dbBehavior ?? this;

            InitEvents();
        }
Ejemplo n.º 3
0
        public ObservableDbOperation(string connectionString, string commandText, TraceSource traceSource, params IDataParameter[] parameters)
            : base(connectionString, commandText, traceSource, parameters)
        {
            _dbBehavior = this;

            InitEvents();
        }
Ejemplo n.º 4
0
    protected void submitCodeBehindButton_Click(object sender, EventArgs e)
    {
        System.Diagnostics.TraceSource source =
            new System.Diagnostics.TraceSource(sourceTextBox.Text);

        source.TraceData(System.Diagnostics.TraceEventType.Error, 100, "Test from the code behind");
    }
        protected TransportDisconnectBase(HostContext context, ITransportHeartbeat heartbeat, IPerformanceCounterManager performanceCounterManager, ITraceManager traceManager)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (heartbeat == null)
            {
                throw new ArgumentNullException("heartbeat");
            }

            if (performanceCounterManager == null)
            {
                throw new ArgumentNullException("performanceCounterManager");
            }

            if (traceManager == null)
            {
                throw new ArgumentNullException("traceManager");
            }

            _context = context;
            _heartbeat = heartbeat;
            _counters = performanceCounterManager;

            // Queue to protect against overlapping writes to the underlying response stream
            WriteQueue = new TaskQueue();

            _trace = traceManager["SignalR.Transports." + GetType().Name];
        }
Ejemplo n.º 6
0
 public SqlInstaller(string connectionString, string tableNamePrefix, int tableCount, TraceSource traceSource)
 {
     _connectionString = connectionString;
     _messagesTableNamePrefix = tableNamePrefix;
     _tableCount = tableCount;
     _trace = traceSource;
 }
Ejemplo n.º 7
0
        public ScaleoutStreamManager(Func<int, IList<Message>, Task> send,
                                     Action<int, ulong, ScaleoutMessage> receive,
                                     int streamCount,
                                     TraceSource trace,
                                     IPerformanceCounterManager performanceCounters,
                                     ScaleoutConfiguration configuration)
        {
            if (configuration.QueueBehavior != QueuingBehavior.Disabled && configuration.MaxQueueLength == 0)
            {
                throw new InvalidOperationException(Resources.Error_ScaleoutQueuingConfig);
            }

            _streams = new ScaleoutStream[streamCount];
            _send = send;
            _receive = receive;

            var receiveMapping = new ScaleoutMappingStore[streamCount];

            performanceCounters.ScaleoutStreamCountTotal.RawValue = streamCount;
            performanceCounters.ScaleoutStreamCountBuffering.RawValue = streamCount;
            performanceCounters.ScaleoutStreamCountOpen.RawValue = 0;

            for (int i = 0; i < streamCount; i++)
            {
                _streams[i] = new ScaleoutStream(trace, "Stream(" + i + ")", configuration.QueueBehavior, configuration.MaxQueueLength, performanceCounters);
                receiveMapping[i] = new ScaleoutMappingStore();
            }

            Streams = new ReadOnlyCollection<ScaleoutMappingStore>(receiveMapping);
        }
Ejemplo n.º 8
0
 public SqlSender(string connectionString, string tableName, TraceSource traceSource, IDbProviderFactory dbProviderFactory)
 {
     _connectionString = connectionString;
     _insertDml = BuildInsertString(tableName);
     _trace = traceSource;
     _dbProviderFactory = dbProviderFactory;
 }
Ejemplo n.º 9
0
        public GSM_SMS()
        {
            //spDriver = new SerialPortDriver();
            spDriver = new SerialPortDriver(9600, 8, StopBits.One, Parity.None, Handshake.None);



            responseTimeout = int.Parse(ConfigurationSettings.AppSettings["ResponseTimeout"]);

            transactionTimer = new System.Timers.Timer(responseTimeout);
            transactionTimer.Elapsed += new ElapsedEventHandler(transactionTimeout);
            transactionTimer.AutoReset = false;

            transactionEvent = new AutoResetEvent(false);

            _gsmSMSTrace = new TraceSource("GSM_SMSTrace");
            _gsmSMSTrace.Switch = new SourceSwitch("GSM_SMSTraceSwitch");


            String gsmSMSTraceFile = ConfigurationSettings.AppSettings["GSM_SMSTraceFile"];

            if (gsmSMSTraceFile != String.Empty && gsmSMSTraceFile!= null)
            {
                _gsmSMSTraceListener = new TextWriterTraceListener(gsmSMSTraceFile);
                _gsmSMSTrace.Listeners.Add(_gsmSMSTraceListener);
                _gsmSMSTrace.Switch.Level = SourceLevels.Information;
            }
            else
            {
                _gsmSMSTrace.Switch.Level = SourceLevels.Off;
            }
        }
Ejemplo n.º 10
0
 RMQServiceBusInterface( ServiceBusClient dispatcher, TraceSource tracer )
 {
     if (dispatcher == null)
         throw new ArgumentNullException("entity");
     Process = dispatcher;
     this.Tracer = tracer;
 }
        private DiagnosticsTraceSource InitializeTraceSource(string traceSourceName)
        {
            var    traceSource      = new DiagnosticsTraceSource(traceSourceName);
            string?parentSourceName = ParentSourceName(traceSourceName);

            if (string.IsNullOrEmpty(parentSourceName))
            {
                if (HasDefaultSwitch(traceSource))
                {
                    traceSource.Switch = _rootSourceSwitch;
                }

                if (_rootTraceListener != null)
                {
                    traceSource.Listeners.Add(_rootTraceListener);
                }
            }
            else
            {
                if (HasDefaultListeners(traceSource))
                {
                    DiagnosticsTraceSource parentTraceSource = GetOrAddTraceSource(parentSourceName);
                    traceSource.Listeners.Clear();
                    traceSource.Listeners.AddRange(parentTraceSource.Listeners);
                }

                if (HasDefaultSwitch(traceSource))
                {
                    DiagnosticsTraceSource parentTraceSource = GetOrAddTraceSource(parentSourceName);
                    traceSource.Switch = parentTraceSource.Switch;
                }
            }

            return(traceSource);
        }
        public ServiceBusConnectionContext(ServiceBusScaleoutConfiguration configuration,
                                           IList<string> topicNames,
                                           TraceSource traceSource,
                                           Action<int, IEnumerable<BrokeredMessage>> handler,
                                           Action<int, Exception> errorHandler,
                                           Action<int> openStream)
        {
            if (topicNames == null)
            {
                throw new ArgumentNullException("topicNames");
            }

            _configuration = configuration;

            _subscriptions = new SubscriptionContext[topicNames.Count];
            _topicClients = new TopicClient[topicNames.Count];

            _trace = traceSource;

            TopicNames = topicNames;
            Handler = handler;
            ErrorHandler = errorHandler;
            OpenStream = openStream;

            TopicClientsLock = new object();
            SubscriptionsLock = new object();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Constructor used to initialize the class
        /// </summary>
        /// <param name="traceSource">The source that we are tracing through as part of this scope</param>
        /// <param name="activityName">The name of the activity that this scope represents</param>
        public TraceTransferScope(TraceSource traceSource, string activityName)
        {
            if (traceSource == null)
            {
                throw new ArgumentNullException("traceSource");
            }

            if (string.IsNullOrEmpty(activityName))
            {
                throw new ArgumentNullException("activityName");
            }

            _traceSource = traceSource;
            _oldActivityId = Trace.CorrelationManager.ActivityId;
            _activityName = activityName;

            _newActivityId = Guid.NewGuid();

            if (_oldActivityId != Guid.Empty)
            {
                // transfer to activity
                _traceSource.TraceTransfer(0, string.Format(CultureInfo.CurrentCulture, "TRANSFER ==> {0} ===", _activityName), _newActivityId);
            }
            Trace.CorrelationManager.ActivityId = _newActivityId;

            _traceSource.Start(_activityName);
        }
 public void SetUp()
 {
     source = new TraceSource("unnamed", SourceLevels.All);
     tempFileName = Path.GetTempFileName();
     xmlTraceListener = new XmlTraceListener(tempFileName);
     source.Listeners.Add(xmlTraceListener);
 }
        private TraceSource InitializeTraceSource(string traceSourceName)
        {
            var traceSource = new TraceSource(traceSourceName);
            if (traceSourceName == RootTraceName)
            {
                if (HasDefaultSwitch(traceSource))
                {
                    traceSource.Switch = _rootSourceSwitch;
                }
                if (_rootTraceListener != null)
                {
                    traceSource.Listeners.Add(_rootTraceListener);
                }
            }
            else
            {
                string parentSourceName = ParentSourceName(traceSourceName);
                if (HasDefaultListeners(traceSource))
                {
                    TraceSource parentTraceSource = GetOrAddTraceSource(parentSourceName);
                    traceSource.Listeners.Clear();
                    traceSource.Listeners.AddRange(parentTraceSource.Listeners);
                }
                if (HasDefaultSwitch(traceSource))
                {
                    TraceSource parentTraceSource = GetOrAddTraceSource(parentSourceName);
                    traceSource.Switch = parentTraceSource.Switch;
                }
            }

            return traceSource;
        }
Ejemplo n.º 16
0
        internal RedisMessageBus(IDependencyResolver resolver, RedisScaleoutConfiguration configuration, IRedisConnection connection, bool connectAutomatically)
            : base(resolver, configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            _connection = connection;

            _connectionString = configuration.ConnectionString;
            _db = configuration.Database;
            _key = configuration.EventKey;

            var traceManager = resolver.Resolve<ITraceManager>();

            _trace = traceManager["SignalR." + typeof(RedisMessageBus).Name];

            ReconnectDelay = TimeSpan.FromSeconds(2);

            if (connectAutomatically)
            {
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    var ignore = ConnectWithRetry();
                });
            }
        }
        internal TracerConfig(string cfg)
        {
            if (string.IsNullOrEmpty(cfg))
            {
                return;
            }

            var source = new TraceSource(TraceEnvVarName, SourceLevels.All);
            this.myListeners = source.Listeners;

            var parser = new TraceCfgParser(cfg);
            var newListener = parser.OutDevice;
            this.myFilters = parser.Filters;
            this.myNotFilters = parser.NotFilters;

            if (newListener != null)
            {
                // when the App.config _Trace source should be used we do not replace
                // anything
                if (!parser.UseAppConfigListeners)
                {
                    this.myListeners.Clear();
                    this.myListeners.Add(newListener);
                }
            }
            else
            {
                this.myListeners = null;
            }
        }
Ejemplo n.º 18
0
 private AgentMessageTable()
 {
     id = Guid.NewGuid().ToString();
     log = new TraceSource(name);
     Hashtable t = new Hashtable();
     messageTable = Hashtable.Synchronized(t);
 }
Ejemplo n.º 19
0
 /// <summary>
 /// 初始化服务容器
 /// </summary>
 /// <param name="serviceName"> 服务约定名称 </param>
 /// <param name="serviceType"> 服务约定基类或接口类型 </param>
 /// <param name="typeComparer"> 比较2个类型服务的优先级 </param>
 /// <param name="logger"> 日志记录器 </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="serviceName" /> and <paramref name="serviceType" /> is all
 /// <see langword="null" />.
 /// </exception>
 /// <exception cref="OverflowException"> 匹配插件数量超过字典的最大容量 (<see cref="F:System.Int32.MaxValue" />)。 </exception>
 protected ServiceContainer(string serviceName, Type serviceType, IComparer<Type> typeComparer, TraceSource logger = null)
 {
     TypeComparer = typeComparer;
     _logger = logger ?? LogServices.Logger;
     _items = new ConcurrentDictionary<Type, ServiceItem>();
     _logger?.Write(TraceEventType.Start, $"开始扫描服务插件 serviceName={serviceName},serviceType={serviceType}");
     foreach (var p in MEF.PlugIns.GetPlugIns(serviceName, serviceType).OrderByDescending(p => p.Priority))
     {
         var value = p.GetValue(serviceType);
         if (value == null)
         {
             continue;
         }
         var type = GetServiceType(p, value);
         if (type == null)
         {
             continue;
         }
         var item = new ServiceItem(this, type, value, p);
         item.MakeSystem(); //默认为系统插件
         if (_items.TryAdd(type, item) == false)
         {
             _logger?.Write(TraceEventType.Verbose, $"服务插件({value.GetType().FullName})因优先级({p.Priority})过低被抛弃");
         }
         else
         {
             _logger?.Write(TraceEventType.Verbose, $"服务插件({value.GetType().FullName}),优先级({p.Priority})装载完成");
         }
     }
     _logger?.Write(TraceEventType.Stop, $"服务插件装载完成,有效服务 {Count} 个");
 }
Ejemplo n.º 20
0
        public TraceLogger(IConfigurationManager logConfig)
        {
            ArgumentValidator.ValidateNonNullReference(logConfig,"logConfig","TraceLogger.Ctor()");

            this._traceSource = new TraceSource(TraceSourceName) { Switch = new SourceSwitch(TraceSwitchName) };
            LogLevel logLevel;
            Enum.TryParse(logConfig.SystemConfiguration["LogLevel"], out logLevel);

            switch (logLevel)
            {
                case LogLevel.Off:
                    this._traceSource.Switch.Level = SourceLevels.Off;
                    break;
                case LogLevel.Critical:
                    this._traceSource.Switch.Level = SourceLevels.All;
                    break;
                case LogLevel.Error:
                    this._traceSource.Switch.Level = SourceLevels.Critical | SourceLevels.Error;
                    break;
                case LogLevel.Warning:
                    this._traceSource.Switch.Level = SourceLevels.Critical | SourceLevels.Error | SourceLevels.Warning;
                    break;
                case LogLevel.Information:
                    this._traceSource.Switch.Level = SourceLevels.Critical | SourceLevels.Error | SourceLevels.Warning | SourceLevels.Information;
                    break;
                case LogLevel.Verbose:
                    this._traceSource.Switch.Level = SourceLevels.Critical | SourceLevels.Error | SourceLevels.Warning | SourceLevels.Information | SourceLevels.Verbose;
                    break;
            }
        }
Ejemplo n.º 21
0
        private static void ApplyListeners(OriginalTraceSource traceSource)
        {
            lock (_lock)
            {
                var defaultListenerMustBeAdded = false;

                for (var c = traceSource.Listeners.Count - 1; c >= 0; c--)
                {
                    var traceSourceListener = traceSource.Listeners[c];

                    var defaultTraceListener = traceSourceListener as DefaultTraceListener;
                    if (null == defaultTraceListener || typeof(DefaultTraceListener) != defaultTraceListener.GetType())
                    {
                        continue;
                    }

                    traceSource.Listeners.RemoveAt(c);

                    defaultListenerMustBeAdded = true;
                }
                if (defaultListenerMustBeAdded && null != _traceListener)
                {
                    traceSource.Listeners.Add(_traceListener);
                }
            }
        }
Ejemplo n.º 22
0
        private TraceSource InitializeTraceSource(string key)
        {
            var traceSource = new TraceSource(key);
            if (key == RootTraceName)
            {
                if (HasDefaultSwitch(traceSource))
                {
                    traceSource.Switch = _switch;
                }
            }
            else
            {
                if (HasDefaultListeners(traceSource))
                {
                    TraceSource rootSource = GetOrAddTraceSource(RootTraceName);
                    traceSource.Listeners.Clear();
                    traceSource.Listeners.AddRange(rootSource.Listeners);
                }
                if (HasDefaultSwitch(traceSource))
                {
                    TraceSource rootSource = GetOrAddTraceSource(RootTraceName);
                    traceSource.Switch = rootSource.Switch;
                }
            }

            return traceSource;
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Process4.Task.Wrappers.MethodWrapper"/> class.
 /// </summary>
 /// <param name="method">The method to wrap.</param>
 public MethodWrapper(MethodDefinition method)
 {
     this.m_Method = method;
     this.m_Type = method.DeclaringType;
     this.m_Module = method.Module;
     this.m_TraceSource = new TraceSource("MethodWrapper");
 }
        /// <summary>
        /// Constructor used to initialize the class
        /// </summary>
        /// <param name="source">The source that we are tracing through as part of this scope</param>
        /// <param name="name">The name of the activity that this scope represents</param>
        public TraceTransferScope(TraceSource source, string name)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            this.source = source;
            this.oldActivity = Trace.CorrelationManager.ActivityId;
            this.name = name;

            this.newActivity = Guid.NewGuid();

            if (this.oldActivity != Guid.Empty)
            {
                this.source.TraceTransfer(0, string.Format("Transferring to {0}...", this.name), this.newActivity);
            }

            Trace.CorrelationManager.ActivityId = this.newActivity;

            this.source.TraceEvent(TraceEventType.Start, 0, this.name);
        }
Ejemplo n.º 25
0
 public HttpRequestLifeTime(TransportDisconnectBase transport, TaskQueue writeQueue, TraceSource trace, string connectionId)
 {
     _transport = transport;
     _trace = trace;
     _connectionId = connectionId;
     _writeQueue = writeQueue;
 }
Ejemplo n.º 26
0
        public static bool TestListeners(TraceSource source, Type[] types, string[] names, Type[] filters)
        {
            //This tests all the listeners for a TestSource
            TraceListenerCollection collection = source.Listeners;
            for (int i = 0; i < types.Length; i++)
            {
                bool found = false;
                for (int j = 0; j < collection.Count; j++)
                {
                    if (collection[j].GetType().Equals(types[i]))
                    {
                        found = true;
                        Assert.True(collection[j].Name == names[i]);
                        if (filters[i] == null)
                            Assert.True(collection[j].Filter == null);
                        else
                            Assert.True(collection[j].Filter.GetType().Equals(filters[i]));
                    }
                }

                Assert.True(found);
            }

            return true;
        }
Ejemplo n.º 27
0
        public void UsesTraceSource()
        {
            Console.WriteLine("Config:"+ AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

            Assert.AreEqual("FromAppConfig", ConfigurationManager.AppSettings["appConfigCheck"]);

            // just ensure, that <system.diagnostics> is configured for our test
            Trace.Refresh();
            TraceSource ts = new TraceSource("TraceLoggerTests", SourceLevels.All);
            Assert.AreEqual(1, ts.Listeners.Count);
            Assert.AreEqual(typeof(CapturingTraceListener), ts.Listeners[0].GetType());

            CapturingTraceListener.Events.Clear();
            ts.TraceEvent(TraceEventType.Information, 0, "message");
            Assert.AreEqual(TraceEventType.Information, CapturingTraceListener.Events[0].EventType);
            Assert.AreEqual("message", CapturingTraceListener.Events[0].FormattedMessage);

            // reset events and set loggerFactoryAdapter
            CapturingTraceListener.Events.Clear();
            NameValueCollection props = new NameValueCollection();
            props["useTraceSource"] = "TRUE";
            TraceLoggerFactoryAdapter adapter = new TraceLoggerFactoryAdapter(props);
            adapter.ShowDateTime = false;
            LogManager.Adapter = adapter;

            ILog log = LogManager.GetLogger("TraceLoggerTests");            
            log.WarnFormat("info {0}", "arg");
            Assert.AreEqual(TraceEventType.Warning, CapturingTraceListener.Events[0].EventType);
            Assert.AreEqual("[WARN]  TraceLoggerTests - info arg", CapturingTraceListener.Events[0].FormattedMessage);
        }
Ejemplo n.º 28
0
        public TraceLogger(string fileName)
        {
            Guard.ArgumentNotEmpty(() => fileName);

            _traceSource = new TraceSource("SmartStore");
            _traceSource.Switch = new SourceSwitch("LogSwitch", "Error");
            _traceSource.Listeners.Remove("Default");

            var console = new ConsoleTraceListener(false);
            console.Filter = new EventTypeFilter(SourceLevels.All);
            console.Name = "console";

            var textListener = new TextWriterTraceListener(fileName);
            textListener.Filter = new EventTypeFilter(SourceLevels.All);
            textListener.TraceOutputOptions = TraceOptions.DateTime;

            _traceSource.Listeners.Add(console);
            _traceSource.Listeners.Add(textListener);

            // Allow the trace source to send messages to
            // listeners for all event types. Currently only
            // error messages or higher go to the listeners.
            // Messages must get past the source switch to
            // get to the listeners, regardless of the settings
            // for the listeners.
            _traceSource.Switch.Level = SourceLevels.All;
        }
        public static HttpConfiguration Configure(WsFederationPluginOptions options)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.SuppressDefaultHostAuthentication();

            config.MessageHandlers.Insert(0, new KatanaDependencyResolver());
            config.Services.Add(typeof(IExceptionLogger), new LogProviderExceptionLogger());
            config.Services.Replace(typeof(IHttpControllerTypeResolver), new HttpControllerTypeResolver());

            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly;

            if (options.IdentityServerOptions.LoggingOptions.EnableWebApiDiagnostics)
            {
                var liblog = new TraceSource("LibLog");
                liblog.Switch.Level = SourceLevels.All;
                liblog.Listeners.Add(new LibLogTraceListener());

                var diag = config.EnableSystemDiagnosticsTracing();
                diag.IsVerbose = options.IdentityServerOptions.LoggingOptions.WebApiDiagnosticsIsVerbose;
                diag.TraceSource = liblog;
            }

            if (options.IdentityServerOptions.LoggingOptions.EnableHttpLogging)
            {
                config.MessageHandlers.Add(new RequestResponseLogger());
            }

            return config;
        }
Ejemplo n.º 30
0
 static TraceSources()
 {
     TemplateSource = new TraceSource("LostDoc.Core.Template", SourceLevels.All);
     AssetResolverSource = new TraceSource("LostDoc.Core.Template.AssetResolver", SourceLevels.All);
     GeneratorSource = new TraceSource("LostDoc.Core.DocGenerator", SourceLevels.All);
     BundleSource = new TraceSource("LostDoc.Core.Bundle", SourceLevels.All);
 }
Ejemplo n.º 31
0
        public static HttpConfiguration Configure(IdentityServerOptions options, ILifetimeScope container)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.SuppressDefaultHostAuthentication();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            config.Services.Add(typeof(IExceptionLogger), new LogProviderExceptionLogger());
            config.Services.Replace(typeof(IHttpControllerTypeResolver), new HttpControllerTypeResolver());
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly;

            if (options.LoggingOptions.EnableWebApiDiagnostics)
            {
                var liblog = new TraceSource("LibLog");
                liblog.Switch.Level = SourceLevels.All;
                liblog.Listeners.Add(new LibLogTraceListener());

                var diag = config.EnableSystemDiagnosticsTracing();
                diag.IsVerbose = options.LoggingOptions.WebApiDiagnosticsIsVerbose;
                diag.TraceSource = liblog;
            }

            ConfigureRoutes(options, config);

            return config;
        }
        public SimpleEmailer(string host, int port, string userName, string password, string domain, bool useSsl, string fromAddress, string fromName)
        {
            string traceName = this.GetType().FullName;
            Trace.WriteLine(string.Format("Creating TraceSource {0}.  Please register a listener for detailed information.", traceName));
            _Trace = new TraceSource(traceName);

            _Trace.TraceInformation("Creating SmtpTransport: UserName:{0}, Password: -, Domain:{1}, Host:{2}, Port:{3}, SSL:{4}", userName, domain, host, port, useSsl);

            _Client = new SmtpClient(host,port);
            _Trace.TraceInformation("Created SMTP Client - {0}:{1}", host, port);

            _Client.EnableSsl = useSsl;

            _From = new MailAddress(fromAddress, fromName);
            _Trace.TraceInformation("From address set to {0} [{1}]", _From.Address, _From.DisplayName);

            if (!string.IsNullOrEmpty(userName))
            {
                _Client.UseDefaultCredentials = false;
                _Client.Credentials = new System.Net.NetworkCredential(userName, password, domain);
                _Trace.TraceInformation("Created credentials for {0}\\{1}", domain, userName);
            }
            else
            {
                _Client.UseDefaultCredentials = true;
                _Trace.TraceInformation("Using default credentials");
            }
        }
Ejemplo n.º 33
0
        public TvCableConciliacionService()
        {
            trace = new System.Diagnostics.TraceSource("TvCableConWinService");
            System.Diagnostics.Trace.CorrelationManager.ActivityId = Guid.NewGuid();
            System.Diagnostics.Trace.CorrelationManager.StartLogicalOperation("TvCableConWinService");

            InitializeComponent();
        }
Ejemplo n.º 34
0
 static Trace()
 {
     kPhxSource    = new                        Diag.TraceSource("PhxLib", Diag.SourceLevels.All);
     kEngineSource = new                     Diag.TraceSource("PhxLib.Engine", Diag.SourceLevels.All);
     kIoSource     = new                         Diag.TraceSource("KSoft.IO", Diag.SourceLevels.All);
     kUtilSource   = new                       Diag.TraceSource("PhxLib.Util", Diag.SourceLevels.All);
     kXMLSource    = new                        Diag.TraceSource("PhxLib.XML", Diag.SourceLevels.All);
 }
 static DiagnosticTrace()
 {
     AppDomainFriendlyName       = AppDomain.CurrentDomain.FriendlyName;
     traceEventTypeNames         = new Dictionary <int, string>();
     traceEventTypeNames[1]      = "Critical";
     traceEventTypeNames[2]      = "Error";
     traceEventTypeNames[4]      = "Warning";
     traceEventTypeNames[8]      = "Information";
     traceEventTypeNames[0x10]   = "Verbose";
     traceEventTypeNames[0x800]  = "Resume";
     traceEventTypeNames[0x100]  = "Start";
     traceEventTypeNames[0x200]  = "Stop";
     traceEventTypeNames[0x400]  = "Suspend";
     traceEventTypeNames[0x1000] = "Transfer";
     TraceFailureThreshold       = 10;
     TraceFailureCount           = TraceFailureThreshold + 1;
     try
     {
         traceSource = new System.Diagnostics.TraceSource("System.Transactions", SourceLevels.Critical);
         AppDomain currentDomain = AppDomain.CurrentDomain;
         if (TraceSource.Switch.ShouldTrace(TraceEventType.Critical))
         {
             currentDomain.UnhandledException += new UnhandledExceptionEventHandler(DiagnosticTrace.UnhandledExceptionHandler);
         }
         currentDomain.DomainUnload += new EventHandler(DiagnosticTrace.ExitOrUnloadEventHandler);
         currentDomain.ProcessExit  += new EventHandler(DiagnosticTrace.ExitOrUnloadEventHandler);
         haveListeners = TraceSource.Listeners.Count > 0;
         SetLevel(TraceSource.Switch.Level);
     }
     catch (ConfigurationErrorsException)
     {
         throw;
     }
     catch (OutOfMemoryException)
     {
         throw;
     }
     catch (StackOverflowException)
     {
         throw;
     }
     catch (ThreadAbortException)
     {
         throw;
     }
     catch (Exception exception)
     {
         if (TraceSource == null)
         {
             LogEvent(TraceEventType.Error, string.Format(CultureInfo.CurrentCulture, System.Transactions.SR.GetString("FailedToCreateTraceSource"), new object[] { exception }), true);
         }
         else
         {
             TraceSource = null;
             LogEvent(TraceEventType.Error, string.Format(CultureInfo.CurrentCulture, System.Transactions.SR.GetString("FailedToInitializeTraceSource"), new object[] { exception }), true);
         }
     }
 }
Ejemplo n.º 36
0
 static Trace()
 {
     kPhoenixSource       = new            Diag.TraceSource("KSoft.Phoenix", Diag.SourceLevels.All);
     kEngineSource        = new                     Diag.TraceSource("KSoft.Phoenix.Engine", Diag.SourceLevels.All);
     kResourceSource      = new           Diag.TraceSource("KSoft.Phoenix.Resource", Diag.SourceLevels.All);
     kSecuritySource      = new           Diag.TraceSource("KSoft.Security", Diag.SourceLevels.All);
     kTriggerSystemSource = new      Diag.TraceSource("KSoft.Phoenix.Triggers", Diag.SourceLevels.All);
     kXmlSource           = new                        Diag.TraceSource("KSoft.Phoenix.XML", Diag.SourceLevels.All);
 }
Ejemplo n.º 37
0
        public static OriginalTraceSource GetOrDefault(string name, OriginalTraceSource traceSource)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(name));
            Contract.Requires(null != traceSource);
            Contract.Ensures(null != Contract.Result <OriginalTraceSource>());

            var result = _traceSources.AddOrUpdate(name, traceSource, (key, oldvalue) => oldvalue);

            return(result);
        }
Ejemplo n.º 38
0
            public SystemNetLoggingScope()
            {
                this.writer = new StringWriter();

                ReflectionUtility.InvokeMethod(SystemNetLogging, "InitializeLogging");
                ReflectionUtility.SetField(SystemNetLogging, "s_LoggingEnabled", true);
                System.Diagnostics.TraceSource s = SystemNetWebSource;
                s.Switch.Level = SourceLevels.All;
                s.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(writer));
            }
Ejemplo n.º 39
0
 public LogFilter(
     ITraceSource requestTraceSource,
     ITraceSource responseTraceSource,
     IContext context,
     IOptions options)
 {
     this.requestTraceSource  = requestTraceSource;
     this.responseTraceSource = responseTraceSource;
     this.context             = context;
     this.options             = options;
     fallbackTraceSource      = new System.Diagnostics.TraceSource(fallbackKey);
 }
Ejemplo n.º 40
0
        //private System.Diagnostics.TraceSource mySource =  new System.Diagnostics.TraceSource("TraceSourceApp");

        private System.Diagnostics.TraceSource CreateDiagTraceSource()
        {
            var rabbitmqListener =
                new Recodify.Logging.Listeners.RabbitMq.TraceListener("events-live,logs-live,logging-test2");

            var mySource = new System.Diagnostics.TraceSource("TraceSourceApp");

            mySource.Switch       = new SourceSwitch("sourceSwitch", "Error");
            mySource.Switch.Level = SourceLevels.All;
            mySource.Listeners.Remove("Default");
            mySource.Listeners.Add(rabbitmqListener);

            return(mySource);
        }
Ejemplo n.º 41
0
        public void LoggingVerboseViaTraceSourceToLog4NetTraceListenerWithFilterSkipsLogging()
        {
            var traceListener = Mock.Create <Log4NetTraceListener>(Behavior.CallOriginal);

            Mock.Arrange(() => traceListener.TraceEvent(Arg.IsAny <TraceEventCache>(), Arg.IsAny <string>(), Arg.IsAny <TraceEventType>(), Arg.IsAny <int>(), Arg.IsAny <string>(), Arg.IsAny <object[]>()))
            .IgnoreInstance()
            .OccursNever();

            var traceSource = new System.Diagnostics.TraceSource("TraceSourceWithLog4NetListenerWithFilter");

            traceSource.TraceEvent(TraceEventType.Verbose, 1, "TraceFromTestMethod '{0}'", DateTimeOffset.Now.ToString("O"));
            traceSource.TraceEvent(TraceEventType.Verbose, 1, "TraceFromTestMethod '{0}'", DateTimeOffset.Now.ToString("O"));

            Mock.Assert(traceListener);
        }
Ejemplo n.º 42
0
        public void LoggingErrorViaTraceSourceToLog4NetTraceListenerWithFilterSkipsLogging()
        {
            var logger = Mock.Create <ILog>();

            Mock.Arrange(() => logger.Fatal(Arg.IsAny <string>()))
            .IgnoreInstance()
            .OccursNever();

            var traceSource = new System.Diagnostics.TraceSource("TraceSourceWithLog4NetListenerWithFilter");

            traceSource.TraceEvent(TraceEventType.Error, 1, "TraceFromTestMethod '{0}'", DateTimeOffset.Now.ToString("O"));
            traceSource.TraceEvent(TraceEventType.Error, 1, "TraceFromTestMethod '{0}'", DateTimeOffset.Now.ToString("O"));

            Mock.Assert(logger);
        }
Ejemplo n.º 43
0
        public void LoggingViaTraceSourceToLog4NetTraceListenerSucceeds()
        {
            var logger = Mock.Create <ILog>();

            Mock.Arrange(() => logger.Fatal(Arg.IsAny <string>()))
            .IgnoreInstance()
            .DoNothing()
            .MustBeCalled();

            var traceSource = new System.Diagnostics.TraceSource("TraceSourceWithLog4NetListener");

            traceSource.TraceEvent(TraceEventType.Critical, 1, "TraceFromTestMethod '{0}'", DateTimeOffset.Now.ToString("O"));

            Mock.Assert(logger);
        }
Ejemplo n.º 44
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            if (options.ExcludeUrls.Any(x => request.RequestUri.AbsoluteUri.ToLower().Contains(x)))
            {
                return(await base.SendAsync(request, cancellationToken));
            }

            var fallbackTraceSource = new System.Diagnostics.TraceSource(fallbackKey);
            var sw = new Stopwatch();

            sw.Start();

            await LogRequest(request, fallbackTraceSource);

            return(await LogResponse(request, cancellationToken, fallbackTraceSource, sw));
        }
Ejemplo n.º 45
0
        public static OriginalTraceSource GetBase(string traceSourceBase)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(traceSourceBase));
            Contract.Ensures(null != Contract.Result <OriginalTraceSource>());

            var traceSource = _traceSources.GetOrAdd(traceSourceBase, key =>
            {
                var result = new OriginalTraceSource(key, SourceLevels.All);

                ApplyListeners(result);

                return(result);
            });

            return(traceSource);
        }
Ejemplo n.º 46
0
        private async Task LogRequest(HttpRequestMessage request, System.Diagnostics.TraceSource fallbackTraceSource)
        {
            var requestContent = await request.Content.ReadAsStringAsync();

            try
            {
                var requestHeaders = request.Headers.ToDictionary(k => k.Key, v => v.Value);
                requestTraceSource.TraceRequest(
                    request.Method.ToString(),
                    GetRequestHeaders(request),
                    requestContent);
            }
            catch (Exception exp)
            {
                fallbackTraceSource.TraceData(TraceEventType.Error, (int)Event.LoggingExceptionFallingBack, exp);
            }
        }
Ejemplo n.º 47
0
        public static void Trace(object[] data, string traceSourceName)
        {
            try
            {
                string sourceName = !String.IsNullOrEmpty(traceSourceName) ? traceSourceName : ModuleConfiguration.DefaultTraceSourceName;

                System.Diagnostics.TraceSource trace = new System.Diagnostics.TraceSource(sourceName);

                trace.TraceData(System.Diagnostics.TraceEventType.Information, new Random().Next(), data);

                trace.Flush();
            }
            catch (Exception)
            {
                //If you want to handle this exception, add your exception handling code here, else you may uncomment the following line to throw this exception out.
                throw;
            }
        }
        private void SetLevel(SourceLevels level)
        {
            SourceLevels levels = this.FixLevel(level);

            this.level = levels;
            if (this.TraceSource != null)
            {
                this.haveListeners = this.TraceSource.Listeners.Count > 0;
                if ((this.TraceSource.Switch.Level != SourceLevels.Off) && (level == SourceLevels.Off))
                {
                    System.Diagnostics.TraceSource traceSource = this.TraceSource;
                    this.CreateTraceSource();
                    traceSource.Close();
                }
                this.tracingEnabled           = this.HaveListeners && (levels != SourceLevels.Off);
                this.TraceSource.Switch.Level = levels;
                this.shouldUseActivity        = (levels & SourceLevels.ActivityTracing) != SourceLevels.Off;
            }
        }
Ejemplo n.º 49
0
        private void SetLevel(SourceLevels level)
        {
            SourceLevels sourceLevel = Microsoft.ServiceBus.Diagnostics.DiagnosticTrace.FixLevel(level);

            this.level = sourceLevel;
            if (this.TraceSource != null)
            {
                this.haveListeners = this.TraceSource.Listeners.Count > 0;
                if (this.TraceSource.Switch.Level != SourceLevels.Off && level == SourceLevels.Off)
                {
                    System.Diagnostics.TraceSource traceSource = this.TraceSource;
                    this.CreateTraceSource();
                    traceSource.Close();
                }
                this.tracingEnabled           = (!this.HaveListeners ? false : sourceLevel != SourceLevels.Off);
                this.TraceSource.Switch.Level = sourceLevel;
                this.shouldUseActivity        = (sourceLevel & SourceLevels.ActivityTracing) != SourceLevels.Off;
            }
        }
Ejemplo n.º 50
0
        protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
        {
            var allParameters = GetParams();

            _columnMap = allParameters.Where(a => a.Name.StartsWith(ColumnMap.ColumnRename, StringComparison.OrdinalIgnoreCase));

            var parameters = allParameters.Except(_columnMap, new ColumnMapComparer());

            foreach (var parameter in parameters)
            {
                // dapper 1.7+ rips off the @, this allows for either @ or no prefix to be found and replaced
                var name = parameter.Name.StartsWith(ColumnMap.Parameter, StringComparison.OrdinalIgnoreCase) ? parameter.Name : ColumnMap.Parameter + parameter.Name;
                _command.CommandText = _command.CommandText.Replace(name, parameter.Value.ToString());
            }

            var trace = new System.Diagnostics.TraceSource("mdx");

            trace.TraceData(System.Diagnostics.TraceEventType.Information, 0, _command.CommandText);

            var results = PopulateFromXml(_command.ExecuteXmlReader());

            return(behavior == CommandBehavior.CloseConnection ? new MdxDataReader(results, _connection) : new MdxDataReader(results));
        }
Ejemplo n.º 51
0
 public TraceSource(System.Diagnostics.TraceSource traceSource, IEnricher enricher)
 {
     this.traceSource    = traceSource;
     fallbackTraceSource = new System.Diagnostics.TraceSource(fallbackKey);
     this.enricher       = enricher;
 }
Ejemplo n.º 52
0
 static Trace()
 {
     kWwiseSource       = new                      Diag.TraceSource("KSoft.Wwise", Diag.SourceLevels.All);
     kFilePackageSource = new        Diag.TraceSource("KSoft.Wwise.FilePackage", Diag.SourceLevels.All);
 }
 private static bool HasDefaultSwitch(DiagnosticsTraceSource traceSource)
 {
     return(string.IsNullOrEmpty(traceSource.Switch.DisplayName) == string.IsNullOrEmpty(traceSource.Name) &&
            traceSource.Switch.Level == SourceLevels.Off);
 }
 private static bool HasDefaultListeners(DiagnosticsTraceSource traceSource)
 {
     return(traceSource.Listeners.Count == 1 && traceSource.Listeners[0] is DefaultTraceListener);
 }
Ejemplo n.º 55
0
 public SanitisedTraceSource(System.Diagnostics.TraceSource traceSource, IEnricher enricher, ISanitiser sanitiser)
     : base(traceSource, enricher)
 {
     this.sanitiser = sanitiser;
 }
Ejemplo n.º 56
0
 public DiagnosticsTracer(TraceSource source)
 {
     this.source = source;
 }
Ejemplo n.º 57
0
 static Trace()
 {
     kPhxGuixSource = new Diag.TraceSource("PhxGui", Diag.SourceLevels.All);
 }
Ejemplo n.º 58
0
 public TraceSourceLogger(DiagnosticsTraceSource traceSource)
 {
     _traceSource = traceSource;
 }
Ejemplo n.º 59
0
        private async Task <HttpResponseMessage> LogResponse(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken, System.Diagnostics.TraceSource fallbackTraceSource, Stopwatch sw)
        {
            var response = await base.SendAsync(request, cancellationToken);

            if (response == null || response.Content == null)
            {
                return(response);
            }

            var responseContent = await response.Content.ReadAsStringAsync();

            try
            {
                sw.Stop();
                var statusCode      = (int)response.StatusCode;
                var responseHeaders = response.Content.Headers.ToString() + " " + response.Headers.ToString();

                responseTraceSource.TraceResponse(
                    (int)response.StatusCode,
                    responseHeaders,
                    responseContent,
                    sw.ElapsedMilliseconds);
            }
            catch (Exception exp)
            {
                fallbackTraceSource.TraceData(TraceEventType.Error, (int)Event.LoggingExceptionFallingBack, exp);
            }

            return(response);
        }
Ejemplo n.º 60
0
 public static void Refresh()
 {
     Switch.RefreshAll();
     TraceSource.RefreshAll();
     TraceInternal.Refresh();
 }