Exemple #1
0
        public InstancesBuilder(IEnumerable <T> data, int classindex, int trainingsize = 0)
        {
            this.data = data.ToArray();
            if (this.data.Any(row => row is string))
            {
                throw new ArgumentException("data are strings, perhaps you intended to call Runtime.LoadFromFiles<>");
            }
            this.classindex   = classindex;
            this.trainingsize = trainingsize;

            T template = this.data[0];

            type        = typeof(T) == typeof(object) ? template.GetType() : typeof(T);
            attsbuilder = new AttributesBuilder <T>(this.data);

            var pis = template is IExtendableObj <object>?
                      Helpers.GetProps(((IExtendableObj <object>)template).BaseObject.GetType()) :
                          Helpers.GetProps(type);

            properties = pis.
                         Where(pi => !InternalHelpers.IsAtt <IgnoreFeatureAttribute>(pi)).
                         Select(pi => pi.Name).
                         ToArray();
            var tohasclasspis = pis.Where(InternalHelpers.IsAtt <AppendHasClassifierAttribute>).ToArray();

            tohasclass           = tohasclasspis.Select(pi => pi.Name).ToArray();
            tobinarize           = pis.Where(InternalHelpers.IsAtt <BinarizeAttribute>).Select(pi => pi.Name).ToArray();
            expected_has_classes = tohasclasspis.ToDictionary(
                pi => pi.Name,
                pi => InternalHelpers.ToAtt <AppendHasClassifierAttribute>(pi).Classifier);
        }
        public void SqlDecimalUtilsPerformanceTest(byte scale)
        {
            var sourceValue = sourceDecimal;
            var counter     = new Stopwatch();

            var sqlDecimal = new SqlDecimal(sourceValue.Precision, scale, sourceValue.IsPositive, sourceValue.Data);

            var list = new List <long>();

            for (var i = 0; i < 100; i++)
            {
                counter.Restart();

                for (var j = 0; j < 100000; j++)
                {
                    _ = InternalHelpers.TruncateToNetDecimal(sqlDecimal);
                }

                counter.Stop();
                list.Add(counter.ElapsedMilliseconds);
            }

            Console.WriteLine(
                "Val:{0}  Scale:{1}  Min:{2}  Avg:{3}",
                sqlDecimal,
                sqlDecimal.Scale,
                list.Min(),
                list.Average());
        }
        public static ILogResponseBodyStrategy Create(Stream stream, Encoding encoding, Logger logger)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

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

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

            if (!stream.CanRead)
            {
                return(new NullLogResponseBody());
            }

            if (stream.Length > Constants.MaximumAllowedFileSizeInBytes)
            {
                return(new LogResponseBodySizeTooLargeException(logger, stream.Length, Constants.MaximumAllowedFileSizeInBytes));
            }

            var    headers          = logger.DataContainer.HttpProperties.Response?.Properties?.Headers;
            string contentType      = headers?.FirstOrDefault(p => string.Compare(p.Key, "Content-Type", StringComparison.OrdinalIgnoreCase) == 0).Value;
            string responseFileName = InternalHelpers.GenerateResponseFileName(headers);

            IReadStreamStrategy strategy = ReadStreamStrategyFactory.Create(stream, encoding, contentType);

            return(new LogResponseBody(logger, responseFileName, strategy));
        }
Exemple #4
0
        public void ContainsFileAttribute()
        {
            FileAttributes attr = FileAttributes.Archive;

            InternalHelpers.ContainsFileAttribute(attr, FileAttributes.Archive).Should().Be(true);
            InternalHelpers.ContainsFileAttribute(attr, FileAttributes.System).Should().Be(false);
        }
