コード例 #1
0
        public static bool TryInject(
            IServiceRegistrationProvider serviceProvider,
            object target,
            Type attributeType,
            ITrace logger = null,
            Func <Type, object> instanceProvider = null,
            bool tryConstructArguments           = false,
            bool?requireConstructorAttributes    = null,
            IReadOnlyCollection <Type> constructorAttributeTypes = null)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (attributeType == null)
            {
                throw new ArgumentNullException(nameof(attributeType));
            }
            if ((constructorAttributeTypes == null) ||
                (constructorAttributeTypes.Count == 0))
            {
                constructorAttributeTypes = new[] { typeof(ServiceProviderConstructorAttribute) }
            }
            ;
            ServiceConstructorRequest request
                = new ServiceConstructorRequest(logger ?? TraceSources.For(typeof(ServiceConstructorMethods)));

            request.Logger.Verbose(
                "Injecting '{0}' on '{1}'.",
                attributeType.GetFriendlyFullName(),
                target.GetType().GetFriendlyFullName());
            if (ServiceConstructorMethods.invokeMember(
                    ServiceConstructorMethods.findMethods(target, attributeType, request.TraceStack),
                    true,
                    target,
                    out _,
                    request,
                    serviceProvider,
                    instanceProvider,
                    tryConstructArguments,
                    requireConstructorAttributes,
                    constructorAttributeTypes,
                    false))
            {
                request.Logger.Verbose(
                    "Inject result for '{0}' on '{1}' is true.",
                    attributeType.GetFriendlyFullName(),
                    target.GetType().GetFriendlyFullName());
                return(true);
            }
            request.Logger.Info(
                "Inject result for '{0}' on '{1}' is false.",
                attributeType.GetFriendlyFullName(),
                target.GetType().GetFriendlyFullName());
            return(false);
        }
コード例 #2
0
 public void RegisterExport(Type importType, Type exportType)
 {
     if (importType == null)
     {
         throw new ArgumentNullException(nameof(importType));
     }
     if (exportType == null)
     {
         throw new ArgumentNullException(nameof(exportType));
     }
     if (!typeof(TExport).IsAssignableFrom(exportType))
     {
         throw new ArgumentException(typeof(TExport).GetFriendlyFullName(), nameof(exportType));
     }
     lock (Registrations) {
         if (Registrations.ContainsKey(importType))
         {
             throw new InvalidOperationException(
                       $"Cannot add duplicate registration for '{importType.GetFriendlyFullName()}'.");
         }
         if (!OnRegisterExport(importType, exportType))
         {
             return;
         }
         TraceSources.For(GetType())
         .Verbose(
             $"{nameof(ExportRegistry<TExport>.RegisterExport)}:"
             + " '{0}' for '{1}'.",
             exportType.GetFriendlyFullName(),
             importType.GetFriendlyFullName());
         Registrations[importType] = exportType;
     }
 }
コード例 #3
0
        /// <summary>
        /// Invokes the <see cref="TraceSources"/> factory method with a delegate
        /// that adds a verbose console trace listener to all sources.
        /// </summary>
        /// <returns>Dispose to reset the default factory.</returns>
        public static IDisposable TraceAllVerbose()
        {
            void Configure(SimpleTraceSource traceSource)
            {
                traceSource.TraceSource.TryAdd(
                    new Diagnostics.ConsoleTraceListener
                {
                    Filter = new EventTypeFilter(SourceLevels.All),
                });
                traceSource.TraceSource.Switch.Level = SourceLevels.All;
            }

            void Remove(SimpleTraceSource traceSource)
            => traceSource.TraceSource.Listeners.Remove(Diagnostics.ConsoleTraceListener.DefaultName);

            DelegateTraceSourceSelector selector = new DelegateTraceSourceSelector(Configure, Remove);

            TraceSources.AddSelector(selector);
            TraceSources.For(typeof(TestHelper))
            .Verbose("TraceSources are verbose.");
            void Dispose()
            => TraceSources.RemoveSelector(selector);

            return(DelegateDisposable.With(Dispose));
        }
コード例 #4
0
 /// <summary>
 /// Convenience method flushes this <see cref="LogFileListener"/>, flushes
 /// <see cref="TraceSources"/>, <see cref="Trace"/>, and <see cref="Debug"/>.
 /// This will be invoked when disposed.
 /// </summary>
 public void FlushAll()
 {
     TraceSources.FlushAll();
     LogFileListener?.Flush();
     Trace.Flush();
     Debug.Flush();
 }
コード例 #5
0
        private void refresh(FileSystemEventArgs fileSystemEventArgs)
        {
            Exception exception;

            lock (syncLock) {
                if (isDisposed)
                {
                    if (fileSystemEventArgs == null)
                    {
                        throw new ObjectDisposedException(ToString());
                    }
                    return;
                }
                disposeFileSystemWatcher();
                tryCreateFileSystemWatcher(out exception);
                if (exception != null)
                {
                    TraceSources.For <DirectoryWatcher>()
                    .Error("Local Error for {0}: {1}.", exception, this, exception.Message);
                }
                else if ((fileSystemEventArgs == null) ||
                         !IsWatchingPath)
                {
                    return;
                }
            }
            Changed?.Invoke(this, new DirectoryWatcherEventArgs(fileSystemEventArgs, exception));
        }
