Ejemplo n.º 1
0
 /// <summary>
 /// Constructs the intelligent DB context.
 /// </summary>
 /// <param name="options">The options to construct the DB context with.</param>
 /// <param name="currentUserProvider">The current user provider.</param>
 /// <param name="logger">The logger to use within the IntelligentDbContext.</param>
 protected IntelligentDbContext(DbContextOptions options, IUserInformationProvider currentUserProvider, ILogger logger)
     : base(options)
 {
     CurrentUserProvider = currentUserProvider ?? Nobody.Instance;
     Logger           = logger ?? throw new ArgumentNullException(nameof(logger));
     _createTempLists = options.WithTemporaryLists();
 }
        public static void LogUserInformation(ILogger logger, IUserInformationProvider userInformationProvider)
        {
            if (userInformationProvider == null)
            {
                throw new ArgumentNullException(nameof(userInformationProvider));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (userInformationProvider.IsAuthenticated())
            {
                BitJwtToken bitJwtToken = userInformationProvider.GetBitJwtToken();
                logger.AddLogData("UserId", bitJwtToken.UserId);
                if (bitJwtToken.CustomProps != null)
                {
                    foreach (var keyVal in bitJwtToken.CustomProps)
                    {
                        logger.AddLogData(keyVal.Key, keyVal.Value);
                    }
                }
                logger.AddLogData("AuthenticationType", userInformationProvider.GetAuthenticationType());
                logger.AddLogData("ClientId", userInformationProvider.GetClientId());
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="securityService"></param>
 /// <param name="userInformationProvider"></param>
 public RoleMenuController(
     IRoleManagementService securityService,
     IUserInformationProvider userInformationProvider)
 {
     _roleManagementService   = securityService;
     _userInformationProvider = userInformationProvider;
 }
Ejemplo n.º 4
0
 public static void LogUserInformation(ILogger logger, IUserInformationProvider userInformationProvider)
 {
     if (userInformationProvider.IsAuthenticated())
     {
         logger.AddLogData("UserId", userInformationProvider.GetCurrentUserId());
         logger.AddLogData("AuthenticationType", userInformationProvider.GetAuthenticationType());
     }
 }
Ejemplo n.º 5
0
        public virtual bool Authorize([NotNull] DashboardContext context)
        {
            IOwinContext             owinContext             = new OwinContext(context.GetOwinEnvironment());
            IUserInformationProvider userInformationProvider = owinContext.GetDependencyResolver().Resolve <IUserInformationProvider>();
            bool isAuthenticated = userInformationProvider.IsAuthenticated();

            return(isAuthenticated);
        }
Ejemplo n.º 6
0
 public ChangeSetsController(IChangeSetRepository changeSetsRepository, IMessageSender messageSender, IUserInformationProvider userInformationProvider, IBitChangeSetManagerRepository<User> usersRepository)
     : base(changeSetsRepository)
 {
     _changeSetsRepository = changeSetsRepository;
     _messageSender = messageSender;
     _userInformationProvider = userInformationProvider;
     _usersRepository = usersRepository;
 }
Ejemplo n.º 7
0
        public DefaultMessageHubEvents(IUserInformationProvider userInformationProvider)
        {
            if (userInformationProvider == null)
            {
                throw new ArgumentNullException(nameof(userInformationProvider));
            }

            _userInformationProvider = userInformationProvider;
        }
Ejemplo n.º 8
0
 public ProductLicense(RSACryptoServiceProvider cryptoService, IMachineIdentifierProvider identifierService, ProductLicenseInfo licenseInfo, IUserInformationProvider userInfoProvider)
 {
     _hashService       = new SHA1CryptoServiceProvider();
     _cryptoService     = cryptoService;
     _identifierService = identifierService;
     _userInfoProvider  = userInfoProvider;
     LicenseInfo        = licenseInfo;
     ProcessLicense();
 }
Ejemplo n.º 9
0
        public async Task Invoke(HttpContext context)
        {
            ILogger logger = context.RequestServices.GetService <ILogger>();

            IUserInformationProvider userInformationProvider = context.RequestServices.GetService <IUserInformationProvider>();

            LogUserInformationMiddleware.LogUserInformation(logger, userInformationProvider);

            await Next.Invoke(context);
        }
Ejemplo n.º 10
0
        public Task Invoke(HttpContext context)
        {
            ILogger logger = context.RequestServices.GetRequiredService <ILogger>();

            IUserInformationProvider userInformationProvider = context.RequestServices.GetRequiredService <IUserInformationProvider>();

            LogUserInformationMiddleware.LogUserInformation(logger, userInformationProvider);

            return(_next.Invoke(context));
        }
Ejemplo n.º 11
0
 public MachineInformationProvider(ILegacyApi legacyApi, IUserInformationProvider userInformationProvider, IMACInformationProvider macInformationProvider)
 {
     CodeContract.RequiresArgumentNotNull <ILegacyApi>(legacyApi, "legacyApi");
     CodeContract.RequiresArgumentNotNull <IUserInformationProvider>(userInformationProvider, "userInformationProvider");
     CodeContract.RequiresArgumentNotNull <IMACInformationProvider>(macInformationProvider, "macInformationProvider");
     this.legacyApi = legacyApi;
     this.userInformationProvider = userInformationProvider;
     this.macInformationProvider  = macInformationProvider;
     machineId = new Lazy <Guid>(() => CalculateMachineId(), LazyThreadSafetyMode.ExecutionAndPublication);
 }
Ejemplo n.º 12
0
        public ProductLicenseManager(ITraceManager traceManager, string publicXmlKey, ILicenseStore licenseStore, IMachineIdentifierProvider identifierService, IUserInformationProvider userInfoProvider)
        {
            _traceManager = traceManager;

            _cryptoService = new RSACryptoServiceProvider();
            _cryptoService.FromXmlString(publicXmlKey);

            _licenseStore      = licenseStore;
            _identifierService = identifierService;
            _userInfoProvider  = userInfoProvider;
        }
        public OpenIdConnectAuthenticationOptionsBuilder(OktaMvcOptions oktaMvcOptions, IUserInformationProvider userInformationProvider = null)
        {
            _oktaMvcOptions       = oktaMvcOptions;
            _issuer               = UrlHelper.CreateIssuerUrl(oktaMvcOptions.OktaDomain, oktaMvcOptions.AuthorizationServerId);
            _httpClient           = new HttpClient(new UserAgentHandler("okta-aspnet", typeof(OktaMiddlewareExtensions).Assembly.GetName().Version));
            _configurationManager = new ConfigurationManager <OpenIdConnectConfiguration>(
                _issuer + "/.well-known/openid-configuration",
                new OpenIdConnectConfigurationRetriever(),
                new HttpDocumentRetriever(_httpClient));

            _userInformationProvider = userInformationProvider ?? new UserInformationProvider(oktaMvcOptions, _issuer, _configurationManager);
        }
Ejemplo n.º 14
0
        public virtual bool Authorize([NotNull] DashboardContext context)
        {
#if DotNetCore
            throw new NotImplementedException();
#else
            IUserInformationProvider userInformationProvider = null;
            IOwinContext             owinContext             = new OwinContext(context.GetOwinEnvironment());
            userInformationProvider = owinContext.GetDependencyResolver().Resolve <IUserInformationProvider>();
            bool isAuthenticated = userInformationProvider.IsAuthenticated();
            return(isAuthenticated);
#endif
        }
Ejemplo n.º 15
0
        public virtual bool Authorize([NotNull] DashboardContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IServiceProvider         serviceProvider         = GetServiceProvider(context);
            IUserInformationProvider userInformationProvider = serviceProvider.GetRequiredService <IUserInformationProvider>();
            bool isAuthenticated = userInformationProvider.IsAuthenticated();

            return(isAuthenticated);
        }
        public virtual bool Authorize([NotNull] DashboardContext context)
        {
            IUserInformationProvider userInformationProvider = null;

#if NET461
            IOwinContext owinContext = new OwinContext(context.GetOwinEnvironment());
            userInformationProvider = owinContext.GetDependencyResolver().Resolve <IUserInformationProvider>();
#else
            userInformationProvider = Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService <IUserInformationProvider>(context.GetHttpContext().RequestServices);
#endif
            bool isAuthenticated = userInformationProvider.IsAuthenticated();
            return(isAuthenticated);
        }
Ejemplo n.º 17
0
        public override Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            ILogger logger = dependencyResolver.Resolve <ILogger>();

            IUserInformationProvider userInformationProvider =
                dependencyResolver.Resolve <IUserInformationProvider>();

            LogUserInformation(logger, userInformationProvider);

            return(Next.Invoke(context));
        }
Ejemplo n.º 18
0
        public static IServiceProvider CreateServiceProvider <TContext>(IUserInformationProvider currentUserProvider = null, ITestOutputHelper outputHelper = null, bool withTempTables = true, bool seed = true) where TContext : ExampleContext
        {
            var col = new ServiceCollection();

            var logger = new ExampleLogger(outputHelper);

            col.AddSingleton <ILogger>(logger);

            if (currentUserProvider is null)
            {
                currentUserProvider = new ExampleUserInformationProvider()
                {
                    CurrentUser = ExampleUserInformationProvider.Users.Maximillian
                }
            }
            ;

            col.AddSingleton <IUserInformationProvider>(currentUserProvider);

            var options = CreateOptions <TContext>(withTempTables);

            col.AddSingleton <DbContextOptions <TContext> >(options);

            col.AddSingleton <DbContextOptions>(options);

            col.AddDbContext <TContext>();

            var sp = col.BuildServiceProvider();

            using (var scope = sp.CreateScope())
            {
                using (var preContext = scope.ServiceProvider.GetRequiredService <TContext>())
                {
                    preContext.Database.EnsureCreated();
                }
            }

            if (seed)
            {
                using (var scope = sp.CreateScope())
                {
                    using (var preContext = scope.ServiceProvider.GetRequiredService <TContext>())
                    {
                        preContext.Seed();
                    }
                }
            }

            return(sp);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Set up telemetry session properties
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="initializerObject"></param>
        /// <param name="isCloned"></param>
        private TelemetrySession(TelemetrySessionSettings settings, bool isCloned, TelemetrySessionInitializer initializerObject)
        {
            CodeContract.RequiresArgumentNotNull <TelemetrySessionInitializer>(initializerObject, "initializerObject");
            initializerObject.Validate();
            initializerObject.AppInsightsInstrumentationKey = settings.AppInsightsInstrumentationKey;
            initializerObject.AsimovInstrumentationKey      = settings.AsimovInstrumentationKey;
            TelemetryService.EnsureEtwProviderInitialized();
            sessionInitializer      = initializerObject;
            sessionSettings         = settings;
            isSessionCloned         = isCloned;
            cancellationTokenSource = initializerObject.CancellationTokenSource;
            diagnosticTelemetry     = initializerObject.DiagnosticTelemetry;
            identityTelemetry       = initializerObject.IdentityTelemetry;
            optinStatusReader       = initializerObject.OptinStatusReader;
            channelValidators       = initializerObject.ChannelValidators;
            telemetryBufferChannel  = new TelemetryBufferChannel();
            initializerObject.WatsonSessionChannelBuilder.Build(this);
            WatsonSessionChannel sessionChannel = initializerObject.WatsonSessionChannelBuilder.WatsonSessionChannel;

            if (IsValidChannel(sessionChannel))
            {
                watsonSessionChannel = sessionChannel;
            }
            machineInformationProvider    = initializerObject.MachineInformationProvider;
            macInformationProvider        = initializerObject.MACInformationProvider;
            userInformationProvider       = initializerObject.UserInformationProvider;
            defaultContextPropertyManager = initializerObject.DefaultContextPropertyManager;
            persistentPropertyBag         = initializerObject.PersistentPropertyBag;
            initializerObject.EventProcessorChannelBuilder.Build(this);
            persistentSharedProperties = initializerObject.PersistentSharedProperties;
            EventProcessor             = initializerObject.EventProcessorChannelBuilder.EventProcessor;
            if (initializerObject.CustomActionToAdd != null)
            {
                foreach (IEventProcessorAction item in initializerObject.CustomActionToAdd)
                {
                    EventProcessor.AddCustomAction(item);
                }
            }
            eventProcessorChannel    = initializerObject.EventProcessorChannelBuilder.EventProcessorChannel;
            telemetryManifestManager = new Lazy <ITelemetryManifestManager>(() => initializerObject.TelemetryManifestManagerBuilder.Build(this));
            contextScheduler         = initializerObject.ContextScheduler;
            if (initializerObject.ChannelsToAdd != null)
            {
                AddSessionChannels(initializerObject.ChannelsToAdd);
            }
            defaultContext = CreateDefaultContext();
            macInformationProvider.MACAddressHashCalculationCompleted += MACAddressHashCalculationCompleted;
            identityTelemetry.IdentityInformationProvider.HardwareIdCalculationCompleted += HardwareIdCalculationCompleted;
        }
        public Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            ILogger logger = context.RequestServices.GetRequiredService <ILogger>();

            IUserInformationProvider userInformationProvider = context.RequestServices.GetRequiredService <IUserInformationProvider>();

            LogUserInformationMiddleware.LogUserInformation(logger, userInformationProvider);

            return(_next.Invoke(context));
        }
Ejemplo n.º 21
0
        public UsersSettingsController(IUserInformationProvider userInformationProvider, IRepository <UserSetting> usersSettingsRepository)
        {
            if (userInformationProvider == null)
            {
                throw new ArgumentNullException(nameof(userInformationProvider));
            }

            if (usersSettingsRepository == null)
            {
                throw new ArgumentNullException(nameof(usersSettingsRepository));
            }

            _userInformationProvider = userInformationProvider;
            _usersSettingsRepository = usersSettingsRepository;
        }
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            ILogger logger = dependencyResolver.Resolve <ILogger>();

            IUserInformationProvider userInformationProvider =
                dependencyResolver.Resolve <IUserInformationProvider>();

            if (userInformationProvider.IsAuthenticated())
            {
                logger.AddLogData("UserId", userInformationProvider.GetCurrentUserId());
                logger.AddLogData("AuthenticationType", userInformationProvider.GetAuthenticationType());
            }

            await Next.Invoke(context);
        }
Ejemplo n.º 23
0
 public BitChangeSetManagerAppMessageHubEvents(IUserInformationProvider userInformationProvider, IBitChangeSetManagerRepository <User> usersRepository)
     : base(userInformationProvider)
 {
     _userInformationProvider = userInformationProvider;
     _usersRepository         = usersRepository;
 }
Ejemplo n.º 24
0
        private static TelemetrySessionInitializer BuildInitializer(TelemetrySessionSettings telemetrySessionSettings)
        {
            //IL_0012: Unknown result type (might be due to invalid IL or missing references)
            //IL_0018: Expected O, but got Unknown
            CancellationTokenSource cancellationTokenSource          = new CancellationTokenSource();
            DiagnosticTelemetry     diagnosticTelemetry              = new DiagnosticTelemetry();
            EnvironmentTools        environmentTools                 = new EnvironmentTools();
            RegistryTools           registryTools                    = (RegistryTools)(object)new RegistryTools();
            ProcessTools            processTools                     = new ProcessTools();
            ILegacyApi                   legacyApi                   = GetLegacyApi((IRegistryTools)(object)registryTools);
            IPersistentPropertyBag       persistentStorage           = CreatePersistentPropertyBag(string.Empty);
            IPersistentPropertyBag       persistentPropertyBag       = CreatePersistentPropertyBag("c57a9efce9b74de382d905a89852db71");
            IMACInformationProvider      mACInformationProvider      = GetMACInformationProvider(processTools, persistentStorage, legacyApi);
            IInternalSettings            internalSettings            = GetInternalSettings(diagnosticTelemetry, (IRegistryTools)(object)registryTools);
            IHostInformationProvider     hostInformationProvider     = GetHostInformationProvider();
            IUserInformationProvider     userInformationProvider     = GetUserInformationProvider((IRegistryTools)(object)registryTools, internalSettings, environmentTools, legacyApi, telemetrySessionSettings);
            MachineInformationProvider   machineInformationProvider  = new MachineInformationProvider(legacyApi, userInformationProvider, mACInformationProvider);
            IIdentityInformationProvider identityInformationProvider = GetIdentityInformationProvider();
            IPersistentPropertyBag       persistentPropertyBag2      = CreatePersistentPropertyBag(hostInformationProvider.ProcessName);
            TelemetryScheduler           telemetryScheduler          = new TelemetryScheduler();
            OptOutAction                 optOutAction                = new OptOutAction();

            optOutAction.AddOptOutFriendlyEventName("vs/telemetryapi/session/initialized");
            optOutAction.AddOptOutFriendlyEventName("context/postproperty");
            optOutAction.AddOptOutFriendlyPropertiesList(new List <string>
            {
                "Context.Default.VS.Core.BranchName",
                "Context.Default.VS.Core.BuildNumber",
                "Context.Default.VS.Core.ExeName",
                "Context.Default.VS.Core.ExeVersion",
                "Context.Default.VS.Core.HardwareId",
                "Context.Default.VS.Core.MacAddressHash",
                "Context.Default.VS.Core.Machine.Id",
                "Context.Default.VS.Core.SkuName",
                "Context.Default.VS.Core.OS.Version",
                "Context.Default.VS.Core.ProcessId",
                "Context.Default.VS.Core.User.Id",
                "Context.Default.VS.Core.User.IsMicrosoftInternal",
                "Context.Default.VS.Core.User.IsOptedIn",
                "Context.Default.VS.Core.User.Location.GeoId",
                "Context.Default.VS.Core.User.Type",
                "Context.Default.VS.Core.Version",
                "Reserved.EventId",
                "Reserved.SessionId",
                "Reserved.TimeSinceSessionStart",
                "VS.Core.Locale.Product",
                "VS.Core.Locale.System",
                "VS.Core.Locale.User",
                "VS.Core.Locale.UserUI",
                "VS.Core.SkuId",
                "VS.Sqm.SkuId"
            });
            ClientSideThrottlingAction item = new ClientSideThrottlingAction(new List <string>
            {
                "context/create",
                "context/close",
                "context/postproperty",
                "vs/core/command",
                "vs/core/extension/installed",
                "vs/core/sessionstart",
                "vs/core/sessionend",
                "vs/telemetryapi/session/initialized",
                "vs/telemetryapi/clientsidethrottling",
                "vs/telemetryapi/manifest/load",
                "vs/telemetryapi/piiproperties"
            }, 0.0, 0L);
            PIIPropertyProcessor  pIIPropertyProcessor = new PIIPropertyProcessor();
            PiiAction             item2 = new PiiAction(pIIPropertyProcessor);
            ComplexPropertyAction item3 = new ComplexPropertyAction(new JsonComplexObjectSerializerFactory(), pIIPropertyProcessor);

            return(new TelemetrySessionInitializer
            {
                CancellationTokenSource = cancellationTokenSource,
                SessionId = Guid.NewGuid().ToString(),
                AppInsightsInstrumentationKey = "f144292e-e3b2-4011-ac90-20e5c03fbce5",
                AsimovInstrumentationKey = "AIF-312cbd79-9dbb-4c48-a7da-3cc2a931cb70",
                DiagnosticTelemetry = diagnosticTelemetry,
                IdentityTelemetry = new IdentityTelemetry(identityInformationProvider, telemetryScheduler),
                EnvironmentTools = environmentTools,
                RegistryTools = (IRegistryTools2)(object)registryTools,
                ProcessTools = processTools,
                LegacyApi = legacyApi,
                InternalSettings = internalSettings,
                HostInformationProvider = hostInformationProvider,
                MachineInformationProvider = machineInformationProvider,
                UserInformationProvider = userInformationProvider,
                MACInformationProvider = mACInformationProvider,
                EventProcessorScheduler = telemetryScheduler,
                TelemetryManifestManagerBuilder = new TelemetryManifestManagerBuilder(),
                DefaultContextPropertyManager = new DefaultContextPropertyManager(GetPropertyProviders((IRegistryTools)(object)registryTools, environmentTools, hostInformationProvider, machineInformationProvider, mACInformationProvider, userInformationProvider, persistentPropertyBag, identityInformationProvider)),
                PersistentStorage = persistentStorage,
                PersistentSharedProperties = persistentPropertyBag,
                PersistentPropertyBag = persistentPropertyBag2,
                ChannelValidators = new List <IChannelValidator>
                {
                    new RegistryChannelValidator(internalSettings),
                    new InternalChannelValidator(userInformationProvider),
                    new DisabledTelemetryChannelValidator(internalSettings)
                },
                CustomActionToAdd = new List <IEventProcessorAction>
                {
                    optOutAction,
                    new EnforceAIRestrictionAction(),
                    item2,
                    item3,
                    new MetricAction(),
                    new SettingAction(),
                    item,
                    new SuppressEmptyPostPropertyEventAction()
                },
                EventProcessorChannelBuilder = new EventProcessorChannelBuilder(persistentPropertyBag2, telemetryScheduler),
                WatsonSessionChannelBuilder = new WatsonSessionChannelBuilder(internalSettings.FaultEventWatsonSamplePercent(), internalSettings.FaultEventMaximumWatsonReportsPerSession(), internalSettings.FaultEventMinimumSecondsBetweenWatsonReports(), ChannelProperties.Default),
                OptinStatusReader = GetOptInStatusReader((IRegistryTools2)(object)registryTools),
                ProcessCreationTime = GetProcessCreationTime()
            });
        }
Ejemplo n.º 25
0
        private static IEnumerable <IPropertyProvider> GetPropertyProviders(IRegistryTools registryTools, IEnvironmentTools environmentTools, IHostInformationProvider host, IMachineInformationProvider machine, IMACInformationProvider macAddress, IUserInformationProvider user, IPersistentPropertyBag sharedProperties, IIdentityInformationProvider identity)
        {
            yield return(new IdentityPropertyProvider());

            if (Platform.IsMac)
            {
                yield return(new MacHostPropertyProvider(host, new NsBundleInformationProvider()));

                yield return(new AssemblyPropertyProvider());

                yield return(new MacLocalePropertyProvider());

                yield return(new MacMachinePropertyProvider(machine, registryTools, macAddress));

                yield return(new MacOSPropertyProvider(environmentTools));

                yield return(new MacUserPropertyProvider(user));

                yield return(new PersistentSharedPropertyProvider(sharedProperties));
            }
            else if (Platform.IsLinux)
            {
                yield return(new LinuxHostPropertyProvider(host));

                yield return(new AssemblyPropertyProvider());

                yield return(new LinuxLocalePropertyProvider());

                yield return(new PersistentSharedPropertyProvider(sharedProperties));
            }
            else
            {
                yield return(new WindowsHostPropertyProvider(host));

                yield return(new AssemblyPropertyProvider());

                yield return(new WindowsLocalePropertyProvider(registryTools));

                yield return(new WindowsMachinePropertyProvider(machine, registryTools, macAddress));

                yield return(new WindowsOSPropertyProvider(environmentTools, registryTools));

                yield return(new WindowsUserPropertyProvider(user));

                yield return(new PersistentSharedPropertyProvider(sharedProperties));
            }
        }
Ejemplo n.º 26
0
        private void PerformLog(LogEntry logEntry)
        {
            RequestTelemetry requestTelemetry = null;

            if (logEntry.LogData.Any(ld => ld.Key == nameof(IRequestInformationProvider.DisplayUrl)) && HttpContextAccessor.HttpContext != null)
            {
                HttpContext httpContext = HttpContextAccessor.HttpContext;

                if (!httpContext.Items.ContainsKey(nameof(RequestTelemetry)))
                {
                    throw new InvalidOperationException($"Register app insight logger using dependencyManager.{nameof(IDependencyManagerExtensions.RegisterApplicationInsights)}();");
                }

                requestTelemetry = (RequestTelemetry)httpContext.Items[nameof(RequestTelemetry)];

                IUserInformationProvider userInformationProvider = httpContext.RequestServices.GetRequiredService <IUserInformationProvider>();

                if (userInformationProvider.IsAuthenticated())
                {
                    requestTelemetry.Context.User.AccountId = requestTelemetry.Context.User.AuthenticatedUserId = userInformationProvider.GetCurrentUserId();
                }
            }

            List <KeyVal> keyValues = logEntry.LogData.Select(ld =>
            {
                string k = ld.Key;

                if (k == nameof(IRequestInformationProvider.HttpMethod) ||
                    k == nameof(IRequestInformationProvider.DisplayUrl) ||
                    k == nameof(IRequestInformationProvider.UserAgent) ||
                    k == "UserId" ||
                    k == "ResponseStatusCode" ||
                    k == nameof(IRequestInformationProvider.ClientIp) ||
                    ld.Value == null)
                {
                    return(null); // Already being logged by app insights!
                }
                string v = null;

                if (ld.Value is string valueAsStr)
                {
                    v = valueAsStr;
                }

                if (k == "ClientLogs" || k == "OperationArgs")
                {
                    v = Formatter.Serialize(ld.Value);
                }
                else
                {
                    v = ld.Value.ToString();
                }

                return(new KeyVal {
                    Key = k, Value = v
                });
            })
                                      .Where(d => d != null)
                                      .ToList();

            keyValues.Add(new KeyVal {
                Key = nameof(LogEntry.MemoryUsage), Value = logEntry.MemoryUsage.ToString()
            });

            if (logEntry.AppServerDateTime.HasValue)
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerDateTime), Value = logEntry.AppServerDateTime.ToString()
                });
            }

            keyValues.Add(new KeyVal {
                Key = nameof(LogEntry.Severity), Value = logEntry.Severity
            });
            keyValues.Add(new KeyVal {
                Key = nameof(LogEntry.Message), Value = logEntry.Message
            });

            if (logEntry.Id.HasValue)
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.Id), Value = logEntry.Id.ToString()
                });
            }

            if (logEntry.AppServerThreadId.HasValue)
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerThreadId), Value = logEntry.AppServerThreadId.ToString()
                });
            }

            if (requestTelemetry != null)
            {
                LogData userAgent = logEntry.LogData.FirstOrDefault(ld => ld.Key == nameof(IRequestInformationProvider.UserAgent));
                if (userAgent != null)
                {
                    requestTelemetry.Context.User.UserAgent = (string)userAgent.Value;
                }

                foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                {
                    if (!requestTelemetry.Properties.ContainsKey(keyVal.Key))
                    {
                        requestTelemetry.Properties.Add(keyVal.Key, keyVal.Value);
                    }
                }
            }
            else
            {
                TelemetryClient telemetryClient = new TelemetryClient();

                Dictionary <string, string> customData = new Dictionary <string, string>();

                foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                {
                    if (!customData.ContainsKey(keyVal.Key))
                    {
                        customData.Add(keyVal.Key, keyVal.Value);
                    }
                }

                Exception ex = null;

                try
                {
                    customData.TryGetValue("ExceptionTypeAssemblyQualifiedName", out string exceptionTypeAssemblyQualifiedName);

                    if (!string.IsNullOrEmpty(exceptionTypeAssemblyQualifiedName))
                    {
                        ex = (Exception)Activator.CreateInstance(Type.GetType(exceptionTypeAssemblyQualifiedName) ?? throw new InvalidOperationException($"{exceptionTypeAssemblyQualifiedName} could not be found"), args: new object[] { logEntry.Message });
                    }
                }
                catch { }

                if (ex == null)
                {
                    switch (logEntry.Severity)
                    {
                    case "Information":
                        ex = new InformationException(logEntry.Message);
                        break;

                    case "Warning":
                        ex = new WarningException(logEntry.Message);
                        break;

                    case "Error":
                        ex = new ErrorException(logEntry.Message);
                        break;

                    case "Fatal":
                        ex = new FatalException(logEntry.Message);
                        break;

                    default:
                        ex = new Exception(logEntry.Message);
                        break;
                    }
                }

                telemetryClient.TrackException(ex, customData);
            }
        }
        private void PerformLog(LogEntry logEntry)
        {
            TelemetryClient          telemetryClient         = null;
            IUserInformationProvider userInformationProvider = null;
            bool isPerRequestTelemetryClient = false;

            if (logEntry.LogData.Any(ld => ld.Key == nameof(IRequestInformationProvider.RequestUri)))
            {
                IOwinContext owinContext = OwinContext.Value;

                IDependencyResolver resolver = owinContext.GetDependencyResolver();

                telemetryClient = resolver.Resolve <TelemetryClient>();

                userInformationProvider = resolver.Resolve <IUserInformationProvider>();

                isPerRequestTelemetryClient = true;
            }

            List <KeyVal> keyValues = logEntry.LogData.Select(ld =>
            {
                string k = ld.Key;

                if (k == nameof(IRequestInformationProvider.HttpMethod) ||
                    k == nameof(IRequestInformationProvider.RequestUri) ||
                    k == nameof(IRequestInformationProvider.UserAgent) ||
                    k == "UserId" ||
                    k == "ResponseStatusCode" ||
                    k == nameof(IRequestInformationProvider.ClientIp) ||
                    ld.Value == null)
                {
                    return(null);
                }

                string v = null;

                if (ld.Value is string valueAsStr)
                {
                    v = valueAsStr;
                }

                if (k == "ClientLogs" || k == "OperationArgs")
                {
                    v = Formatter.Serialize(ld.Value);
                }
                else
                {
                    v = ld.Value.ToString();
                }

                return(new KeyVal {
                    Key = k, Value = v
                });
            })
                                      .Where(d => d != null)
                                      .ToList();

            try
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppEnvironmentName), Value = logEntry.AppEnvironmentName
                });

                if (logEntry.AppServerProcessId.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerProcessId), Value = logEntry.AppServerProcessId.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerAppDomainName), Value = logEntry.AppServerAppDomainName
                });

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerOSVersion), Value = logEntry.AppServerOSVersion
                });

                if (logEntry.AppServerDateTime.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerDateTime), Value = logEntry.AppServerDateTime.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerName), Value = logEntry.AppServerName
                });

                if (logEntry.AppWasInDebugMode.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppWasInDebugMode), Value = logEntry.AppWasInDebugMode.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerUserAccountName), Value = logEntry.AppServerUserAccountName
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppVersion), Value = logEntry.AppVersion
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.ApplicationName), Value = logEntry.ApplicationName
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.Severity), Value = logEntry.Severity
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.Message), Value = logEntry.Message
                });

                if (logEntry.Id.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.Id), Value = logEntry.Id.ToString()
                    });
                }

                if (logEntry.AppServerThreadId.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerThreadId), Value = logEntry.AppServerThreadId.ToString()
                    });
                }

                if (isPerRequestTelemetryClient == true)
                {
                    if (userInformationProvider.IsAuthenticated())
                    {
                        telemetryClient.Context.User.AccountId = telemetryClient.Context.User.AuthenticatedUserId = userInformationProvider.GetCurrentUserId();
                    }

                    LogData userAgent = logEntry.LogData.FirstOrDefault(ld => ld.Key == nameof(IRequestInformationProvider.UserAgent));
                    if (userAgent != null)
                    {
                        telemetryClient.Context.User.UserAgent = (string)userAgent.Value;
                    }

                    foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                    {
                        if (!telemetryClient.Context.Properties.ContainsKey(keyVal.Key))
                        {
                            telemetryClient.Context.Properties.Add(keyVal.Key, keyVal.Value);
                        }
                    }
                }
                else
                {
                    telemetryClient = new TelemetryClient();

                    Dictionary <string, string> customData = new Dictionary <string, string>();

                    foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                    {
                        if (!customData.ContainsKey(keyVal.Key))
                        {
                            customData.Add(keyVal.Key, keyVal.Value);
                        }
                    }

                    Exception ex = null;

                    try
                    {
                        customData.TryGetValue("ExceptionTypeAssemblyQualifiedName", out string exceptionTypeAssemblyQualifiedName);

                        if (!string.IsNullOrEmpty(exceptionTypeAssemblyQualifiedName))
                        {
                            ex = (Exception)Activator.CreateInstance(Type.GetType(exceptionTypeAssemblyQualifiedName) ?? throw new InvalidOperationException($"{exceptionTypeAssemblyQualifiedName} could not be found"), args: new object[] { logEntry.Message });
                        }
                    }
                    catch { }

                    if (ex == null)
                    {
                        switch (logEntry.Severity)
                        {
                        case "Information":
                            ex = new InformationException(logEntry.Message);
                            break;

                        case "Warning":
                            ex = new WarningException(logEntry.Message);
                            break;

                        case "Error":
                            ex = new ErrorException(logEntry.Message);
                            break;

                        case "Fatal":
                            ex = new FatalException(logEntry.Message);
                            break;

                        default:
                            ex = new Exception(logEntry.Message);
                            break;
                        }
                    }

                    telemetryClient.TrackException(ex, customData);
                }
            }
            finally
            {
                telemetryClient.Flush();
            }
        }