Exemple #5
0
        public override void LoadDataFromPropertiesDictionary(DiscountOrder discount, IPropertyProvider fields, ILocalization localization)
        {
            discount.Localization = localization;
            LoadBaseProperties(discount, fields, localization, _storeService);

            discount.RequiredItemIds    = StoreHelper.ReadMultiStoreItemFromPropertiesDictionary(_aliasses.items, localization, fields).Split(',').Select(id => Common.Helpers.ParseInt(id)).Distinct().Where(id => id > 0).ToList();
            discount.AffectedOrderlines = StoreHelper.ReadMultiStoreItemFromPropertiesDictionary(_aliasses.affectedOrderlines, localization, fields).Split(',').Select(id => Common.Helpers.ParseInt(id)).Distinct().Where(id => id > 0).ToList();

            var tagsValue = StoreHelper.ReadMultiStoreItemFromPropertiesDictionary(_aliasses.affectedTags, localization, fields);

            discount.AffectedProductTags = InternalHelpers.ParseTagsString(tagsValue);

            DiscountOrderCondition condition;
            var discountOrderConditionParseResult = Enum.TryParse(StoreHelper.ReadMultiStoreItemFromPropertiesDictionary(_aliasses.orderCondition, localization, fields), out condition);

            discount.Condition = discountOrderConditionParseResult ? condition : DiscountOrderCondition.None;

            discount.NumberOfItemsCondition = StoreHelper.GetMultiStoreIntValue(_aliasses.numberOfItemsCondition, localization, fields);

            discount.MinimumOrderAmountInCents = StoreHelper.GetMultiStoreIntValue(_aliasses.minimumAmount, localization, fields);

            var shippingDiscountable = StoreHelper.ReadMultiStoreItemFromPropertiesDictionary(_aliasses.shippingDiscountable, localization, fields);

            discount.IncludeShippingInOrderDiscountableAmount = shippingDiscountable == "enable" || shippingDiscountable == "1" || shippingDiscountable == "true";

            // for backwards compatibility
            discount.CouponCode = StoreHelper.ReadMultiStoreItemFromPropertiesDictionary("couponCode", localization, fields);

            var oncePerCustomer = StoreHelper.ReadMultiStoreItemFromPropertiesDictionary(_aliasses.oncePerCustomer, localization, fields);

            discount.OncePerCustomer = oncePerCustomer == "enable" || oncePerCustomer == "1" || oncePerCustomer == "true";
        }
Exemple #6
0
        public static void Notify(Logger[] loggers)
        {
            if (loggers == null)
            {
                throw new ArgumentNullException();
            }

            if (!loggers.Any())
            {
                return;
            }

            FlushLogArgs args = FlushLogArgsFactory.Create(loggers);

            Guid?httpRequestId = args.HttpProperties == null ? (Guid?)null : args.HttpProperties.Request.Id;

            List <LogListenerDecorator> logListeners = KissLogConfiguration.Listeners.GetAll();

            foreach (LogListenerDecorator decorator in logListeners)
            {
                InternalHelpers.WrapInTryCatch(() =>
                {
                    Notify(args, decorator, httpRequestId);
                });
            }

            foreach (Logger logger in loggers)
            {
                logger.Reset();
            }
        }
Exemple #7
0
        public void OnFlush(FlushLogArgs args)
        {
            bool isValid = ValidateProperties();

            if (!isValid)
            {
                return;
            }

            InternalLogger.Log("RequestLogsApiListener: OnFlush begin", LogLevel.Trace);

            ObfuscateFlushLogArgsService obfuscateService = new ObfuscateFlushLogArgsService(ObfuscationService);

            obfuscateService.Obfuscate(args);

            CreateRequestLogRequest request = PayloadFactory.Create(args);

            request.OrganizationId = _application.OrganizationId;
            request.ApplicationId  = _application.ApplicationId;
            request.Keywords       = InternalHelpers.WrapInTryCatch(() => Options.Handlers.GenerateSearchKeywords(args));

            FlushOptions flushOptions = new FlushOptions
            {
                UseAsync    = UseAsync,
                OnException = OnException
            };

            IPublicApi kisslogApi = _kisslogApi ?? new PublicRestApi(ApiUrl, IgnoreSslCertificate);

            Flusher.FlushAsync(flushOptions, kisslogApi, args, request).ConfigureAwait(false);

            InternalLogger.Log("RequestLogsApiListener: OnFlush complete", LogLevel.Trace);
        }