コード例 #6
0
 /// <summary>
 /// This method is virtual and implements
 /// <see cref="IHandleComposed{TTarget}.HandleComposed{T}"/>.
 /// This implementation invokes all participants added here.
 /// Notice that each is invoked in a catch block, and this will trace exceptions,
 /// AND re-throw a new <see cref="AggregateException"/> if there are
 /// any exceptions.
 /// </summary>
 /// <param name="eventArgs"><see cref="IHandleComposed{TTarget}"/> argument.</param>
 /// <exception cref="AggregateException"></exception>
 public void HandleComposed <T>(ComposerEventArgs <T> eventArgs)
     where T : TTarget
 {
     lock (Participants) {
         checkDisposed();
         List <Exception> exceptions = new List <Exception>(Participants.Count);
         foreach (IHandleComposed <TTarget> participant
                  in Participants.OfType <IHandleComposed <TTarget> >())
         {
             try {
                 participant.HandleComposed(eventArgs);
             } catch (Exception exception) {
                 TraceSources.For(GetType())
                 .Error(
                     exception,
                     "Participant exception invoking HandleComposed: {0}, '{1}'.",
                     participant,
                     exception.Message);
                 exceptions.Add(exception);
             }
         }
         if (exceptions.Count != 0)
         {
             throw new AggregateException(
                       $"One or more exceptions was raised by a {GetType().GetFriendlyName()} participant in"
                       + $" {nameof(IHandleComposed<TTarget>.HandleComposed)}.",
                       exceptions.EnumerateInReverse());
         }
     }
 }
コード例 #7
0
        protected sealed override void WithAllParts(ContainerConfiguration target)
        {
            Action Mutate(MultiDictionary <CompositionHost, object> exportsList)
            {
                try {
                    CompositionHost compositionHost = target.CreateContainer();
                    List <object>   newExports      = new List <object>();
                    foreach (Type compositionContract in ExportTypes)
                    {
                        newExports.AddRange(compositionHost.GetExports(compositionContract));
                    }
                    Action OnMutate(List <object> list)
                    => handleNewExports(list, newExports);

                    return(handleMutate(exportsList, OnMutate, compositionHost));
                } catch (Exception exception) {
                    TraceSources.For <MefSingletonComposer>()
                    .Error(
                        exception,
                        "Catching exception refreshing Exports: {0}",
                        exception.Message);
                    throw;
                }
            }

            exports.Mutate(Mutate)
            ?.Invoke();
        }
コード例 #8
0
        /// <summary>
        /// This virtual method provides the implementation for
        /// <see cref="IProvideParts{TTarget}"/>.
        /// This enumerates the files on the <see cref="DirectoryWatcher"/> with the
        /// <see cref="SearchOption"/>, and loads each path with <see cref="TryLoadAssembly"/>.
        /// This method catches and traces all exceptions; and also provides support for
        /// <see cref="ProvideAssembliesOneTimeOnly"/>.
        /// </summary>
        public virtual void ProvideParts <T>(ProvidePartsEventArgs <T> eventArgs)
            where T : ContainerConfiguration
        {
            List <Assembly> assemblies = new List <Assembly>();

            if (DirectoryWatcher.PathExists)
            {
                try {
                    foreach (string filePath in Directory.EnumerateFiles(
                                 DirectoryWatcher.Path,
                                 DirectoryWatcher.Filter,
                                 SearchOption))
                    {
                        if (TryLoadAssembly(filePath, out Assembly assembly))
                        {
                            assemblies.Add(assembly);
                        }
                    }
                } catch (Exception exception) {
                    TraceSources.For <MefDirectoryPartWatcher>()
                    .Warning(
                        exception,
                        "Catching exception enumerating files in the watched directory: '{0}'.",
                        exception.Message);
                }
            }
            if (assemblies.Count == 0)
            {
                return;
            }
            lock (ComposedAssemblies) {
                if (ProvideAssembliesOneTimeOnly)
                {
                    foreach (Assembly assembly in new List <Assembly>(assemblies))
                    {
                        if (!ComposedAssemblies.Contains(assembly))
                        {
                            ComposedAssemblies.Add(assembly);
                        }
                        else
                        {
                            assemblies.Remove(assembly);
                        }
                    }
                    if (assemblies.Count == 0)
                    {
                        return;
                    }
                }
            }
            if (Conventions != null)
            {
                eventArgs.Target.WithAssemblies(assemblies, Conventions);
            }
            else
            {
                eventArgs.Target.WithAssemblies(assemblies);
            }
        }