Ejemplo n.º 28
0
        private void PerformLog(LogEntry logEntry)
        {
            if (DiagnosticContext == null || SerilogLogger == null)
            {
                throw new InvalidOperationException($"Configure asp.net core & serilog using https://github.com/serilog/serilog-aspnetcore");
            }

            bool isRequestLogEntry = false;

            if (logEntry.LogData.Any(ld => ld.Key == nameof(IRequestInformationProvider.DisplayUrl)) && HttpContextAccessor.HttpContext != null)
            {
                isRequestLogEntry = true;

                HttpContext httpContext = HttpContextAccessor.HttpContext;

                IUserInformationProvider userInformationProvider = httpContext.RequestServices.GetRequiredService <IUserInformationProvider>();
            }

            var keyValues = logEntry.LogData.Select(ld =>
            {
                string k = ld.Key;

                if (k == nameof(IRequestInformationProvider.HttpMethod) ||
                    k == nameof(IRequestInformationProvider.DisplayUrl) ||
                    k == "ResponseStatusCode" ||
                    ld.Value == null)
                {
                    return(Key: null, Value: null);  // Already being logged by serilog!
                }
                string v = null;

                if (ld.Value is string valueAsStr)
                {
                    v = valueAsStr;
                }

                if (k == "ClientLogs" || k == "OperationArgs")
                {
                    v = Formatter.Serialize(ld.Value);
                }
                else
                {
                    v = ld.Value.ToString();
                }

                return(Key: k, Value: v);
            })
                            .Where(d => d.Key != null)
                            .ToList();

            keyValues.Add((Key: nameof(LogEntry.MemoryUsage), Value: logEntry.MemoryUsage.ToString()));

            if (logEntry.AppServerDateTime.HasValue)
            {
                keyValues.Add((Key: nameof(LogEntry.AppServerDateTime), Value: logEntry.AppServerDateTime.ToString()));
            }

            keyValues.Add((Key: nameof(LogEntry.Severity), Value: logEntry.Severity));
            keyValues.Add((Key: nameof(LogEntry.Message), Value: logEntry.Message));

            if (logEntry.Id.HasValue)
            {
                keyValues.Add((Key: nameof(LogEntry.Id), Value: logEntry.Id.ToString()));
            }

            if (logEntry.AppServerThreadId.HasValue)
            {
                keyValues.Add((Key: nameof(LogEntry.AppServerThreadId), Value: logEntry.AppServerThreadId.ToString()));
            }

            foreach (var(Key, Value) in keyValues.OrderBy(kv => kv.Key))
            {
                DiagnosticContext.Set(Key, Value);
            }

            if (isRequestLogEntry == true)
            {
                LogData userAgent = logEntry.LogData.FirstOrDefault(ld => ld.Key == nameof(IRequestInformationProvider.UserAgent));

                if (userAgent != null)
                {
                    DiagnosticContext.Set("UserAgent", userAgent.Value);
                }
            }
            else
            {
                Exception ex = null;

                try
                {
                    var(Key, Value) = keyValues.ExtendedSingleOrDefault("Finding ExceptionTypeAssemblyQualifiedName...", kv => kv.Key == "ExceptionTypeAssemblyQualifiedName");

                    if (!string.IsNullOrEmpty(Value))
                    {
                        ex = (Exception)Activator.CreateInstance(Type.GetType(Value) ?? throw new InvalidOperationException($"{Value} could not be found"), args: new object[] { logEntry.Message });
                    }
                }
                catch { }

                LogEventLevel level = logEntry.Severity switch
                {
                    "Information" => LogEventLevel.Information,
                    "Warning" => LogEventLevel.Warning,
                    "Error" => LogEventLevel.Error,
                    "Fatal" => LogEventLevel.Fatal,
                    _ => LogEventLevel.Debug,
                };

                SerilogLogger.Write(level, ex?.Message ?? logEntry.Message);
            }
        }