Exemple #8
0
        public void OnFlush(FlushLogArgs args, ILogger logger)
        {
            FlushProperties flushProperties = GetAndValidateFlushProperties(args);

            if (flushProperties == null)
            {
                return;
            }

            InternalHelpers.Log("KissLogApiListener: OnFlush begin", LogLevel.Trace);

            ObfuscateService?.Obfuscate(args);
            TruncateService?.Truncate(args);

            Requests.CreateRequestLogRequest request = CreateRequestLogRequestFactory.Create(args);
            request.OrganizationId = flushProperties.Application.OrganizationId;
            request.ApplicationId  = flushProperties.Application.ApplicationId;
            request.Keywords       = Configuration.Configuration.Options.ApplyAddRequestKeywordstHeader(args);

            // we need to copy files, because we start a new Thread, and the existing files will be deleted before accessing them
            IList <LoggerFile> copy = CopyFiles(args.Files?.ToList());

            IFlusher flusher = CreateFlusher(flushProperties);

            if (UseAsync == true)
            {
                flusher.FlushAsync(request, copy).ConfigureAwait(false);
            }
            else
            {
                flusher.Flush(request, copy);
            }

            InternalHelpers.Log("KissLogApiListener: OnFlush complete", LogLevel.Trace);
        }
Exemple #9
0
 static KissLogWebApiExceptionFilterAttribute()
 {
     InternalHelpers.WrapInTryCatch(() =>
     {
         ModuleInitializer.Init();
     });
 }
 static KissLogExceptionLogger()
 {
     InternalHelpers.WrapInTryCatch(() =>
     {
         ModuleInitializer.Init();
     });
 }
Exemple #11
0
        /// <summary>
        /// Converts a list of property names and values to a list of type of <typeparamref name="T"/>.
        ///
        /// Population of complex nested child properties is supported by underscoring "_" into the
        /// nested child properties in the property name.
        /// </summary>
        /// <typeparam name="T">Type to instantiate and automap to</typeparam>
        /// <param name="listOfProperties">List of property names and values</param>
        /// <returns>List of type <typeparamref name="T"/></returns>
        public static IEnumerable <T> Map <T>(IEnumerable <IDictionary <string, object> > listOfProperties)
        {
            var instanceCache = new Dictionary <object, object>();

            foreach (var properties in listOfProperties)
            {
                var getInstanceResult = InternalHelpers.GetInstance(typeof(T), properties, 0);

                object instance = getInstanceResult.Item2;

                int instanceIdentifierHash = getInstanceResult.Item3;

                if (instanceCache.ContainsKey(instanceIdentifierHash) == false)
                {
                    instanceCache.Add(instanceIdentifierHash, instance);
                }

                var caseInsensitiveDictionary = new Dictionary <string, object>(properties, StringComparer.OrdinalIgnoreCase);

                InternalHelpers.Map(caseInsensitiveDictionary, instance);
            }

            foreach (var pair in instanceCache)
            {
                yield return(( T )pair.Value);
            }
        }