コード例 #9
0
        private void trySetPropertiesFromConfigFile()
        {
            string configFilePath = GetConfigFileFullPath();

            if (File.Exists(configFilePath))
            {
                try {
                    LogFileFactoryConfig newLogFileFactoryConfig
                        = LogFileFactoryConfig.LoadFromFile(configFilePath);
                    bool resetIsInitializing = false;
                    try {
                        lock (SyncLock) {
                            resetIsInitializing = !isInitializing;
                            isInitializing      = true;
                        }
                        newLogFileFactoryConfig.SetPropertiesOn(this);
                    } finally {
                        lock (SyncLock) {
                            logFileFactoryConfig = newLogFileFactoryConfig;
                            if (resetIsInitializing)
                            {
                                isInitializing = false;
                            }
                        }
                    }
                    TraceSources.For(TraceFileFactoryAssembly)
                    .Info(
                        "Found {0} file found at '{1}' - '{2}'.",
                        nameof(LogFileFactoryConfig),
                        configFilePath,
                        logFileFactoryConfig);
                } catch (Exception exception) {
                    TraceSources.For(TraceFileFactoryAssembly)
                    .Error(
                        exception,
                        "Invalid {0} file found at '{1}' - '{2}'.",
                        nameof(LogFileFactoryConfig),
                        configFilePath,
                        exception.Message);
                }
            }
            else
            {
                try {
                    Directory.CreateDirectory(GetLogFolderPath());
                    LogFileFactoryConfig.CreateFrom(this, out XmlDocument xmlDocument);
                    File.WriteAllText(configFilePath, xmlDocument.InnerXml);
                } catch (Exception exception) {
                    TraceSources.For(TraceFileFactoryAssembly)
                    .Error(
                        exception,
                        "Error writing {0} file to '{1}' - '{2}'.",
                        nameof(LogFileFactoryConfig),
                        configFilePath,
                        exception.Message);
                }
            }
        }
コード例 #10
0
 private void handleConfigWatcherError(object sender, ErrorEventArgs e)
 => TraceSources.For <LogFileFactory>()
 .Error(
     e.GetException(),
     "{0} error for config file watcher at '{1}' - '{2}'.",
     nameof(FileSystemWatcher),
     Path.Combine(GetLogFolderPath(), GetConfigFileName()),
     e.GetException()
     .Message);
コード例 #11
0
        public object Get(HttpRequestMessage requestMessage, string id)
        {
            var messageId = requestMessage.GetCorrelationId().ToString();

            TraceSources.AddAdditionalLogItem("RequestMessageId", messageId);
            try
            {
                var passwordChange = new PasswordChange();
                var token          = passwordChange.ExpirationCheck(id);
                return(new IsExpiredTokenSuccessResponse
                {
                    Result = passwordChange.Result != PasswordChange.ValidatedResult.IsExpired && token != null
                });
            }
            catch (InvalidRequestForTConnectApiException e)
            {
                PCSiteTraceSource.InvalidRequest_Api("is-expired-token", "token", e);
                return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
            }
            catch (InvalidJwtException ex)
            {
                var trace = PCSiteTraceSource.InvalidJwt(id, ex);
                var code  = 0;
                trace.TryGetId(out code);
                return(requestMessage.CreateResponse(HttpStatusCode.BadRequest,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", code.ToString() }
                    }
                }));
            }
            catch (TableNotFoundException tex)
            {
                var trace = PCSiteTraceSource.ConnectionFailToAzureStorageTable_Api("StredTokenテーブルにアクセスできませんでした。", tex);
                var code  = 0;
                trace.TryGetId(out code);
                return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", code.ToString() }
                    }
                }));
            }
            catch (Exception ex)
            {
                var trace = PCSiteTraceSource.SystemError_Api("有効期限検証APIで想定外のエラーが発生", ex);
                var code  = 0;
                trace.TryGetId(out code);
                return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", code.ToString() }
                    }
                }));
            }
        }
コード例 #12
0
 private void disposeResources()
 {
     disposeConfigFileWatcher();
     traceAction($"{nameof(LogFileFactory)} Is Being Reset ...");
     TraceSources.RemoveSelector(this);
     lock (SyncLock) {
         logFileListener?.Dispose();
         logFileListener = null;
     }
 }
コード例 #13
0
 private void traceAction(string message)
 {
     TraceSources.For(TraceFileFactoryAssembly)
     .Warning($"##########    ####    {message}    ####    ##########");
     Trace.TraceWarning(
         "##########    ####    "
         + $"{message} For: {TraceFileFactoryAssembly.GetName().Name}."
         + "    ####    ##########");
     FlushAll();
 }