Ejemplo n.º 29
0
 public InternalChannelValidator(IUserInformationProvider theUserInformationProvider)
 {
     CodeContract.RequiresArgumentNotNull <IUserInformationProvider>(theUserInformationProvider, "theUserInformationProvider");
     userInformationProvider = theUserInformationProvider;
 }
Ejemplo n.º 30
0
        public virtual void Initialize(ITelemetry telemetry)
        {
            if (telemetry == null)
            {
                throw new ArgumentNullException(nameof(telemetry));
            }

            LogEntryAppLevelConstantInfo logEntryAppLevelConstantInfo = LogEntryAppLevelConstantInfo.GetAppConstantInfo();

            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.ApplicationName)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.ApplicationName), logEntryAppLevelConstantInfo.ApplicationName);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppVersion)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppVersion), logEntryAppLevelConstantInfo.AppVersion);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppEnvironmentName)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppEnvironmentName), logEntryAppLevelConstantInfo.AppEnvironmentName);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppWasInDebugMode)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppWasInDebugMode), logEntryAppLevelConstantInfo.AppWasInDebugMode.ToString());
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerName)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerName), logEntryAppLevelConstantInfo.AppServerName);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerOSVersion)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerOSVersion), logEntryAppLevelConstantInfo.AppServerOSVersion);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerAppDomainName)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerAppDomainName), logEntryAppLevelConstantInfo.AppServerAppDomainName);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerProcessId)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerProcessId), logEntryAppLevelConstantInfo.AppServerProcessId.ToString());
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerUserAccountName)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerUserAccountName), logEntryAppLevelConstantInfo.AppServerUserAccountName);
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppServerWas64Bit)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppServerWas64Bit), logEntryAppLevelConstantInfo.AppServerWas64Bit.ToString(CultureInfo.InvariantCulture));
            }
            if (!telemetry.Context.GlobalProperties.ContainsKey(nameof(LogEntry.AppWas64Bit)))
            {
                telemetry.Context.GlobalProperties.Add(nameof(LogEntry.AppWas64Bit), logEntryAppLevelConstantInfo.AppWas64Bit.ToString(CultureInfo.InvariantCulture));
            }

            if (telemetry is RequestTelemetry requestTelemetry && HttpContextAccessor.HttpContext != null)
            {
                List <AppInsightsLogKeyVal> logKeyValues;

                if (HttpContextAccessor.HttpContext.Items.TryGetValue("LogKeyValues", out object?logKeyValuesAsObj))
                {
                    logKeyValues = (List <AppInsightsLogKeyVal>)logKeyValuesAsObj;
                }
                else // in ok responses, we've no LogKeyValues because ApplicationInsightsLogStore won't gets called.
                {
                    using IDependencyResolver childResolver = DependencyManager.CreateChildDependencyResolver(); // HttpContextAccessor.HttpContext.RequestServices is null because scope is gets disposed at this time.

                    IRequestInformationProvider requestInformationProvider = childResolver.Resolve <IRequestInformationProvider>();
                    IUserInformationProvider    userInformationProvider    = childResolver.Resolve <IUserInformationProvider>();

                    logKeyValues = new List <AppInsightsLogKeyVal> {
                    };

                    if (userInformationProvider.IsAuthenticated())
                    {
                        logKeyValues.Add(new AppInsightsLogKeyVal {
                            Key = "UserId", Value = userInformationProvider.GetCurrentUserId()
                        });
                    }

                    logKeyValues.Add(new AppInsightsLogKeyVal {
                        Key = nameof(IRequestInformationProvider.UserAgent), Value = requestInformationProvider.UserAgent
                    });

                    logKeyValues.Add(new AppInsightsLogKeyVal {
                        Key = "X-Correlation-ID", Value = requestInformationProvider.XCorrelationId
                    });
                }

                AppInsightsLogKeyVal userAgent = logKeyValues.FirstOrDefault(ld => ld.Key == nameof(IRequestInformationProvider.UserAgent));

                if (userAgent != null)
                {
                    requestTelemetry.Context.User.UserAgent = userAgent.Value;
                }

                AppInsightsLogKeyVal userId = logKeyValues.FirstOrDefault(ld => ld.Key == "UserId");

                if (userId != null)
                {
                    requestTelemetry.Context.User.AccountId = requestTelemetry.Context.User.Id = requestTelemetry.Context.User.AuthenticatedUserId = requestTelemetry.Context.User.AuthenticatedUserId = userId.Value;
                }

                foreach (AppInsightsLogKeyVal keyVal in logKeyValues.OrderBy(kv => kv.Key))
                {
                    if (keyVal.Key == nameof(IRequestInformationProvider.UserAgent) || keyVal.Key == "UserId")
                    {
                        continue;
                    }
                    if (!requestTelemetry.Properties.ContainsKey(keyVal.Key))
                    {
                        requestTelemetry.Properties.Add(keyVal.Key, keyVal.Value);
                    }
                }

                AppInsightsLogKeyVal xCorrelationId = logKeyValues.FirstOrDefault(ld => ld.Key == "X-Correlation-ID");

                if (xCorrelationId != null)
                {
                    requestTelemetry.Id = xCorrelationId.Value;
                }
            }
        }