Exemple #12
0
        public BaseAttributeSelectionEvaluator(Runtime rt, I impl)
        {
            this.rt = rt;
            Impl    = impl;

            InternalHelpers.SetSeedOnInstance(impl);
        }
        internal static void UpdateSiteName(Activity activity, string newID)
        {
            if (activity == null)
            {
                throw new ArgumentException("activity");
            }
            string str = newID;

            if (Helpers.IsActivityLocked(activity))
            {
                str = InternalHelpers.GenerateQualifiedNameForLockedActivity(activity, newID);
            }
            activity.Site.Name = str;
            if (activity is CompositeActivity)
            {
                foreach (Activity activity2 in Helpers.GetNestedActivities(activity as CompositeActivity))
                {
                    if (Helpers.IsActivityLocked(activity2))
                    {
                        Activity declaringActivity = Helpers.GetDeclaringActivity(activity2);
                        activity2.Site.Name = declaringActivity.Site.Name + "." + activity2.Name;
                    }
                }
            }
        }
        /// <summary>
        /// Converts a list of property names and values to a list of type of <typeparamref name="T"/>.
        ///
        /// Population of complex nested child properties is supported by underscoring "_" into the
        /// nested child properties in the property name.
        /// </summary>
        /// <typeparam name="T">Type to instantiate and automap to</typeparam>
        /// <param name="listOfProperties">List of property names and values</param>
        /// <param name="keepCache">If false, clears instance cache after mapping is completed. Defaults to true, meaning instances are kept between calls.</param>
        /// <returns>List of type <typeparamref name="T"/></returns>
        public static IEnumerable <T> Map <T>(IEnumerable <IDictionary <string, object> > listOfProperties, bool keepCache = true)
        {
            var instanceCache = new Dictionary <object, object>();

            foreach (var properties in listOfProperties)
            {
                var getInstanceResult = InternalHelpers.GetInstance(typeof(T), properties);

                object instance = getInstanceResult.Item2;

                var key = getInstanceResult.Item3;

                if (instanceCache.ContainsKey(key) == false)
                {
                    instanceCache.Add(key, instance);
                }

                var caseInsensitiveDictionary = new Dictionary <string, object>(properties, StringComparer.OrdinalIgnoreCase);

                InternalHelpers.Map(caseInsensitiveDictionary, instance);
            }

            if (!keepCache)
            {
                Cache.ClearInstanceCache();
            }

            return(instanceCache.Select(pair => ( T )pair.Value));
        }
Exemple #15
0
        public BaseAssociation(Runtime rt, I impl)
        {
            this.rt = rt;
            Impl    = impl;

            InternalHelpers.SetSeedOnInstance(impl);
        }
        public void GetServerNameFromHttpRequestDoesNotThrowExceptionForNullServerVariables()
        {
            var httpRequest = new Mock <HttpRequestBase>();

            httpRequest.Setup(p => p.ServerVariables).Returns((NameValueCollection)null);

            InternalHelpers.GetServerNameFromHttpRequest(httpRequest.Object);
        }
        public void MachineNameIsCopied(string url)
        {
            FlushLogArgs item = FlushLogArgsFactory.Create(new[] { new Logger(url: url) });

            string machineName = InternalHelpers.GetMachineName();

            Assert.AreEqual(machineName, item.HttpProperties.Request.MachineName);
        }
Exemple #18
0
        public void MachineNameIsCopied()
        {
            HttpProperties result = HttpPropertiesFactory.Create("/");

            string machineName = InternalHelpers.GetMachineName();

            Assert.AreEqual(machineName, result.Request.MachineName);
        }
Exemple #19
0
        public void AddFileAttrribute()
        {
            FileAttributes attr = FileAttributes.Archive;

            FileAttributes result = InternalHelpers.AddFileAttrribute(attr, FileAttributes.System);

            InternalHelpers.ContainsFileAttribute(result, FileAttributes.Archive).Should().Be(true);
            InternalHelpers.ContainsFileAttribute(result, FileAttributes.System).Should().Be(true);
        }
Exemple #20
0
        public void RemoveFileAttribute()
        {
            FileAttributes attr = FileAttributes.Archive | FileAttributes.System;

            FileAttributes result = InternalHelpers.RemoveFileAttribute(attr, FileAttributes.Archive);

            InternalHelpers.ContainsFileAttribute(result, FileAttributes.Archive).Should().Be(false);
            InternalHelpers.ContainsFileAttribute(result, FileAttributes.System).Should().Be(true);
        }
        public void ClaimsIdentityToKeyValuePairIgnoresEmptyKeyNames(string keyName)
        {
            ClaimsIdentity collection = new ClaimsIdentity();

            collection.AddClaim(new Claim(keyName, Guid.NewGuid().ToString()));

            var result = InternalHelpers.ToKeyValuePair(collection);

            Assert.AreEqual(0, result.Count);
        }
        public void HttpCookieCollectionToKeyValuePairIgnoresEmptyKeyNames(string keyName)
        {
            HttpCookieCollection collection = new HttpCookieCollection();

            collection.Add(new HttpCookie(keyName, Guid.NewGuid().ToString()));

            var result = InternalHelpers.ToKeyValuePair(collection);

            Assert.AreEqual(0, result.Count);
        }