コード例 #14
0
 private void tryCreateFileSystemWatcher(out Exception exception)
 {
     try {
         string path = Path;
         do
         {
             if (Directory.Exists(path))
             {
                 break;
             }
             path = System.IO.Path.GetDirectoryName(PathHelper.RemoveTrailingSeparators(path));
             if (!string.IsNullOrWhiteSpace(path))
             {
                 continue;
             }
             throw new NotSupportedException($"Failed to create {nameof(FileSystemWatcher)} for {this}.");
         } while (true);
         fileSystemWatcher = PathHelper.IsSameFullPath(Path, path)
                                         ? new FileSystemWatcher
         {
             Path   = Path,
             Filter = Filter,
             IncludeSubdirectories = IncludeSubdirectories,
             NotifyFilter          = NotifyFilter,
             EnableRaisingEvents   = true
         }
                                         : new FileSystemWatcher
         {
             Path   = path,
             Filter = "*",
             IncludeSubdirectories = true,
             NotifyFilter          = NotifyFilters.LastWrite
                                     | NotifyFilters.DirectoryName,
             EnableRaisingEvents = true
         };
         fileSystemWatcher.Changed += handleFileSystemWatcherChanged;
         fileSystemWatcher.Created += handleFileSystemWatcherChanged;
         fileSystemWatcher.Deleted += handleFileSystemWatcherChanged;
         fileSystemWatcher.Renamed += handleFileSystemWatcherChanged;
         fileSystemWatcher.Error   += handleFileSystemWatcherError;
         exception = null;
     } catch (Exception error) {
         TraceSources.For <DirectoryWatcher>()
         .Error(
             error,
             "Failed to refresh {0}: {1}. Not watching any folder.",
             this,
             error.Message);
         fileSystemWatcher?.Dispose();
         fileSystemWatcher = null;
         exception         = error;
     }
 }
コード例 #15
0
        private void handleFileSystemWatcherError(object sender, ErrorEventArgs errorEventArgs)
        {
            Exception exception = errorEventArgs.GetException();

            TraceSources.For <DirectoryWatcher>()
            .Warning(
                exception,
                $"{nameof(FileSystemWatcher)} Error for {{0}}: {{1}}.",
                this,
                exception.Message);
            FileSystemWatcherError?.Invoke(this, errorEventArgs);
        }
コード例 #16
0
        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            TraceSources.AddAdditionalLogItem("RequsetId", Guid.NewGuid());
            string AccessURI = HttpContext.Current.Request.Url.PathAndQuery;

            PCSiteTraceSource.CheckPoint("リクエストを受信しました。AccessURI: " + AccessURI);

            var context  = HttpContext.Current;
            var security = new ApiSecurity();

            if (!security.XidXpassFilter(context))
            {
                context.Response.StatusCode = 404;
            }
        }
コード例 #17
0
        /// <summary>
        /// Gets the configured trace source.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        /// <exception cref="System.Configuration.ConfigurationErrorsException"></exception>
        public static TraceSource GetConfiguredTraceSource(this TraceSources instance, string key)
        {
            if (instance == null)
            {
                return(null);
            }

            var name = ConfigurationManager.AppSettings[key];

            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }

            return(TraceSources.Instance.GetTraceSource(name));
        }
コード例 #18
0
 /// <summary>
 /// This protected virtual method loads each Assembly. If a delegate was provided, that
 /// is invoked here; and otherwise, this loads the Assembly with <c>Assembly.LoadFrom</c>.
 /// This is invoked in <see cref="ProvideParts{T}"/>. This method catches and traces all
 /// exceptions.
 /// </summary>
 /// <param name="filePath">Not null.</param>
 /// <param name="assembly">Not null if the method returns true.</param>
 /// <returns>True if the out argument is not null.</returns>
 protected virtual bool TryLoadAssembly(string filePath, out Assembly assembly)
 {
     try {
         assembly = loadAssembly != null
                                         ? loadAssembly(filePath)
                                         : Assembly.LoadFrom(filePath);
     } catch (Exception exception) {
         TraceSources.For <MefDirectoryPartWatcher>()
         .Warning(
             exception,
             "Failed to load Assembly from '{0}': {1}.",
             filePath,
             exception.Message);
         assembly = null;
     }
     return(assembly != null);
 }
コード例 #19
0
        private void setupTracingUnsafe()
        {
            bool resetIsInitializing = false;

            try {
                lock (SyncLock) {
                    if (!isInitialized ||
                        isInitializing)
                    {
                        return;
                    }
                    isInitializing      = true;
                    resetIsInitializing = true;
                }
                TraceSources.For(TraceFileFactoryAssembly)
                .Info("Configure tracing.");
                HandleBeginSetupTracing();
                disposeResources();
                if (ToggleLogFile)
                {
                    lock (SyncLock) {
                        logFileListener = CreateFileLogTraceListener();
                    }
                }
                setupConfigFileWatcher();
                if (addToTraceSources)
                {
                    TraceSources.AddSelector(this);
                }
                traceAction(
                    LogFileListener != null
                                                                ? $"{nameof(LogFileFactory)} Trace File Initialized."
                                                                : $"{nameof(LogFileFactory)} Reset With No Trace File.");
            } finally {
                if (resetIsInitializing)
                {
                    lock (SyncLock) {
                        isInitializing = false;
                    }
                }
            }
            HandleEndSetupTracing();
        }
