Ejemplo n.º 1
0
        /// <summary>
        /// Get the file details for the specified resource
        /// </summary>
        /// <param name="resource">A resource to load</param>
        /// <returns>File datails</returns>
        private IResourceDetails GetFileDetails(IResource resource)
        {
            RetryPolicy  retryPolicy  = RetryPolicy ?? RetryPolicy.None;
            RetryCounter retryCounter = new RetryCounter(retryPolicy);
            int          iteration    = 0;
            Tuple <ResourceReadStatus, IResourceDetails> finalStatus = retryCounter.Run(
                () =>
            {
                iteration++;
                ULSLogging.LogTraceTag(0x238208cd /* tag_9669n */, Categories.ConfigurationDataSet, Levels.Verbose,
                                       "Attempting data set load for resource '{0}' in iteration '{1}' of '{2}'.",
                                       resource.Name, iteration, retryPolicy.RetryLimit);

                Tuple <ResourceReadStatus, IResourceDetails> status = resource.Read();
                return(Tuple.Create(status.Item1 == ResourceReadStatus.Success, status));
            });

            if (finalStatus.Item1 != ResourceReadStatus.Success)
            {
                ULSLogging.LogTraceTag(0x238208ce /* tag_9669o */, Categories.ConfigurationDataSet, Levels.Warning,
                                       "Failed to read resource '{0}' as the file read status is '{1}'.",
                                       resource.Name, finalStatus);
                return(null);
            }

            return(finalStatus.Item2);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Retrieves the XML reader settings.
        /// </summary>
        /// <param name="type">The object type to read.</param>
        /// <param name="schema">The schema to use.</param>
        /// <param name="schemaUri">The schema URI to use.</param>
        /// <returns>The relevant XML reader settings.</returns>
        public static XmlReaderSettings GetXmlReaderSettings(this Type type, string schema, string schemaUri)
        {
            if (type == null)
            {
                ULSLogging.LogTraceTag(0x23820889 /* tag_9668j */, Categories.Common, Levels.Error,
                                       "Null type value passed to GetXmlReaderSettings.");
                return(null);
            }

            if (string.IsNullOrEmpty(schema))
            {
                ULSLogging.LogTraceTag(0x2382088a /* tag_9668k */, Categories.Common, Levels.Error,
                                       "Null or empty schema value passed to GetXmlReaderSettings.");
                return(null);
            }

            XmlSchemaSet schemas = new XmlSchemaSet();

            using (XmlReader reader = XmlReader.Create(type.Assembly.GetManifestResourceStream(schema)))
            {
                schemas.Add(schemaUri, reader);
            }

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.ValidationType = ValidationType.Schema;
            settings.Schemas        = schemas;
            return(settings);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="file">File adaptor</param>
        /// <param name="folder">Folder</param>
        /// <param name="name">File Name including extension</param>
        public FileResource(IFile file, string folder, string name)
        {
            File   = Code.ExpectsArgument(file, nameof(file), TaggingUtilities.ReserveTag(0x238208d2 /* tag_9669s */));
            Folder = Code.ExpectsNotNullOrWhiteSpaceArgument(folder, nameof(folder), TaggingUtilities.ReserveTag(0x238208d3 /* tag_9669t */));
            Name   = Code.ExpectsNotNullOrWhiteSpaceArgument(name, nameof(name), TaggingUtilities.ReserveTag(0x238208d4 /* tag_9669u */));

            bool locationSet = false;

            try
            {
                if (!HasInvalidPathChars(Folder) && !HasInvalidPathChars(Name))
                {
                    Location    = Path.Combine(Folder, Name);
                    locationSet = true;
                }
                else
                {
                    ULSLogging.LogTraceTag(0x238208d5 /* tag_9669v */, Categories.ConfigurationDataSet, Levels.Error,
                                           "Failed to combine FileResource.Location for folder: '{0}', name: '{1}'", Folder, Name);
                }
            }
            catch (ArgumentException exception)
            {
                ULSLogging.ReportExceptionTag(0x238208d6 /* tag_9669w */, Categories.ConfigurationDataSet, exception,
                                              "Exception constructing FileResource for folder: '{0}', name: '{1}'", Folder, Name);
            }

            if (!locationSet)
            {
                Location = Name;
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Is the gate applicable for the current context
        /// </summary>
        /// <param name="gate">gate to check</param>
        /// <returns>true if applicable, false otherwise</returns>
        private bool IsGateApplicableInternal(IGate gate)
        {
            bool grantAccess = gate.IsGateEnabled;

            // If the gate is disabled but has been asked to be enabled through settings.
            if (m_settings?.GatesToggleEnabled?.Contains(gate.Name) ?? false)
            {
                grantAccess = true;
                ULSLogging.LogTraceTag(0x2382104e /* tag_967bo */, Categories.GateSelection, Levels.Verbose, "Enabling gate '{0}' through BRS that was disabled using gate toggle setting",
                                       gate.Name);
            }

            grantAccess = grantAccess && DoesHostEnvironmentHaveAccess(gate);
            grantAccess = grantAccess && DoesServiceHaveAccess(gate);
            grantAccess = grantAccess && DoesIPAddressHaveAccess(gate);
            grantAccess = grantAccess && DoesMarketHaveAccess(gate);
            grantAccess = grantAccess && DoesEnvironmentHaveAccess(gate);
            grantAccess = grantAccess && DoesBrowserHaveAccess(gate);
            grantAccess = grantAccess && DoesClientHaveAccess(gate);
            grantAccess = grantAccess && DoesUserHaveAccess(gate);
            grantAccess = grantAccess && IsCurrentDateEnabled(gate);
            grantAccess = grantAccess && DoQueryParametersHaveAccess(gate);
            grantAccess = grantAccess && DoesCloudContextHaveAccess(gate);

            if (gate.ExperimentInfo != null)
            {
                grantAccess = grantAccess && ExperimentContext.IsExperimentalGateApplicable(gate);
            }

            return(grantAccess);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Attempts to load a new dataset and replaces the old one if load was successful
        /// </summary>
        /// <param name="arguments">The arguments for the update event.</param>
        protected virtual void UpdateLoadedDataSet(ResourceUpdatedEventArgs arguments)
        {
            RunExclusiveAction action = AllowMultipleThreadsLoadingDataSet ? m_action : s_action;

            action.Do(() =>
            {
                if (arguments.IsInitialLoad)
                {
                    ULSLogging.LogTraceTag(0x23821004 /* tag_967ae */, Categories.ConfigurationDataSet, Levels.Verbose,
                                           "Adding data set type '{0}' to cache.", typeof(T).Name);

                    if (Cache.GetOrAdd(typeof(IConfigurationDataSetLoader <T>),
                                       () => CreateCachedConfigurationDataSet(new CachedConfigurationDataSet <T>(DataSetOverride), arguments),
                                       out bool wasAdded) is CachedConfigurationDataSet <T> result && wasAdded)
                    {
                        OnLoad(result.LoadDetails);
                    }
                }
                else
                {
                    ULSLogging.LogTraceTag(0x23850399 /* tag_97qoz */, Categories.ConfigurationDataSet, Levels.Verbose,
                                           "Updating data set type '{0}' in cache.", typeof(T).Name);
                    CachedConfigurationDataSet <T> dataSets             = DataSets;
                    IList <ConfigurationDataSetLoadDetails> loadDetails = dataSets.LoadDetails;

                    if (Cache.AddOrUpdate(typeof(IConfigurationDataSetLoader <T>),
                                          () => CreateCachedConfigurationDataSet(dataSets, arguments),
                                          out bool wasUpdated) is CachedConfigurationDataSet <T> result && wasUpdated)
                    {
                        OnReload(loadDetails, result.LoadDetails);
                    }
                }
            });
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets the experiment corresponding to the experimentName
        /// </summary>
        /// <param name="experimentName">The experiment name</param>
        /// <returns>the experiment</returns>
        public IExperiment GetExperiment(string experimentName)
        {
            if (!Code.ValidateNotNullOrWhiteSpaceArgument(experimentName, nameof(experimentName), TaggingUtilities.ReserveTag(0x23821085 /* tag_967cf */)))
            {
                return(null);
            }

            //This is to ensure threading
            IDictionary <string, IExperiment> temporaryReadDictionary = ExperimentsDictionary;

            if (temporaryReadDictionary == null)
            {
                ULSLogging.LogTraceTag(0x23821086 /* tag_967cg */, Categories.Experimentation, Levels.Error,
                                       "Experiment dictionary is being returned null");
                return(null);
            }

            if (!temporaryReadDictionary.ContainsKey(experimentName))
            {
                ULSLogging.LogTraceTag(0x23821087 /* tag_967ch */, Categories.Experimentation, Levels.Error,
                                       "Trying to get gates for an unknown experiment '{0}'", experimentName);
                return(null);
            }

            return(temporaryReadDictionary[experimentName]);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Configure event replaying when a timed scope ends
        /// </summary>
        /// <param name="scope"></param>
        public void ConfigureReplayEventsOnScopeEnd(TimedScope scope)
        {
            CorrelationData currentCorrelation = Correlation.CurrentCorrelation;

            if (scope.IsSuccessful ?? false)
            {
                // assumption is that if any lower level scopes fail that should bubble up to the parent scope; if replay is enabled a previous scope has failed so
                // log some telemetry to help us understand these mixed scenarios better / identify error handling bugs
                if (currentCorrelation != null && currentCorrelation.ShouldReplayUls)
                {
                    // ASSERTTAG_IGNORE_START
                    ULSLogging.LogTraceTag(0, Categories.TimingGeneral, Levels.Warning,
                                           "Scope '{0}' succeeded even though a previous scope on this correlation failed.", scope.Name);
                    // ASSERTTAG_IGNORE_FINISH
                }
            }
            else
            {
                // flip the replay switch on Scope failure for scenarios where its useful to get a verbose ULS trace in production
                if (currentCorrelation != null &&
                    scope.Result.ShouldReplayEvents() &&
                    !scope.IsTransaction &&
                    !scope.ScopeDefinition.OnDemand &&
                    !scope.DisableVerboseUlsCapture &&
                    !DisabledTimedScopes.IsDisabled(scope.ScopeDefinition))
                {
                    currentCorrelation.ShouldReplayUls = true;
                    currentCorrelation.ReplayPreviouslyCachedUlsEvents();
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Is the ip address of the request part of the gate criteria
        /// </summary>
        /// <param name="gate">gate</param>
        /// <returns>true if the ip address of the request matches the gate criteria, false otherwise</returns>
        private bool DoesIPAddressHaveAccess(IGate gate)
        {
            bool             grantAccess = true;
            HashSet <string> ipRanges    = gate.KnownIPRanges;

            if (ipRanges != null)
            {
                grantAccess = false;

                foreach (string ipRange in ipRanges)
                {
                    if (Request != null && Request.IsPartOfKnownIPRange(KnownIpAddresses, ipRange))
                    {
                        grantAccess = true;
                        break;
                    }
                }

                if (!grantAccess)
                {
                    ULSLogging.LogTraceTag(0x23821058 /* tag_967by */, Categories.GateSelection, Levels.Verbose,
                                           "Not allowing access to gate '{0}' as the ip address of the request is not in the set of allowed known ip ranges '{1}'.",
                                           gate.Name ?? "<NULL>", string.Join(", ", ipRanges));
                }
            }

            return(grantAccess);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Are any of the current query parameters blocked by the gate critera?
        /// </summary>
        /// <param name="gate">gate</param>
        /// <returns>true if no blocked query parameters match the requests query parmeters</returns>
        private bool DoQueryParametersHaveAccess(IGate gate)
        {
            bool grantAccess = true;
            IDictionary <string, HashSet <string> > blockedQueryParameters = gate.BlockedQueryParameters;

            if (blockedQueryParameters != null && blockedQueryParameters.Count > 0)
            {
                IDictionary <string, HashSet <string> > requestsQueryParameters = Request?.QueryParameters;
                //if no params exist on the request, then we grant access by default.
                if (requestsQueryParameters == null || requestsQueryParameters.Count == 0)
                {
                    ULSLogging.LogTraceTag(0x23821053 /* tag_967bt */, Categories.GateSelection, Levels.Verbose,
                                           "Allowing access to gate '{0}' as the GatedRequest has no query parameters.",
                                           gate.Name ?? "<NULL>");
                    return(grantAccess);
                }

                //if any request query param matches a blocked query param, we should not grant access.
                foreach (string requestParameterName in requestsQueryParameters.Keys)
                {
                    if (blockedQueryParameters.ContainsKey(requestParameterName))
                    {
                        //if the wild card '*' is specified as a value for a blocked param, then we restrict access
                        if (blockedQueryParameters[requestParameterName].Contains(Gate.BlockedQueryParameterValueWildCard))
                        {
                            grantAccess = false;

                            ULSLogging.LogTraceTag(0x23821054 /* tag_967bu */, Categories.GateSelection, Levels.Verbose,
                                                   "Not allowing access to gate '{0}' with the query parameter(s) '{1}'='{2}' as all parameters with name '{3}' are blocked by the wildcard '*'.",
                                                   gate.Name ?? "<NULL>",
                                                   requestParameterName,
                                                   requestsQueryParameters[requestParameterName],
                                                   requestParameterName);

                            break;
                        }

                        //if there's corresponding parameters in the request and the list of blocked, we do not grant access
                        IEnumerable <string> intersection = blockedQueryParameters[requestParameterName]
                                                            .Intersect(requestsQueryParameters[requestParameterName], StringComparer.OrdinalIgnoreCase);

                        if (intersection.Count() > 0)
                        {
                            grantAccess = false;

                            ULSLogging.LogTraceTag(0x23821055 /* tag_967bv */, Categories.GateSelection, Levels.Verbose,
                                                   "Not allowing access to gate '{0}' as the query parameter(s) '{1}'='{2}' is in the set of blocked query parameters '{3}'.",
                                                   gate.Name ?? "<NULL>",
                                                   requestParameterName,
                                                   string.Join(",", intersection),
                                                   string.Join(", ", blockedQueryParameters.Select(parameter => string.Format("'{0}={1}'", parameter.Key, parameter.Value))));

                            break;
                        }
                    }
                }
            }

            return(grantAccess);
        }
        public void AddUlsLoggerAddapter_SubscribesToEvents()
        {
            Mock <ILogger>        mockLogger  = new Mock <ILogger>();
            Mock <ILoggerFactory> mockFactory = new Mock <ILoggerFactory>();

            mockFactory.Setup(f => f.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);

            new HostBuilder()
            .ConfigureServices(collection =>
            {
                collection
                .AddSingleton(mockFactory.Object)
                .AddUlsLoggerAddapter();
            })
            .Build()
            .Start();

            uint      eventId    = 1;
            Category  category   = new Category("Test");
            Level     logLevel   = Levels.Error;
            string    logMessage = "TestLogMessage";
            Exception exception  = new Exception();

            mockLogger.Invocations.Clear();
            ULSLogging.LogTraceTag(eventId, category, logLevel, logMessage);
            Assert.AreEqual(1, mockLogger.Invocations.Count, "ULSLogging.LogTraceTag not calling ILogger");

            mockLogger.Invocations.Clear();
            ULSLogging.ReportExceptionTag(eventId, category, exception, logMessage);
            Assert.AreEqual(1, mockLogger.Invocations.Count, "ULSLogging.ReportExceptionTag not calling ILogger");
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Stop monitoring the resources.
 /// </summary>
 public void StopMonitoring(ResourceUpdatedHandler callback)
 {
     if (!m_resourceMonitoringData.TryRemove(callback, out ResourceMonitoringData monitoringInstance))
     {
         ULSLogging.LogTraceTag(0x238208cb /* tag_9669l */, Categories.ConfigurationDataSet, Levels.Verbose,
                                "An attempt to remove a non-existing handler");
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Log a code error. This raises a ShipAssert event
        /// </summary>
        /// <param name="tag">tag</param>
        /// <param name="category">category</param>
        /// <param name="skipLog">should the logging be skipped</param>
        /// <param name="addToLoadingErrors">add to dataset loading errors</param>
        /// <param name="message">message</param>
        /// <param name="parameters">message format parameters</param>
        public void LogCodeErrorTag(uint tag, Category category, bool skipLog, bool addToLoadingErrors, string message, params object[] parameters)
        {
            ULSLogging.LogTraceTag(tag, category, Levels.Error, message, parameters);

            if (addToLoadingErrors)
            {
                LogError(message, parameters);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Updates DataSet on resources change event
        /// </summary>
        /// <param name="arguments">event arguments</param>
        /// <remarks>Since this may be called on a background thread without a current correlation,
        /// start a new correlation if one does not already exist</remarks>
        protected virtual void OnResourceUpdated(ResourceUpdatedEventArgs arguments)
        {
            ULSLogging.LogTraceTag(0x23821005 /* tag_967af */, Categories.ConfigurationDataSet, Levels.Verbose,
                                   "'{0}' loader encountered an event for resources '{1}'.",
                                   typeof(T).Name, string.Join(";", arguments.Details.Select(d => d.Key)));

            UpdateLoadedDataSet(arguments);
            DataSetLoaded?.Invoke(this, EventArgs.Empty);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Merge two gated clients
        /// </summary>
        /// <param name="client1">first client</param>
        /// <param name="client2">second client</param>
        /// <returns>merged gated client</returns>
        /// <remarks>The name must be the same on both clients. The Version returned is the
        /// greatest version of the two clients. If one or no client has a product code, that
        /// code is used, if both have a product code, the code from the client with the greatest
        /// version is used.</remarks>
        public static GatedClient MergeClient(GatedClient client1, GatedClient client2)
        {
            if (client1 == null)
            {
                return(client2);
            }

            if (client2 == null)
            {
                return(client1);
            }

            if (!string.Equals(client1.Name, client2.Name, StringComparison.OrdinalIgnoreCase))
            {
                ULSLogging.LogTraceTag(0x23821047 /* tag_967bh */, Categories.GateSelection, Levels.Error,
                                       "The name of the clients must be the same. Client1 '{0}', Client2 '{1}'.",
                                       client1.Name, client2.Name);
                return(null);
            }

            GatedClient mergedClient = new GatedClient
            {
                Name = client1.Name
            };

            if (client1.Version == null)
            {
                mergedClient.Version        = client2.Version;
                mergedClient.ProductCode    = client2.ProductCode ?? client1.ProductCode;
                mergedClient.AppCode        = client2.AppCode;
                mergedClient.AudienceGroups = client2.AudienceGroups;
            }
            else if (client2.Version == null)
            {
                mergedClient.Version        = client1.Version;
                mergedClient.ProductCode    = client1.ProductCode ?? client2.ProductCode;
                mergedClient.AppCode        = client1.AppCode;
                mergedClient.AudienceGroups = client1.AudienceGroups;
            }
            else if (client1.Version > client2.Version)
            {
                mergedClient.Version        = client1.Version;
                mergedClient.ProductCode    = client1.ProductCode ?? client2.ProductCode;
                mergedClient.AppCode        = client1.AppCode;
                mergedClient.AudienceGroups = client1.AudienceGroups;
            }
            else
            {
                mergedClient.Version        = client2.Version;
                mergedClient.ProductCode    = client2.ProductCode ?? client1.ProductCode;
                mergedClient.AppCode        = client2.AppCode;
                mergedClient.AudienceGroups = client2.AudienceGroups;
            }

            return(mergedClient);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Log trace tag. This raises a LogEvent of a specified level.
        /// </summary>
        /// <param name="tagid">tag</param>
        /// <param name="category">category</param>
        /// <param name="level">level to log at</param>
        /// <param name="addToLoadingErrors">add to dataset loading errors</param>
        /// <param name="message">message</param>
        /// <param name="parameters">message format parameters</param>
        public void LogTraceTag(uint tagid, Category category, Level level, bool addToLoadingErrors, string message,
                                params object[] parameters)
        {
            ULSLogging.LogTraceTag(tagid, category, level, message, parameters);

            if (addToLoadingErrors)
            {
                LogError(message, parameters);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// End the timed scope
        /// </summary>
        public void End()
        {
            if (IsDisposed)
            {
                ULSLogging.LogTraceTag(0x238174df /* tag_96xt5 */, Categories.TimingGeneral, Levels.Error,
                                       "Attempting to end scope '{0}' that has already been disposed.", Name);
                return;
            }

            EndScope(MachineInformation);
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Logs document db response info to ULS.
 /// </summary>
 /// <param name="caller">Caller function name. No need to specify explicitly, will be set automatically on run time.</param>
 /// <param name="activityId">Document db activity id.</param>
 /// <param name="charge">Charge in RU s.</param>
 /// <param name="statusCode">Status code or the response.</param>
 /// <param name="contentLocation">Location of the documentdb resource.</param>
 /// <param name="tagId">ULS tag.</param>
 private static void LogInfo(
     string caller, string activityId, double charge, int statusCode, string contentLocation, uint tagId)
 {
     ULSLogging.LogTraceTag(tagId, Categories.DocumentDb, Levels.Info,
                            "Operation: {0} Cost: {1} ContentLocation: {2} StatusCode: {3} ActivityId: {4}",
                            caller,
                            charge,
                            contentLocation,
                            statusCode,
                            activityId);
 }
Ejemplo n.º 18
0
        private static string SanitizeString(string mdmString, string name, string activityName, Category logCategory)
        {
            string validatedString = Convert.ToString(mdmString, CultureInfo.InvariantCulture) ?? string.Empty;

            if (validatedString.Length > 1024)
            {
                ULSLogging.LogTraceTag(0x23857681 /* tag_97x0b */, logCategory, Levels.Warning, StringLimitMessage, 1024, name, activityName, validatedString.Length);
                validatedString = validatedString.Substring(0, 1024);
            }

            return(validatedString);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Does the service have access.
        /// </summary>
        /// <param name="gate">The gate.</param>
        /// <returns>true if service has access, false otherwise.</returns>
        private bool DoesServiceHaveAccess(IGate gate)
        {
            bool grantAccess = true;
            IDictionary <string, GatedServiceTypes> services = gate.Services;

            // If gate doesn't expect service based gating, grant access.
            if (services != null)
            {
                GatedServiceTypes serviceFlag;
                string            serviceName = MachineInformation.ServiceName;
                if (services.TryGetValue(serviceName, out serviceFlag))
                {
                    switch (serviceFlag)
                    {
                    // GrantAccess if gate will be applicable for both Full & Canary Services.
                    case GatedServiceTypes.All:
                        break;

                    // GrantAccess only when its a full(non-canary service).
                    case GatedServiceTypes.FullService:
                        grantAccess = !MachineInformation.IsCanary;
                        break;

                    // GrantAccess only when its a canary service.
                    case GatedServiceTypes.CanaryService:
                        grantAccess = MachineInformation.IsCanary;
                        break;

                    // Deny Access if service flag is none.
                    case GatedServiceTypes.None:
                        grantAccess = false;
                        break;
                    }
                }
                else
                {
                    // If gate expects a service but current machine is not running that service or there's no service
                    // either because no service was mentioned within service tag in gate or consolidation yielded zero service,
                    // deny access in all cases.
                    grantAccess = false;
                }

                if (!grantAccess)
                {
                    ULSLogging.LogTraceTag(0x23821057 /* tag_967bx */, Categories.GateSelection, Levels.Verbose,
                                           "Not allowing access to gate '{0}' as '{1}' did not match the required criteria.",
                                           gate.Name ?? "<NULL>", serviceName ?? "<NULL>");
                }
            }

            return(grantAccess);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Checks the gate's applicability based on the user agent browser. This is a common method which checks gate's applicability for
        /// both allowed browsers and blocked browsers.
        /// </summary>
        /// <param name="browsers">The browsers.</param>
        /// <returns>true if gate's applicability based on constraints is confirmed, false otherwise.</returns>
        private bool CheckGateApplicabilityForBrowser(IDictionary <string, HashSet <int> > browsers)
        {
            Tuple <string, int> browser = Request?.GetUserAgentBrowser();

            if (browser == null)
            {
                ULSLogging.LogTraceTag(0x2382105c /* tag_967b2 */, Categories.GateSelection, Levels.Verbose,
                                       "HttpRequest object doesn't have any browser, which means request not made from a browser.");

                // Request not made from a browser.
                return(false);
            }

            if (!browsers.TryGetValue(browser.Item1, out HashSet <int> browserVersion))
            {
                ULSLogging.LogTraceTag(0x2382105d /* tag_967b3 */, Categories.GateSelection, Levels.Verbose,
                                       "Gate expects a different browser than the one from which the request was made.");

                // Gate expects different browser, hence return false.
                return(false);
            }

            if (browserVersion == null)
            {
                ULSLogging.LogTraceTag(0x2382105e /* tag_967b4 */, Categories.GateSelection, Levels.Verbose,
                                       "Gate doesn't contain any browser version, which means all the versions apply.");

                // No constraint set on the browser's version, hence return true.
                return(true);
            }

            if (browserVersion.Count == 0)
            {
                ULSLogging.LogTraceTag(0x2382105f /* tag_967b5 */, Categories.GateSelection, Levels.Verbose,
                                       "Gate doesn't contain any browser version, which means all the versions apply.");

                // No constraint set on the browser's version, hence return true.
                return(true);
            }

            if (!browserVersion.Contains(browser.Item2))
            {
                ULSLogging.LogTraceTag(0x23821060 /* tag_967b6 */, Categories.GateSelection, Levels.Verbose,
                                       "Gate expects a different browser version than the one from which the request was made.");

                // Browser versions not compatible, return false.
                return(false);
            }

            return(true);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Loads DataSet and starts resources monitoring
        /// </summary>
        /// <param name="resources">resources</param>
        protected virtual void Initialize(IEnumerable <IResource> resources)
        {
            Resources = Code.ExpectsArgument(resources, nameof(resources), TaggingUtilities.ReserveTag(0x23821001 /* tag_967ab */));

            if (!m_resourceMonitor.TryStartMonitoring(Resources, OnResourceUpdated))
            {
                ULSLogging.LogTraceTag(0x23821002 /* tag_967ac */, Categories.ConfigurationDataSet, Levels.Error,
                                       "Failed to start resources monitoring for {0}", typeof(T).Name);
            }
            else
            {
                ULSLogging.LogTraceTag(0x23821003 /* tag_967ad */, Categories.ConfigurationDataSet, Levels.Verbose,
                                       "Successfully started resource monitoring for {0}", typeof(T).Name);
            }
        }
Ejemplo n.º 22
0
        public void AddOmexCompatibilityServices_RegisterTypes()
        {
            Mock <ILogger>        mockLogger  = new Mock <ILogger>();
            Mock <ILoggerFactory> mockFactory = new Mock <ILoggerFactory>();

            mockFactory.Setup(f => f.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);

            new HostBuilder()
            .ConfigureServices(collection =>
            {
                collection
                .AddTimedScopes()
                .AddSingleton(mockFactory.Object)
                .AddOmexCompatibilityServices();
            })
            .Build()
            .Start();

            EventId   eventId    = new EventId(1);
            Category  category   = new Category("Test");
            LogLevel  logLevel   = LogLevel.Error;
            string    logMessage = "TestLogMessage";
            Exception exception  = new Exception();

            mockLogger.Invocations.Clear();
            ULSLogging.LogTraceTag(eventId, category, logLevel, logMessage);
            Assert.AreEqual(1, mockLogger.Invocations.Count, "ULSLogging.LogTraceTag not calling ILogger");

            mockLogger.Invocations.Clear();
            ULSLogging.ReportExceptionTag(eventId, category, exception, logMessage);
            Assert.AreEqual(1, mockLogger.Invocations.Count, "ULSLogging.ReportExceptionTag not calling ILogger");

            mockLogger.Invocations.Clear();
            Code.Validate(false, logMessage, eventId);
            Assert.AreEqual(1, mockLogger.Invocations.Count, "Code.Validate not calling ILogger");

            using (TimedScope startedTimedScope = new TimedScopeDefinition("TestStartedTimedScope").Create(TimedScopeResult.SystemError))
            {
                AssertResult(ActivityResultStrings.SystemError);
            }

            using (TimedScope notStartedTimedScope = new TimedScopeDefinition("TestNotStartedTimedScope").Create(TimedScopeResult.ExpectedError, false))
            {
                notStartedTimedScope.Start();
                AssertResult(ActivityResultStrings.ExpectedError);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Retrieves currently loaded TestGroups DataSet
        /// </summary>
        /// <returns>Currently loaded TestGroups DataSet</returns>
        private ITestGroupsDataSet GetTestGroupsDataSet()
        {
            ITestGroupsDataSet dataSet = m_testGroupsDataSetLoader.LoadedDataSet;

            if (dataSet == null)
            {
                ULSLogging.LogTraceTag(0x238210c0 /* tag_967da */, Categories.TestGroupsDataSet, Levels.Error,
                                       "TestGroupsDataSet is null, TestGroups authentication will fail.");
            }
            else if (!dataSet.IsHealthy)
            {
                ULSLogging.LogTraceTag(0x238210c1 /* tag_967db */, Categories.TestGroupsDataSet, Levels.Error,
                                       "TestGroupsDataSet is not healthy.");
            }

            return(dataSet);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Logs the scope end to ULS
        /// </summary>
        private void LogEnd(IMachineInformation machineInformation)
        {
            if (!IsSuccessful.HasValue)
            {
                ULSLogging.LogTraceTag(0x238174e3 /* tag_96xt9 */, Categories.TimingGeneral, Levels.Warning,
                                       "Result not set for scope {0}. Considered as SystemError", Name);

                Result             = TimedScopeResult.SystemError;
                FailureDescription = InternalFailureDescription.UnknownResultAsSystemError;
            }

            CorrelationData scopeData = ConstructCorrelationDataEntries(machineInformation);

            ScopeLogger.LogScopeEnd(this, scopeData);

            ReplayEventConfigurator.ConfigureReplayEventsOnScopeEnd(this);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Is experiment valid
        /// </summary>
        /// <param name="experimentName">experiment name</param>
        /// <returns>true if the list of experiment contains the experiment</returns>
        public bool IsValidExperiment(string experimentName)
        {
            if (!Code.ValidateNotNullOrWhiteSpaceArgument(experimentName, nameof(experimentName), TaggingUtilities.ReserveTag(0x23821083 /* tag_967cd */)))
            {
                return(false);
            }

            IDictionary <string, IExperiment> temporaryReadDictionary = ExperimentsDictionary;

            if (temporaryReadDictionary == null)
            {
                ULSLogging.LogTraceTag(0x23821084 /* tag_967ce */, Categories.Experimentation, Levels.Error,
                                       "Experiment dictionary is being returned null");
                return(false);
            }

            return(temporaryReadDictionary.ContainsKey(experimentName));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Create a dictionary of resources details in the format in which handlers expect it
        /// </summary>
        /// <param name="allKnownDetails">Resource details</param>
        /// <returns>Mapping of resource names to details</returns>
        private IDictionary <string, IResourceDetails> CreateResourceSetDetails(IDictionary <IResource, IResourceDetails> allKnownDetails)
        {
            IDictionary <string, IResourceDetails> result = new Dictionary <string, IResourceDetails>();

            foreach (IResource resource in m_trackedResources)
            {
                if (!allKnownDetails.ContainsKey(resource))
                {
                    ULSLogging.LogTraceTag(0x238208c8 /* tag_9669i */, Categories.ConfigurationDataSet, Levels.Error,
                                           "Resource details for '{0}' are not present although it should've been loaded at this stage", resource.Name);
                    continue;
                }

                result[resource.Name] = allKnownDetails[resource];
            }

            return(result);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Loads embedded resource
        /// </summary>
        /// <param name="resourceName">Resource name</param>
        /// <param name="type">Type to determine assembly</param>
        /// <returns>Resource contents as string</returns>
        public static string GetEmbeddedResourceAsString(string resourceName, Type type)
        {
            using (Stream stream = type.Assembly.GetManifestResourceStream(resourceName))
            {
                if (stream == null)
                {
                    ULSLogging.LogTraceTag(0x23821040 /* tag_967ba */, Categories.Infrastructure,
                                           Levels.Error, "Cannot find embedded resource '{0}' in assembly '{1}'.",
                                           resourceName, type.Assembly);
                    return(null);
                }

                using (StreamReader reader = new StreamReader(stream))
                {
                    return(reader.ReadToEnd());
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Loads an embedded resource and returns as a string
        /// </summary>
        /// <param name="assembly">The assembly to load from</param>
        /// <param name="resourceName">Name of the embedded resource</param>
        /// <returns>Resource as string, or null if not found</returns>
        public static string LoadEmbeddedResourceAsString(this Assembly assembly, string resourceName)
        {
            if (!Code.ValidateArgument(assembly, nameof(assembly), TaggingUtilities.ReserveTag(0x23820895 /* tag_9668v */)) ||
                !Code.ValidateNotNullOrWhiteSpaceArgument(resourceName, nameof(resourceName), TaggingUtilities.ReserveTag(0x23820896 /* tag_9668w */)))
            {
                return(null);
            }

            string[] resources = assembly.GetManifestResourceNames();
            if (!Array.Exists(resources, name => string.Equals(name, resourceName, StringComparison.Ordinal)))
            {
                // try resolving partial name

                string[] matches = Array.FindAll(resources, name => name.StartsWith(resourceName, StringComparison.Ordinal));

                if (matches.Length == 1)
                {
                    resourceName = matches[0];
                }
                else
                {
                    ULSLogging.LogTraceTag(0x23820897 /* tag_9668x */, Categories.Infrastructure, Levels.Error,
                                           "Embedded resource '{0}' was not found in '{1}'.", resourceName, assembly.FullName);

                    return(null);
                }
            }

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                if (stream == null)
                {
                    ULSLogging.LogTraceTag(0x23820898 /* tag_9668y */, Categories.Infrastructure, Levels.Error,
                                           "Embedded resource '{0}' could not be loaded from '{1}'.", resourceName, assembly.FullName);

                    return(null);
                }

                using (StreamReader reader = new StreamReader(stream))
                {
                    return(reader.ReadToEnd());
                }
            }
        }
Ejemplo n.º 29
0
            /// <summary>
            /// Loads DataSet
            /// </summary>
            /// <param name="arguments">The arguments for the update event.</param>
            /// <returns>Loaded DataSet</returns>
            private TDataSet LoadDataSet(ResourceUpdatedEventArgs arguments)
            {
                ULSLogging.LogTraceTag(0x2382100c /* tag_967am */, Categories.ConfigurationDataSet, Levels.Verbose,
                                       "Loading data set for '{0}'.", typeof(TDataSet).Name);

                TDataSet dataSet = m_dataSetDefault ?? new TDataSet();

                try
                {
                    dataSet.Load(arguments.Details);
                }
                catch (Exception exception)
                {
                    ULSLogging.ReportExceptionTag(0x2382100d /* tag_967an */, Categories.ConfigurationDataSet, exception,
                                                  "Exception encountered while loading '{0}'", typeof(TDataSet).Name);
                }

                return(dataSet);
            }
Ejemplo n.º 30
0
        /// <summary>
        /// Decides whether the result is success
        /// </summary>
        /// <param name="result">The result</param>
        /// <returns>Success flag (null if we don't know)</returns>
        public static bool?IsSuccessful(this TimedScopeResult result)
        {
            switch (result)
            {
            case default(TimedScopeResult):
                return(null);

            case TimedScopeResult.Success:
                return(true);

            case TimedScopeResult.ExpectedError:
            case TimedScopeResult.SystemError:
                return(false);

            default:
                ULSLogging.LogTraceTag(0x23817701 /* tag_96x2b */, Categories.TimingGeneral, Levels.Error, "IsSuccessful status unknown for timed scope result {0}", result);
                return(false);
            }
        }