Exemple #23
0
        public static void UnloadFrozenObject(object o)
        {
            var optr          = Marshal.ReadIntPtr((IntPtr)Unsafe.AsPointer(ref o));
            var baseAddress   = optr - IntPtr.Size - IntPtr.Size - IntPtr.Size; // 3 because optr is actually pointing to MT*
            var length        = Marshal.ReadIntPtr(baseAddress);
            var segmentHandle = Marshal.ReadIntPtr(baseAddress, IntPtr.Size);

            InternalHelpers.UnregisterFrozenSegment(segmentHandle);
            FreeMemory(baseAddress, length);
        }
        private static string FormatAsSimpleType(object value, ConstructionLogContext context)
        {
            Func <object, string> formatter;

            return(value == null || value.GetType().IsSimpleType()
                                ? InternalHelpers.DumpValue(value)
                                : context.ValueFormatters.TryGetValue(value.GetType(), out formatter)
                                        ? formatter(value)
                                        : null);
        }
        public void SqlDecimalUtilsBigScaleTest(byte scale)
        {
            var sourceValue = sourceDecimal;

            var sqlDecimal = new SqlDecimal(sourceValue.Precision, scale, sourceValue.IsPositive, sourceValue.Data);
            var output     = InternalHelpers.TruncateToNetDecimal(sqlDecimal);
            var dec        = decimal.Parse(sqlDecimal.ToString(), CultureInfo.InvariantCulture);

            Assert.That(output, Is.EqualTo(dec));
        }
Exemple #26
0
        public void TryAddFileAttrribute()
        {
            FileAttributes attr = FileAttributes.Archive;

            InternalHelpers.TryAddFileAttrribute(attr, FileAttributes.System, out attr).Should().BeTrue("First add failed");
            InternalHelpers.ContainsFileAttribute(attr, FileAttributes.System).Should().Be(true, "First test failed");

            InternalHelpers.TryAddFileAttrribute(attr, FileAttributes.System, out attr).Should().BeFalse("Second add failed");
            InternalHelpers.ContainsFileAttribute(attr, FileAttributes.System).Should().Be(true, "Second test failed");
        }
Exemple #27
0
        public void TryRemoveFileAttrribute()
        {
            FileAttributes attr = FileAttributes.Archive | FileAttributes.System;

            InternalHelpers.TryRemoveFileAttrribute(attr, FileAttributes.System, out attr).Should().BeTrue("First remove failed");
            InternalHelpers.ContainsFileAttribute(attr, FileAttributes.System).Should().Be(false, "First test failed");

            InternalHelpers.TryRemoveFileAttrribute(attr, FileAttributes.System, out attr).Should().BeFalse("Second remove failed");
            InternalHelpers.ContainsFileAttribute(attr, FileAttributes.System).Should().Be(false, "First test failed");
        }
Exemple #28
0
        public void QueryCollectionToKeyValuePairIgnoresEmptyKeyNames(string keyName)
        {
            CustomQueryCollection collection = new CustomQueryCollection(new Dictionary <string, StringValues>
            {
                { keyName, Guid.NewGuid().ToString() }
            });

            var result = InternalHelpers.ToKeyValuePair(collection);

            Assert.AreEqual(0, result.Count);
        }
        public void CanReadResponseBody(string contentType, bool canRead)
        {
            List <KeyValuePair <string, string> > headers = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Content-Type", contentType)
            };

            var result = InternalHelpers.CanReadResponseBody(headers);

            Assert.AreEqual(canRead, result);
        }
        public void GetExplicitLogResponseBodyReturnsNullIfNoValueIsFound()
        {
            Logger logger1 = new Logger();
            Logger logger2 = new Logger();

            bool?value = InternalHelpers.GetExplicitLogResponseBody(new List <Logger> {
                logger1, logger2
            });

            Assert.IsNull(value);
        }