コード例 #20
0
 private TypeRegistration CreateLogWriterStructureHolderRegistration()
 {
     return
         (new TypeRegistration <LogWriterStructureHolder>(() =>
                                                          new LogWriterStructureHolder(
                                                              Container.ResolvedEnumerable <ILogFilter>(LogFilters.Select(lfd => lfd.Name)),
                                                              TraceSources.Select(tsd => tsd.Name).ToArray(),
                                                              Container.ResolvedEnumerable <LogSource>(TraceSources.Select(tsd => tsd.Name)),
                                                              Container.Resolved <LogSource>(AllTraceSourceKey),
                                                              Container.Resolved <LogSource>(NoMatchesTraceSourceKey),
                                                              Container.Resolved <LogSource>(ErrorsTraceSourceKey),
                                                              DefaultCategory,
                                                              TracingEnabled,
                                                              LogWarningWhenNoCategoriesMatch,
                                                              RevertImpersonation))
     {
         Lifetime = TypeRegistrationLifetime.Transient,
         IsDefault = true
     });
 }
コード例 #21
0
        private object tryGetService(
            Type serviceType,
            ServiceConstructorRequest serviceConstructorRequest)
        {
            if (serviceType == null)
            {
                throw new ArgumentNullException(nameof(serviceType));
            }
            object service = serviceProvider.GetService(serviceType);

            return(serviceType.IsInstanceOfType(service)
                                        ? service
                                        : parentServiceRegistrationProvider != null
                                                        ? parentServiceRegistrationProvider.GetService(
                       serviceType,
                       serviceConstructorRequest
                       ?? new ServiceConstructorRequest(
                           TraceSources.For <ServiceRegistrationProviderWrapper>()))
                                                        : ParentServiceProvider?.GetService(serviceType));
        }
コード例 #22
0
 private void setupConfigFileWatcher()
 {
     lock (SyncLock) {
         if (!isInitialized)
         {
             return;
         }
         disposeConfigFileWatcher();
         if (!WatchConfigFileChanges)
         {
             return;
         }
         try {
             Directory.CreateDirectory(GetLogFolderPath());
             configFileWatcher
                 = new FileSystemWatcher(
                       GetLogFolderPath(),
                       GetConfigFileName())
                 {
                 IncludeSubdirectories = false,
                 NotifyFilter          = NotifyFilters.CreationTime
                                         | NotifyFilters.FileName
                                         | NotifyFilters.LastWrite,
                 EnableRaisingEvents = true,
                 };
             configFileWatcher.Changed += handleConfigWatcherChangeEvent;
             configFileWatcher.Created += handleConfigWatcherChangeEvent;
             configFileWatcher.Deleted += handleConfigWatcherChangeEvent;
             configFileWatcher.Error   += handleConfigWatcherError;
         } catch (Exception exception) {
             disposeConfigFileWatcher();
             TraceSources.For(TraceFileFactoryAssembly)
             .Error(
                 exception,
                 "Exception trying to watch for {0} config file changes at '{1}' - '{2}'.",
                 nameof(LogFileFactoryConfig),
                 GetConfigFileFullPath(),
                 exception.Message);
         }
     }
 }
コード例 #23
0
 /// <summary>
 /// Removes a selector added in <see cref="AddSelector"/>.
 /// </summary>
 /// <param name="selector">Not null.</param>
 /// <exception cref="ArgumentNullException"></exception>
 public void RemoveSelector(ILogFileFactorySelector selector)
 {
     if (selector == null)
     {
         throw new ArgumentNullException(nameof(selector));
     }
     lock (SyncLock) {
         if (!selectors.Remove(selector))
         {
             return;
         }
         if (!isInitialized ||
             !addToTraceSources ||
             isInitializing)
         {
             return;
         }
     }
     TraceSources.RemoveSelector(this);
     TraceSources.AddSelector(this);
 }
コード例 #24
0
        private IEnumerable <TypeRegistration> GetRegistrationsCore(IConfigurationSource configurationSource)
        {
            var registrations = new List <TypeRegistration>();

            registrations.Add(CreateLoggingInstrumentationProviderRegistration(configurationSource));
            registrations.Add(CreateLoggingUpdateCoordinatorRegistration());
            registrations.Add(CreateLogWriterRegistration());
            registrations.Add(CreateDefaultLoggingEventLoggerRegistration(configurationSource));
            registrations.AddRange(TraceListeners.SelectMany(tld => tld.GetRegistrations()));
            registrations.AddRange(LogFilters.SelectMany(lfd => lfd.GetRegistrations()));
            registrations.AddRange(Formatters.SelectMany(fd => fd.GetRegistrations()));
            registrations.AddRange(TraceSources.Select(tsd => tsd.GetRegistrations()));
            registrations.Add(
                CreateLogSourceRegistration(SpecialTraceSources.AllEventsTraceSource, AllTraceSourceKey));
            registrations.Add(
                CreateLogSourceRegistration(SpecialTraceSources.NotProcessedTraceSource, NoMatchesTraceSourceKey));
            registrations.Add(
                CreateLogSourceRegistration(SpecialTraceSources.ErrorsTraceSource, ErrorsTraceSourceKey));
            registrations.Add(CreateLogWriterStructureHolderRegistration());
            registrations.Add(CreateTraceManagerRegistration());
            registrations.Add(CreateTracerInstrumentationProviderRegistration(configurationSource));

            return(registrations);
        }
