Exemplo n.º 1
0
 protected override TrackerCount NewValue(IFlowData data)
 {
     return(new TrackerCount()
     {
         Count = 1
     });
 }
        /// <summary>
        /// Called by the Process method on the
        /// <see cref="FlowElementBase{T, TMeta}"/> base class.
        /// Executes all child elements in parallel.
        /// </summary>
        /// <param name="data">
        /// The data to use when executing the flow elements.
        /// </param>
        protected override void ProcessInternal(IFlowData data)
        {
            List <Task> allTasks = new List <Task>();

            foreach (var element in _flowElements)
            {
                allTasks.Add(
                    // Run each element on a new thread.
                    Task.Run(() =>
                {
                    element.Process(data);
                }).ContinueWith(t =>
                {
                    // If any exceptions occurred then add them to the
                    // flow data.
                    if (t.Exception != null)
                    {
                        foreach (var innerException in t.Exception.InnerExceptions)
                        {
                            data.AddError(innerException, element);
                        }
                    }
                }, TaskScheduler.Default));
            }

            // Wait until all tasks have completed.
            Task.WhenAll(allTasks).Wait();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Retrieve the raw JSON response from the
        /// <see cref="CloudRequestEngine"/> in this pipeline, extract
        /// the data for this specific engine and populate the
        /// <code>TData</code> instance accordingly.
        /// </summary>
        /// <param name="data">
        /// The <see cref="IFlowData"/> to get the raw JSON data from.
        /// </param>
        /// <param name="aspectData">
        /// The <code>TData</code> instance to populate with values.
        /// </param>
        /// <param name="json">
        /// The JsonResponse populated by the CloudRequestEngine.
        /// </param>
        protected override void ProcessCloudEngine(IFlowData data, TData aspectData, string json)
        {
            // Extract data from json to the aspectData instance.
            var dictionary = JsonConvert.DeserializeObject <Dictionary <string, object> >(json);
            // Access the data relating to this engine.
            var propertyKeyed = dictionary[ElementDataKey] as JObject;

            // Access the 'Profiles' property
            foreach (var entry in propertyKeyed["profiles"])
            {
                // Iterate through the devices, parsing each one and
                // adding it to the result.
                var propertyValues = JsonConvert.DeserializeObject <Dictionary <string, object> >(entry.ToString(),
                                                                                                  new JsonSerializerSettings()
                {
                    Converters = JSON_CONVERTERS,
                });
                var device = CreateProfileData();
                // Get the meta-data for properties on device instances.
                var propertyMetaData = Properties
                                       .Single(p => p.Name == "Profiles").ItemProperties;

                var deviceData = CreateAPVDictionary(
                    propertyValues,
                    propertyMetaData);

                device.PopulateFromDictionary(deviceData);
                //device.SetNoValueReasons(nullReasons);
                aspectData.AddProfile(device);
            }
        }
Exemplo n.º 4
0
        protected override void ProcessInternal(IFlowData data)
        {
            // Create a new IStarSignData, and cast to StarSignData so the 'setter' is available.
            StarSignData starSignData = (StarSignData)data.GetOrAdd(ElementDataKey, CreateElementData);

            if (data.TryGetEvidence("date-of-birth", out DateTime dateOfBirth))
            {
                // "date-of-birth" is there, so set the star sign.
                var monthAndDay = new DateTime(1, dateOfBirth.Month, dateOfBirth.Day);
                foreach (var starSign in _starSigns)
                {
                    if (monthAndDay > starSign.Start &&
                        monthAndDay < starSign.End)
                    {
                        // The star sign has been found, so set it in the
                        // results.
                        starSignData.StarSign = starSign.Name;
                        break;
                    }
                }
            }
            else
            {
                // "date-of-birth" is not there, so set the star sign to unknown.
                starSignData.StarSign = "Unknown";
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Process the math operation by parsing the text and computing the
        /// result.
        /// </summary>
        /// <param name="data">FlowData to add the result to</param>
        protected override void ProcessInternal(IFlowData data)
        {
            MathData elementData = (MathData)data.GetOrAdd(
                ElementDataKeyTyped,
                (f) => base.CreateElementData(f));
            string operation = ((string)data.GetEvidence()[EvidenceKeys[0]]);

            if (operation != null)
            {
                // Parse the text representation of the mathematical operation.
                elementData.Operation = operation
                                        .Replace("plus", "+")
                                        .Replace("minus", "-")
                                        .Replace("divide", "/")
                                        .Replace("times", "*");
                // Compute the value of the operation.
                elementData.Result = Convert.ToDouble(
                    new DataTable().Compute(elementData.Operation, ""));
            }
            else
            {
                // Nothing provided, so just set zeros.
                elementData.Operation = "0";
                elementData.Result    = 0;
            }
        }
        /// <summary>
        /// Get all the properties.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="config">The configuration to use</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if the supplied flow data is null.
        /// </exception>
        protected virtual Dictionary <string, object> GetAllProperties(
            IFlowData data,
            PipelineConfig config)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            Dictionary <string, object> allProperties = new Dictionary <string, object>();

            foreach (var element in data.ElementDataAsDictionary().Where(elementData =>
                                                                         _elementExclusionList.Contains(elementData.Key) == false))
            {
                if (allProperties.ContainsKey(element.Key.ToLowerInvariant()) == false)
                {
                    var values = GetValues(data,
                                           element.Key.ToLowerInvariant(),
                                           (element.Value as IElementData).AsDictionary(),
                                           config);
                    allProperties.Add(element.Key.ToLowerInvariant(), values);
                }
            }

            return(allProperties);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Generate any required parameters for the JSON request.
        /// Any query parameters from this request that were ingested by
        /// the Pipeline are added to the request URL by the JavaScript.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected virtual Dictionary <string, string> GetParameters(IFlowData data)
        {
            if (data == null)
            {
                throw new ArgumentException(Messages.ExceptionFlowDataIsNull);
            }

            var parameters = data
                             .GetEvidence()
                             .AsDictionary()
                             .Where(e => e.Key.StartsWith(Core.Constants.EVIDENCE_QUERY_PREFIX,
                                                          StringComparison.OrdinalIgnoreCase))
                             .Where(e => ExcludedParameters.Contains(e.Key) == false)
                             .ToDictionary(k =>
            {
                var dotPos = k.Key.IndexOf(Core.Constants.EVIDENCE_SEPERATOR,
                                           StringComparison.OrdinalIgnoreCase);
                return(WebUtility.UrlEncode(k.Key.Remove(0, dotPos + 1)));
            }, v => WebUtility.UrlEncode(v.Value.ToString()));

            // Serialise the parameters
            var paramsObject =
                JsonConvert.SerializeObject(parameters, Formatting.Indented);

            return(parameters);
        }
        /// <summary>
        /// Generate the Content to send in the POST request. The evidence keys
        /// e.g. 'query.' and 'header.' have an order of precedence. These are
        /// added to the evidence in reverse order, if there is conflict then
        /// the queryData value is overwritten.
        ///
        /// 'query.' evidence should take precedence over all other evidence.
        /// If there are evidence keys other than 'query.' that conflict then
        /// this is unexpected so an error will be logged.
        /// </summary>
        /// <param name="data"></param>
        /// <returns>Evidence in a FormUrlEncodedContent object</returns>
        private FormUrlEncodedContent GetContent(IFlowData data)
        {
            var queryData = new Dictionary <string, string>();

            queryData.Add("resource", _resourceKey);

            if (string.IsNullOrWhiteSpace(_licenseKey) == false)
            {
                queryData.Add("license", _licenseKey);
            }

            var evidence = data.GetEvidence().AsDictionary();

            // Add evidence in reverse alphabetical order, excluding special keys.
            AddQueryData(queryData, evidence, evidence
                         .Where(e =>
                                KeyHasPrefix(e, Core.Constants.EVIDENCE_QUERY_PREFIX) == false &&
                                KeyHasPrefix(e, Core.Constants.EVIDENCE_HTTPHEADER_PREFIX) == false &&
                                KeyHasPrefix(e, Core.Constants.EVIDENCE_COOKIE_PREFIX) == false)
                         .OrderByDescending(e => e.Key));
            // Add cookie evidence.
            AddQueryData(queryData, evidence, evidence
                         .Where(e => KeyHasPrefix(e, Core.Constants.EVIDENCE_COOKIE_PREFIX)));
            // Add header evidence.
            AddQueryData(queryData, evidence, evidence
                         .Where(e => KeyHasPrefix(e, Core.Constants.EVIDENCE_HTTPHEADER_PREFIX)));
            // Add query evidence.
            AddQueryData(queryData, evidence, evidence
                         .Where(e => KeyHasPrefix(e, Core.Constants.EVIDENCE_QUERY_PREFIX)));

            var content = new FormUrlEncodedContent(queryData);

            return(content);
        }
        /// <summary>
        /// Send evidence to the cloud and get back a JSON result.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="aspectData"></param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if a required parameter is null.
        /// </exception>
        protected override void ProcessEngine(IFlowData data, CloudRequestData aspectData)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            if (aspectData == null)
            {
                throw new ArgumentNullException(nameof(aspectData));
            }

            aspectData.ProcessStarted = true;

            string jsonResult = string.Empty;

            using (var content = GetContent(data))
                using (var requestMessage =
                           new HttpRequestMessage(HttpMethod.Post, _dataEndpoint))
                {
                    if (Logger != null && Logger.IsEnabled(LogLevel.Debug))
                    {
                        Logger.LogDebug($"Sending request to cloud service at " +
                                        $"'{_dataEndpoint}'. Content: {content}");
                    }

                    requestMessage.Content = content;
                    var request = AddCommonHeadersAndSend(requestMessage);
                    jsonResult = ProcessResponse(request.Result);
                }

            aspectData.JsonResponse = jsonResult;
        }
Exemplo n.º 10
0
        /// <summary>
        /// Set the HTTP headers in the response using values from
        /// the supplied flow data.
        /// If the supplied headers already have values in the response
        /// then they will be amended rather than replaced.
        /// </summary>
        /// <param name="context">
        /// The <see cref="HttpContext"/> to set the response headers in
        /// </param>
        /// <param name="flowData">
        /// The flow data containing the headers to set.
        /// </param>
        public static void SetHeaders(HttpContext context,
                                      IFlowData flowData)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (flowData == null)
            {
                throw new ArgumentNullException(nameof(flowData));
            }

            var element = flowData.Pipeline.GetElement <ISetHeadersElement>();

            foreach (var header in flowData.GetFromElement(element)
                     .ResponseHeaderDictionary)
            {
                if (context.Response.Headers.ContainsKey(header.Key))
                {
                    context.Response.Headers.Append(header.Key, header.Value);
                }
                else
                {
                    context.Response.Headers.Add(header.Key, header.Value);
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Process method checks for presence of a session id and sequence
        /// number. If they do not exist then they are initialized in evidence.
        /// If they do exist in evidence then the sequence number is incremented
        /// and added back to the evidence.
        /// </summary>
        /// <param name="data">
        /// The <see cref="IFlowData"/> instance to process.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if the supplied data instance is null
        /// </exception>
        protected override void ProcessInternal(IFlowData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            var evidence = data.GetEvidence().AsDictionary();

            // If the evidence does not contain a session id then create a new one.
            if (evidence.ContainsKey(Constants.EVIDENCE_SESSIONID) == false)
            {
                data.AddEvidence(Constants.EVIDENCE_SESSIONID, GetNewSessionId());
            }

            // If the evidence does not have a sequence then add one. Otherwise
            // increment it.
            if (evidence.ContainsKey(Constants.EVIDENCE_SEQUENCE) == false)
            {
                data.AddEvidence(Constants.EVIDENCE_SEQUENCE, 1);
            }
            else if (evidence.TryGetValue(Constants.EVIDENCE_SEQUENCE, out object sequence))
            {
                if (sequence is int result || (sequence is string seq && int.TryParse(seq, out result)))
                {
                    data.AddEvidence(Constants.EVIDENCE_SEQUENCE, result + 1);
                }
                else
                {
                    data.AddError(new Exception(Messages.MessageFailSequenceNumberParse), this);
                    Logger.LogError(Messages.MessageFailSequenceNumberIncrement);
                }
            }
Exemplo n.º 12
0
 /// <summary>
 /// Check if the given key is needed by the given flowdata.
 /// If it is then add it as evidence.
 /// </summary>
 /// <param name="flowData">
 /// The <see cref="IFlowData"/> to add the evidence to.
 /// </param>
 /// <param name="key">
 /// The evidence key
 /// </param>
 /// <param name="value">
 /// The evidence value
 /// </param>
 private static void CheckAndAdd(IFlowData flowData, string key, object value)
 {
     if (flowData.EvidenceKeyFilter.Include(key))
     {
         flowData.AddEvidence(key, value);
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Get the names and values for all the JSON properties required
        /// to represent the given source data.
        /// The method adds meta-properties as required such as
        /// *nullreason, *delayexecution, etc.
        /// </summary>
        /// <param name="flowData">
        /// The <see cref="IFlowData"/> for the current request.
        /// </param>
        /// <param name="dataPath">
        /// The . separated name of the container that the supplied
        /// data will be added to.
        /// For example, 'location' or 'devices.profiles'
        /// </param>
        /// <param name="sourceData">
        /// The source data to use when populating the result.
        /// </param>
        /// <param name="config">
        /// The configuration to use.
        /// </param>
        /// <returns>
        /// A new dictionary with string keys and object values.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if required parameters are null
        /// </exception>
        protected virtual Dictionary <string, object> GetValues(
            IFlowData flowData,
            string dataPath,
            IReadOnlyDictionary <string, object> sourceData,
            PipelineConfig config)
        {
            if (dataPath == null)
            {
                throw new ArgumentNullException(nameof(dataPath));
            }
            if (sourceData == null)
            {
                throw new ArgumentNullException(nameof(sourceData));
            }
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            var values = new Dictionary <string, object>();

            foreach (var value in sourceData)
            {
                AddJsonValuesForProperty(flowData, values, dataPath,
                                         value.Key, value.Value, config, false);
            }
            return(values);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Process the given <see cref="IFlowData"/> with this FlowElement.
        /// </summary>
        /// <param name="data">
        /// The <see cref="IFlowData"/> instance that provides input evidence
        /// and carries the output data to the user.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if the supplied data parameter is null.
        /// </exception>
        public virtual void Process(IFlowData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Stopwatch sw = null;

#pragma warning disable CS0618 // Type or member is obsolete
            // This usage will be replaced once the Cancellation Token
            // mechanism is available.
            if (data.Stop == false)
#pragma warning restore CS0618 // Type or member is obsolete
            {
                bool log = Logger.IsEnabled(LogLevel.Debug);
                if (log)
                {
                    Logger.LogDebug($"FlowElement " +
                                    $"'{GetType().Name}' started processing.");
                    sw = Stopwatch.StartNew();
                }
                ProcessInternal(data);
                if (log)
                {
                    Logger.LogDebug($"FlowElement " +
                                    $"'{GetType().Name}' finished processing. " +
                                    $"Elapsed time: {sw.ElapsedMilliseconds}ms");
                }
            }
        }
        public void FlowElementCached_Process_CheckCacheGet()
        {
            // Arrange

            var evidence = new Dictionary <string, object>()
            {
                { "user-agent", "1234" }
            };
            var             mockData   = MockFlowData.CreateFromEvidence(evidence, false);
            IFlowData       data       = mockData.Object;
            EmptyEngineData cachedData = new EmptyEngineData(
                _loggerFactory.CreateLogger <EmptyEngineData>(),
                data.Pipeline,
                _engine,
                new Mock <IMissingPropertyService>().Object);

            cachedData.ValueOne = 2;
            _cache.Setup(c => c[It.IsAny <IFlowData>()])
            .Returns(cachedData);

            // Act
            _engine.Process(data);

            // Assert
            // Verify that the cached result was added to the flow data.
            mockData.Verify(d => d.GetOrAdd(
                                It.IsAny <ITypedKey <EmptyEngineData> >(),
                                It.Is <Func <IPipeline, EmptyEngineData> >(f => f(mockData.Object.Pipeline) == cachedData)), Times.Once());
            // Verify that the cache was checked once.
            _cache.Verify(c => c[It.Is <IFlowData>(d => d == data)], Times.Once);
            // Verify that the Put method of the cache was not called.
            _cache.Verify(c => c.Put(It.IsAny <IFlowData>(), It.IsAny <IElementData>()), Times.Never);
            // Verify the CacheHit flag is true.
            Assert.IsTrue(cachedData.CacheHit);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Perform processing for this engine
        /// </summary>
        /// <param name="data">
        /// The <see cref="IFlowData"/> instance containing data for the
        /// current request.
        /// </param>
        /// <param name="deviceData">
        /// The <see cref="IDeviceDataHash"/> instance to populate with
        /// property values
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if a required parameter is null
        /// </exception>
        protected override void ProcessEngine(IFlowData data, IDeviceDataHash deviceData)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            if (deviceData == null)
            {
                throw new ArgumentNullException(nameof(deviceData));
            }

            using (var relevantEvidence = new EvidenceDeviceDetectionSwig())
            {
                foreach (var evidenceItem in data.GetEvidence().AsDictionary())
                {
                    if (EvidenceKeyFilter.Include(evidenceItem.Key))
                    {
                        relevantEvidence.Add(new KeyValuePair <string, string>(
                                                 evidenceItem.Key,
                                                 evidenceItem.Value.ToString()));
                    }
                }

                // The results object is disposed in the dispose method of the
                // DeviceDataHash object.
#pragma warning disable CA2000 // Dispose objects before losing scope
                (deviceData as DeviceDataHash).SetResults(new ResultsSwigWrapper(_engine.process(relevantEvidence)));
#pragma warning restore CA2000 // Dispose objects before losing scope
            }
        }
        protected override void ProcessEngine(IFlowData data, IStarSignData aspectData)
        {
            // Cast aspectData to AgeData so the 'setter' is available.
            StarSignData starSignData = (StarSignData)aspectData;

            if (data.TryGetEvidence("date-of-birth", out DateTime dateOfBirth))
            {
                // "date-of-birth" is there, so set the star sign.
                var monthAndDay = new DateTime(1, dateOfBirth.Month, dateOfBirth.Day);
                foreach (var starSign in _starSigns)
                {
                    if (monthAndDay > starSign.Start &&
                        monthAndDay < starSign.End)
                    {
                        // The star sign has been found, so set it in the
                        // results.
                        starSignData.StarSign = starSign.Name;
                        break;
                    }
                }
            }
            else
            {
                // "date-of-birth" is not there, so set the star sign to unknown.
                starSignData.StarSign = "Unknown";
            }
        }
        /// <summary>
        /// Add any errors in the flow data object to the dictionary
        /// </summary>
        /// <param name="data"></param>
        /// <param name="allProperties"></param>
        /// <exception cref="ArgumentNullException">
        /// Thrown if one of the supplied parameters is null
        /// </exception>
        protected static void AddErrors(IFlowData data,
                                        Dictionary <String, object> allProperties)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            if (allProperties == null)
            {
                throw new ArgumentNullException(nameof(allProperties));
            }

            // If there are any errors then add them to the Json.
            if (data.Errors != null && data.Errors.Count > 0)
            {
                var errors = new Dictionary <string, List <string> >();
                foreach (var error in data.Errors)
                {
                    if (errors.ContainsKey(error.FlowElement.ElementDataKey))
                    {
                        errors[error.FlowElement.ElementDataKey].Add(error.ExceptionData.Message);
                    }
                    else
                    {
                        errors.Add(error.FlowElement.ElementDataKey,
                                   new List <string>()
                        {
                            error.ExceptionData.Message
                        });
                    }
                }
                allProperties.Add("errors", errors);
            }
        }
Exemplo n.º 19
0
 protected override void ProcessCloudEngine(IFlowData data, TestData aspectData, string json)
 {
     if (string.IsNullOrEmpty(json))
     {
         Assert.Fail("'json' value should not be null or empty if " +
                     "this method is called");
     }
 }
Exemplo n.º 20
0
 /// <summary>
 /// Implementation of method from the base class
 /// <see cref="FlowElementBase{T, TMeta}"/>.
 /// This exists to centralize the results caching logic.
 /// </summary>
 /// <param name="data">
 /// The <see cref="IFlowData"/> instance that provides the evidence
 /// and holds the result.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// Thrown if the parameter is null
 /// </exception>
 protected sealed override void ProcessInternal(IFlowData data)
 {
     if (data == null)
     {
         throw new ArgumentNullException(nameof(data));
     }
     ProcessWithCache(data);
 }
Exemplo n.º 21
0
        protected override void ProcessInternal(IFlowData data)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            // This usage will be replaced once the Cancellation Token
            // mechanism is available.
            data.Stop = true;
#pragma warning restore CS0618 // Type or member is obsolete
        }
        public void FlowDataProvider_NullFlowData()
        {
            IFlowData flowData = _provider.GetFlowData();

            Assert.IsNull(
                flowData,
                "GetFlowData returned an object but expected null.");
        }
Exemplo n.º 23
0
 /// <summary>
 /// Default process method.
 /// </summary>
 /// <param name="data"></param>
 /// <exception cref="ArgumentNullException">
 /// Thrown if the supplied flow data is null.
 /// </exception>
 protected override void ProcessInternal(IFlowData data)
 {
     if (data == null)
     {
         throw new ArgumentNullException(nameof(data));
     }
     SetUp(data);
 }
        /// <summary>
        /// Add the specified data to the cache.
        /// </summary>
        /// <param name="data">
        /// The <see cref="IFlowData"/> to use as a key.
        /// </param>
        /// <param name="value">
        /// The <code>TValue</code> to store with the key.
        /// </param>
        public virtual void Put(IFlowData data, TValue value)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            _internalCache.Put(data.GenerateKey(GetFilter()), value);
        }
Exemplo n.º 25
0
        protected override void ProcessInternal(IFlowData data)
        {
            TestElementData elementData = data.GetOrAdd(
                ElementDataKeyTyped,
                (p) => new TestElementData(p));
            int value = (int)data.GetEvidence()[EvidenceKeys[0]];

            elementData.Result = value * 5;
        }
Exemplo n.º 26
0
        /// <summary>
        /// Process the client IP address by splitting the segments into an
        /// array
        /// </summary>
        /// <param name="data">FlowData to add the result to</param>
        protected override void ProcessInternal(IFlowData data)
        {
            SplitIpData elementData = (SplitIpData)data.GetOrAdd(
                ElementDataKeyTyped,
                (f) => base.CreateElementData(f));
            string ip = ((string)data.GetEvidence()[EvidenceKeys[0]]);

            elementData.ClientIp = ip.Split('.', ':');
        }
Exemplo n.º 27
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="baseCaps">
 /// The parent <see cref="HttpBrowserCapabilities"/> instance to
 /// create this instance from.
 /// </param>
 /// <param name="request">
 /// The current <see cref="HttpRequest"/>
 /// </param>
 /// <param name="flowData">
 /// The results from the <see cref="IPipeline"/> for the current
 /// request
 /// </param>
 public PipelineCapabilities(
     HttpBrowserCapabilities baseCaps,
     HttpRequest request,
     IFlowData flowData) : base()
 {
     _baseCaps = baseCaps;
     _request  = request;
     FlowData  = flowData;
 }
Exemplo n.º 28
0
        public void ValidateData(IFlowData data, bool validEvidence = true)
        {
            var elementData = data.GetFromElement(_engine);
            var dict        = elementData.AsDictionary();

            foreach (var property in _engine.Properties
                     .Where(p => p.Available &&
                            // The JavascriptImageOptimiser property is deprecated.
                            // It exists in the meta-data but is never populated
                            // so we need to ignore it here.
                            p.Name.Equals("JavascriptImageOptimiser", StringComparison.OrdinalIgnoreCase) == false))
            {
                Assert.IsTrue(dict.ContainsKey(property.Name));
                IAspectPropertyValue value = dict[property.Name] as IAspectPropertyValue;
                if (validEvidence)
                {
                    Assert.IsTrue(value.HasValue);
                }
                else
                {
                    if (property.Category.Equals("Device Metrics"))
                    {
                        Assert.IsTrue(value.HasValue);
                    }
                    else
                    {
                        Assert.IsFalse(value.HasValue);
                        if (EvidenceContainsUserAgent(data) == false)
                        {
                            Assert.AreEqual("The evidence required to determine" +
                                            " this property was not supplied. The most" +
                                            " common evidence passed to this engine is" +
                                            " 'header.user-agent'.", value.NoValueMessage);
                        }
                        else
                        {
                            Assert.AreEqual("No matching profiles could be " +
                                            "found for the supplied evidence. A 'best " +
                                            "guess' can be returned by configuring more " +
                                            "lenient matching rules. See " +
                                            "https://51degrees.com/documentation/_device_detection__features__false_positive_control.html", value.NoValueMessage);
                        }
                    }
                }
            }
            Assert.IsTrue(string.IsNullOrEmpty(elementData.DeviceId.Value) == false);
            if (validEvidence == false)
            {
                Assert.AreEqual("0-0-0-0", elementData.DeviceId.Value);
            }

            var validKeys = data.GetEvidence().AsDictionary().Keys.Where(
                k => _engine.EvidenceKeyFilter.Include(k)).Count();

            Assert.AreEqual(validKeys, elementData.UserAgents.Value.Count);
        }
Exemplo n.º 29
0
        protected override void ProcessInternal(IFlowData data)
        {
            var monthAndDay = new DateTime(1, 1, 1);

            // Create a new IStarSignData, and cast to StarSignData so the 'setter' is available.
            StarSignData starSignData = (StarSignData)data.GetOrAdd(ElementDataKey, CreateElementData);

            bool validDateOfBirth = false;

            if (data.TryGetEvidence("cookie.date-of-birth", out string dateString))
            {
                // "date-of-birth" is there, so parse it.
                string[] dateSections = dateString.Split('/');
                try
                {
                    monthAndDay = new DateTime(
                        1,
                        int.Parse(dateSections[1]),
                        int.Parse(dateSections[0]));
                    validDateOfBirth = true;
                }
                catch (Exception)
                {
                }
            }
            if (validDateOfBirth)
            {
                // "date-of-birth" is valid, so set the star sign.
                foreach (var starSign in _starSigns)
                {
                    if (monthAndDay > starSign.Start &&
                        monthAndDay < starSign.End)
                    {
                        // The star sign has been found, so set it in the
                        // results.
                        starSignData.StarSign = starSign.Name;
                        break;
                    }
                }
                // No need to run the client side code again.
                starSignData.DobJavaScript = new JavaScript("");
            }
            else
            {
                // "date-of-birth" is not there, so set the star sign to unknown.
                starSignData.StarSign = "Unknown";
                // Set the client side JavaScript to get the date of birth.
                starSignData.DobJavaScript = new JavaScript(
                    "var dob = window.prompt('Enter your date of birth.','dd/mm/yyyy');" +
                    "if (dob != null) {" +
                    "document.cookie='date-of-birth='+dob;" +
                    "location.reload();" +
                    "}");
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Add any JavaScript properties to the dictionary
        /// </summary>
        /// <param name="data"></param>
        /// <param name="allProperties"></param>
        private void AddJavaScriptProperties(IFlowData data,
                                             Dictionary <String, object> allProperties)
        {
            var javascriptProperties = GetJavaScriptProperties(data, allProperties);

            if (javascriptProperties != null &&
                javascriptProperties.Count > 0)
            {
                allProperties.Add("javascriptProperties", javascriptProperties);
            }
        }