コード例 #25
0
        /// <summary>
        /// Static helper method is used to configure optional verbose tracing.
        /// </summary>
        private static void configureTracing()
        {
            Console.WriteLine("Verbose Tracing? (Y for Yes)");
            ConsoleKey consoleKey = Console.ReadKey().Key;

            Console.WriteLine();
            if (consoleKey != ConsoleKey.Y)
            {
                return;
            }
            void Configure(SimpleTraceSource traceSource)
            {
                traceSource.TraceSource.TryAdd(
                    new Sc.Diagnostics.ConsoleTraceListener
                {
                    Filter = new EventTypeFilter(SourceLevels.All),
                });
                traceSource.TraceSource.Switch.Level = SourceLevels.All;
            }

            TraceSources.AddSelector(new DelegateTraceSourceSelector(Configure));
            TraceSources.For(typeof(Program))
            .Verbose("TraceSources are verbose.");
        }
コード例 #26
0
 private ServiceConstructorRequest newServiceConstructorRequest()
 => new ServiceConstructorRequest(TraceSources.For <BasicContainer>());
コード例 #27
0
 private void handleFileSystemWatcherChanged(object sender, FileSystemEventArgs fileSystemEventArgs)
 {
     TraceSources.For <DirectoryWatcher>()
     .Verbose("Refreshing {0}.", this);
     refresh(fileSystemEventArgs);
 }
コード例 #28
0
        /// <summary>
        /// Gets the configured trace source.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <returns></returns>
        public static TraceSource GetConfiguredTraceSource(this TraceSources instance)
        {
            var key = DeploymentEnvironment.DefaultTraceSourceNameConfigurationKey;

            return(instance.GetConfiguredTraceSource(key));
        }
コード例 #29
0
        // POST: api/ResetPassword
        public async Task <object> Post(HttpRequestMessage requestMessage, [FromBody] JObject request)
        {
            var messageId = requestMessage.GetCorrelationId().ToString();

            TraceSources.AddAdditionalLogItem("RequestMessageId", messageId);
            var emailAddress = "";

            try
            {
                var personReq  = GetRequestJsosn_PersonForRemindPass(request.ToString());
                var companyReq = GetRequestJson_CompanyForRemindPass(request.ToString());

                var person  = personReq.person;
                var company = companyReq.company;

                if (person != null)
                {
                    if (person.member_id == null || person.birthday == null || person.email == null)
                    {
                        PCSiteTraceSource.InvalidRequest_Api("api/reset-password", "必須要素が存在しない", null);
                        return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
                    }
                    var memberId = person.member_id;
                    var strBirth = person.birthday;
                    emailAddress = person.email;

                    if (memberId.Equals(string.Empty) || memberId.Length > 256)
                    {
                        PCSiteTraceSource.InvalidRequest_Api("api/reset-password", "会員ID", null);
                        return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
                    }

                    //入力チェック
                    if (emailAddress.Equals(string.Empty) || emailAddress.Length > 256)
                    {
                        PCSiteTraceSource.InvalidRequest_Api("api/reset-password", "メールアドレス", null);
                        return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
                    }

                    try
                    {
                        DateTime.ParseExact(strBirth, "yyyyMMdd", null);
                    }
                    catch (Exception)
                    {
                        PCSiteTraceSource.InvalidRequest_Api("api/reset-password", "誕生日", null);
                        return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
                    }

                    //個人の場合I003000213 会員ログイン情報取得を呼びだす
                    var reminder = new Toyota.Gbook.WebSite.Authentication.Control.Reminder();
                    //パスワード変更の場合はT-ConnectIdを指定しているため取得できうる内部会員IDは常に1件のみ。
                    var memberInfoList = reminder.CheckPersonalMemberExist(memberId, strBirth, emailAddress)[0];

                    var token = StoreVerificationData(emailAddress, memberInfoList.InternalMemberId, ReminderConstants.IsPersonalMember);

                    await MailSend(new MailAddress(emailAddress), token);

                    return(requestMessage.CreateResponse(HttpStatusCode.Accepted,
                                                         new SuccessResponse_MessageId {
                        message_id = messageId
                    }));
                }
                else if (company != null)
                {
                    if (company.member_id == null || company.frame_no == null || company.email == null)
                    {
                        PCSiteTraceSource.InvalidRequest_Api("api/reset-password", "必須要素が存在しない", null);
                        return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
                    }
                    var memberId = company.member_id;
                    emailAddress = company.email;
                    var vin = company.frame_no;

                    if (memberId.Equals(string.Empty) || memberId.Length > 256)
                    {
                        PCSiteTraceSource.InvalidRequest_Api("api/reset-password", "会員ID", null);
                        return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
                    }

                    if (emailAddress.Equals(string.Empty) || emailAddress.Length > 256)
                    {
                        PCSiteTraceSource.InvalidRequest_Api("api/reset-password", "メールアドレス", null);
                        return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
                    }

                    if (vin.Equals(string.Empty) || vin.Length > 20)
                    {
                        PCSiteTraceSource.InvalidRequest_Api("api/reset-password", "VIN", null);
                        return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
                    }

                    //法人の場合00901:テレマサービス汎用操作API.テレマサービス契約情報取得を呼びだす
                    var reminder   = new Toyota.Gbook.WebSite.Authentication.Control.Reminder();
                    var memberInfo = reminder.CheckCompanyMemberExist(memberId, emailAddress, vin);

                    var token = StoreVerificationData(emailAddress, memberInfo.InternalMemberId, ReminderConstants.IsCompanyMember);

                    await MailSend(new MailAddress(emailAddress), token);

                    return(requestMessage.CreateResponse(HttpStatusCode.Accepted,
                                                         new SuccessResponse_MessageId {
                        message_id = messageId
                    }));
                }

                return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
            }
            catch (InvalidJsonException)
            {
                return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
            }
            catch (UserNotFoundException)
            {
                var encoding    = Encoding.GetEncoding("UTF-8");
                var emailBytes  = encoding.GetBytes(emailAddress);
                var emailBase64 = System.Convert.ToBase64String(emailBytes);
                var ex          = PCSiteTraceSource.UserNotFound_Api(emailBase64);
                var id          = 0;
                ex.TryGetId(out id);
                return(requestMessage.CreateResponse(HttpStatusCode.Unauthorized,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", id.ToString() }
                    }
                }));
            }
            catch (UnexpectedMemberDivisionException)
            {
                var encoding    = Encoding.GetEncoding("UTF-8");
                var emailBytes  = encoding.GetBytes(emailAddress);
                var emailBase64 = System.Convert.ToBase64String(emailBytes);
                var ex          = PCSiteTraceSource.UnexpectedMemberDivision_Api(emailBase64);
                var id          = 0;
                ex.TryGetId(out id);
                return(requestMessage.CreateResponse(HttpStatusCode.Unauthorized,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", id.ToString() }
                    }
                }));
            }
            catch (MissingFileOnBlobException mex)
            {
                var ex = PCSiteTraceSource.FileMissingOnBlob_Api(mex.FileName, mex);
                var id = 0;
                ex.TryGetId(out id);
                return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", id.ToString() }
                    }
                }));
            }
            catch (UnexpectedResultCodeException uex)
            {
                var ex = PCSiteTraceSource.UnexpectedResultCode_Api(uex.api, uex.resultCode);
                var id = 0;
                ex.TryGetId(out id);
                return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", id.ToString() }
                    }
                }));
            }
            catch (GetMemberLoginInfoFailException gex)
            {
                var ex = PCSiteTraceSource.NetworkAccessFail_Api("00000_common/Member.svc/rest/GetMemberLoginInformation", gex);
                var id = 0;
                ex.TryGetId(out id);
                return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", id.ToString() }
                    }
                }));
            }
            catch (TelemaServiceGeneralOperationFailException tex)
            {
                var ex = PCSiteTraceSource.NetworkAccessFail_Api("00000_common/TelemaServiceGeneralOperation.sv/rest/GetTelemaServiceContract", tex);
                var id = 0;
                ex.TryGetId(out id);
                return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", id.ToString() }
                    }
                }));
            }
            catch (WebApplicationFatalException wex)
            {
                var ex = PCSiteTraceSource.MethodFailure(string.Format("パスワードリセットAPIでエラーが発生。URL{0}, レスポンス:{1}", wex.Url, wex.Response));
                var id = 0;
                ex.TryGetId(out id);
                return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", id.ToString() }
                    }
                }));
            }
            catch (Exception e)
            {
                var ex = PCSiteTraceSource.SystemError_Api("パスワードリセットAPIで想定外のエラーが発生", e);
                var id = 0;
                ex.TryGetId(out id);
                return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", id.ToString() }
                    }
                }));
            }
        }
コード例 #30
0
        public async Task <object> Post(HttpRequestMessage requestMessage, [FromBody] JObject request)
        {
            var messageId = requestMessage.GetCorrelationId().ToString();

            TraceSources.AddAdditionalLogItem("RequestMessageId", messageId);
            try
            {
                CheckRequest(request);
                var requestXml     = JsonConvert.DeserializeXmlNode(request.ToString(), "contact");
                var xmlDeclaration = requestXml.CreateXmlDeclaration("1.0", "UTF-8", null);
                using (var stringwriter = new StringWriter())
                    using (var xmltextWriter = new XmlTextWriter(stringwriter))
                    {
                        xmlDeclaration.WriteTo(xmltextWriter);
                        requestXml.WriteTo(xmltextWriter);
                        var requestBodyXml = stringwriter.ToString();
                        var url            = new Uri(Config.Get <string>("Toyota.Gbook.WebSite.Contact.MemberUtilityApi.Url"));
                        using (var client = new HttpClient())
                            using (var m = new HttpRequestMessage
                            {
                                Method = HttpMethod.Post,
                                RequestUri = url,
                                Content = new StringContent(requestBodyXml)
                            })
                            {
                                m.Headers.Add("MessageId", messageId);

                                var xid   = Config.Get <string>("Toyota.Gbook.WebSite.TConnect.XId");
                                var xpass = Config.Get <string>("Toyota.Gbook.WebSite.TConnect.XPassword");
                                m.Headers.Add("X-ID", xid);
                                m.Headers.Add("X-Password", xpass);
                                PCSiteTraceSource.ApiExecute_Api("問合せAPI(オンプレ)", url.ToString(), requestBodyXml);
                                var response = await client.SendAsync(m);

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

                                PCSiteTraceSource.ApiResponsed_Api("問合せAPI(オンプレ)", response.StatusCode, responseXml);

                                if (response.StatusCode == HttpStatusCode.OK)
                                {
                                    var x = new XmlDocument();
                                    x.LoadXml(responseXml);
                                    var code           = x.SelectSingleNode("//contact/result_code").InnerText;
                                    var result_message = x.SelectSingleNode("//contact/result_code_message").InnerText;
                                    if (code == "000000")
                                    {
                                        if (request["registered"]["user_id"] == null)
                                        {
                                            return(new SuccessResponse
                                            {
                                                UserId = "",
                                                Datetime = request["inquiry"]["input_date"].ToString() + request["inquiry"]["input_time"]
                                            });
                                        }
                                        else
                                        {
                                            return(new SuccessResponse
                                            {
                                                UserId = request["registered"]["user_id"].ToString(),
                                                Datetime = request["inquiry"]["input_date"].ToString() + request["inquiry"]["input_time"]
                                            });
                                        }
                                    }
                                    if (code == "100002")
                                    {
                                        //入力チェックエラー
                                        var trace     = PCSiteTraceSource.UnexpectedResultCode_Api(url.ToString(), code);
                                        var errorCode = 0;
                                        trace.TryGetId(out errorCode);
                                        return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
                                    }
                                    if (code == "300000")
                                    {
                                        //DBアクセスエラー
                                        var trace     = PCSiteTraceSource.UnexpectedResultCode_Api(url.ToString(), code);
                                        var errorCode = 0;
                                        trace.TryGetId(out errorCode);
                                        return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                                             new ErrorResponse {
                                            Errors = new Dictionary <string, string> {
                                                { "code", errorCode.ToString() }
                                            }
                                        }));
                                    }

                                    if (code == "500000")
                                    {
                                        var trace     = PCSiteTraceSource.InvalidRequest_Api(url.ToString(), requestBodyXml, null);
                                        var errorCode = 0;
                                        trace.TryGetId(out errorCode);
                                        return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                                             new ErrorResponse {
                                            Errors = new Dictionary <string, string> {
                                                { "code", errorCode.ToString() }
                                            }
                                        }));
                                    }

                                    if (code == "600000")
                                    {
                                        var trace     = PCSiteTraceSource.ValueMissing_Api(url.ToString(), "処理結果コード");
                                        var errorCode = 0;
                                        trace.TryGetId(out errorCode);
                                        return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                                             new ErrorResponse {
                                            Errors = new Dictionary <string, string> {
                                                { "code", errorCode.ToString() }
                                            }
                                        }));
                                    }

                                    if (code == "900000")
                                    {
                                        var trace     = PCSiteTraceSource.SystemError_Api(string.Format("問合せAPI(オンプレ)で想定外のエラーが発生。メッセージ:", result_message), null);
                                        var errorCode = 0;
                                        trace.TryGetId(out errorCode);
                                        return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                                             new ErrorResponse {
                                            Errors = new Dictionary <string, string> {
                                                { "code", errorCode.ToString() }
                                            }
                                        }));
                                    }

                                    var errorTrace        = PCSiteTraceSource.UnexpectedResultCode(url.ToString(), code);
                                    var unexpcetErrorCode = 0;
                                    errorTrace.TryGetId(out unexpcetErrorCode);
                                    return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                                         new ErrorResponse {
                                        Errors = new Dictionary <string, string> {
                                            { "code", unexpcetErrorCode.ToString() }
                                        }
                                    }));
                                }
                                else
                                {
                                    var trace     = PCSiteTraceSource.UnexpectedHttpStatus_Api(url.ToString(), response.StatusCode, "");
                                    var errorCode = 0;
                                    trace.TryGetId(out errorCode);
                                    return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                                         new ErrorResponse {
                                        Errors = new Dictionary <string, string> {
                                            { "code", errorCode.ToString() }
                                        }
                                    }));
                                }
                            }
                    }
            }
            catch (InvalidRequestForContactException ie)
            {
                PCSiteTraceSource.InvalidRequest_Api("tcmypage/api/contact", request.ToString(), ie);
                return(requestMessage.CreateResponse(HttpStatusCode.BadRequest));
            }
            catch (Exception e)
            {
                var trace = PCSiteTraceSource.SystemError_Api("問合せAPIで想定外のエラーが発生", e);
                var code  = 0;
                trace.TryGetId(out code);
                return(requestMessage.CreateResponse(HttpStatusCode.InternalServerError,
                                                     new ErrorResponse {
                    Errors = new Dictionary <string, string> {
                        { "code", code.ToString() }
                    }
                }));
            }
        }