Esempio n. 1
0
 internal Type[] GetClosedGenericImplementationsFor(Type closedGenericServiceType)
 {
     return(ExtensionHelpers.GetClosedGenericImplementationsFor(
                closedGenericServiceType,
                from item in this.GetItemsFor(closedGenericServiceType)
                select item.ImplementationType));
 }
        private void LoadExtensions()
        {
            cmbExtension.Items.Clear();
            string extensionsPath = Path.Combine(Environment.CurrentDirectory, "Extensions");

            cmbExtension.Items.AddRange(ExtensionHelpers.QueryAssembliesForTypes(extensionsPath, "ITransportExtension"));
        }
        private Expression BuildDecoratorEnumerableExpressionForConstantEnumerable(
            Delegate wrapInstanceWithDecoratorDelegate, IEnumerable collection)
        {
            // Build the query: from item in collection select wrapInstanceWithDecorator(item);
            IEnumerable decoratedCollection =
                collection.Select(this.registeredServiceType, wrapInstanceWithDecoratorDelegate);

            // Passing the enumerable type is needed when running in the Silverlight sandbox.
            Type enumerableServiceType = typeof(IEnumerable <>).MakeGenericType(this.registeredServiceType);

            if (this.Lifestyle == Lifestyle.Singleton)
            {
                Func <IEnumerable> collectionCreator = () =>
                {
                    Array array = ToArray(this.registeredServiceType, decoratedCollection);
                    return(ExtensionHelpers.MakeReadOnly(this.registeredServiceType, array));
                };

                IEnumerable singleton = this.GetSingletonDecoratedCollection(collectionCreator);

                return(Expression.Constant(singleton, enumerableServiceType));
            }

            return(Expression.Constant(decoratedCollection, enumerableServiceType));
        }
Esempio n. 4
0
        public ActionResult Index()
        {
            var           user = db.Users.Find(User.Identity.GetUserId());
            HomeViewModel vm   = new HomeViewModel();

            vm.Household    = db.Households.Find(User.Identity.GetHouseholdId());
            vm.BankAccounts = new List <BankAccountViewModel>();
            var accounts = db.BankAccounts.Where(a => a.Owner.HouseholdId == vm.Household.Id).ToList();

            foreach (var account in accounts)
            {
                var type     = db.BankAccountTypes.Find(account.BankAccountTypeId).Name;
                var bankName = db.BankNames.Find(account.BankNameId).Name;
                var owner    = db.Users.Find(account.OwnerId).FullName;
                vm.BankAccounts.Add(new BankAccountViewModel
                {
                    Id            = account.Id,
                    Name          = account.NickName,
                    AccountType   = type,
                    BankName      = bankName,
                    Owner         = owner,
                    Balance       = account.Balance.ToString("C", ExtensionHelpers.GetCulture(User.Identity.GetCultureId(), User.Identity.GetNegFormatId())),
                    BalanceEditor = new AccountBalanceEditor {
                        BankAccountBalance = account.Balance
                    },
                    Details            = GetBankAccountDetails(account.Id),
                    TransactionCreator = GetTransactionCreator(account)
                });
            }
            return(View(vm));
        }
        private Expression BuildDecoratorEnumerableExpressionForNonConstantExpression(
            Delegate wrapInstanceWithDecorator, Expression expression)
        {
            // Build the query: from item in expression select wrapInstanceWithDecorator(item);
            var callExpression =
                DecoratorHelpers.Select(expression, this.registeredServiceType, wrapInstanceWithDecorator);

            if (this.Lifestyle == Lifestyle.Singleton)
            {
                Type enumerableServiceType = typeof(IEnumerable <>).MakeGenericType(this.registeredServiceType);

                Func <IEnumerable> collectionCreator = () =>
                {
                    Type     funcType            = typeof(Func <>).MakeGenericType(enumerableServiceType);
                    Delegate lambda              = Expression.Lambda(funcType, callExpression).Compile();
                    var      decoratedCollection = (IEnumerable)lambda.DynamicInvoke();
                    Array    array = ToArray(this.registeredServiceType, decoratedCollection);
                    return(ExtensionHelpers.MakeReadOnly(this.registeredServiceType, array));
                };

                IEnumerable singleton = this.GetSingletonDecoratedCollection(collectionCreator);

                // Passing the enumerable type is needed when running in a (Silverlight) sandbox.
                return(Expression.Constant(singleton, enumerableServiceType));
            }

            return(callExpression);
        }
Esempio n. 6
0
 /// <summary>
 /// Load the Transport extension, this method will throw if the extension cannot be loaded.
 /// </summary>
 void cmbExtension_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (cmbExtension.SelectedIndex >= 0)
     {
         // try loading the transport extension...
         transportExtension = ExtensionHelpers.RetrieveExtension(cmbExtension.SelectedItem.ToString());
     }
 }
 private void AddExtensions(string[] extensions)
 {
     foreach (string extensionName in extensions)
     {
         string displayName = ExtensionHelpers.CheckForDisplayName(extensionName);
         cmbAuthMode.Items.Add(new ExtensionDetails(displayName, extensionName));
     }
 }
Esempio n. 8
0
        public override void Merge(IConventionContext context, Convention convention)
        {
            if (convention is SortConvention sortConvention &&
                Definition is not null &&
                sortConvention.Definition is not null)
            {
                ExtensionHelpers.MergeDictionary(
                    Definition.Bindings,
                    sortConvention.Definition.Bindings);

                ExtensionHelpers.MergeListDictionary(
                    Definition.Configurations,
                    sortConvention.Definition.Configurations);

                ExtensionHelpers.MergeListDictionary(
                    Definition.EnumConfigurations,
                    sortConvention.Definition.EnumConfigurations);

                for (var i = 0; i < Definition.Operations.Count; i++)
                {
                    sortConvention.Definition.Operations.Add(Definition.Operations[i]);
                }

                for (var i = 0; i < Definition.ProviderExtensions.Count; i++)
                {
                    sortConvention.Definition.ProviderExtensions.Add(
                        Definition.ProviderExtensions[i]);
                }

                for (var i = 0; i < Definition.ProviderExtensionsTypes.Count; i++)
                {
                    sortConvention.Definition.ProviderExtensionsTypes.Add(
                        Definition.ProviderExtensionsTypes[i]);
                }

                if (Definition.ArgumentName != SortConventionDefinition.DefaultArgumentName)
                {
                    sortConvention.Definition.ArgumentName = Definition.ArgumentName;
                }

                if (Definition.Provider is not null)
                {
                    sortConvention.Definition.Provider = Definition.Provider;
                }

                if (Definition.ProviderInstance is not null)
                {
                    sortConvention.Definition.ProviderInstance = Definition.ProviderInstance;
                }

                if (Definition.DefaultBinding is not null)
                {
                    sortConvention.Definition.DefaultBinding = Definition.DefaultBinding;
                }
            }
        }
 private void InitialiseAuthMode()
 {
     if (chkIsSecure.Checked && (lastMode != cmbAuthMode.Text))
     {
         ExtensionDetails details = (ExtensionDetails)cmbAuthMode.Items[cmbAuthMode.SelectedIndex];
         authMode          = ExtensionHelpers.RetrieveAuthenticationMode(details.TypeName);
         authMode.Settings = settings;
         lastMode          = cmbAuthMode.Text;
     }
 }
        private void LoadModes()
        {
            cmbAuthMode.Items.Clear();
            string appPath = Environment.CurrentDirectory;

            AddExtensions(ExtensionHelpers.QueryAssembliesForTypes(appPath, "IAuthenticationMode"));
            string extensionsPath = Path.Combine(Environment.CurrentDirectory, "Extensions");

            AddExtensions(ExtensionHelpers.QueryAssembliesForTypes(extensionsPath, "IAuthenticationMode"));
        }
Esempio n. 11
0
 internal static void ServiceOrItsGenericTypeDefinitionIsAssignableFromImplementation(Type service,
                                                                                      Type implementation, string paramName)
 {
     if (service != implementation &&
         !ExtensionHelpers.ServiceIsAssignableFromImplementation(service, implementation))
     {
         throw new ArgumentException(
                   StringResources.SuppliedTypeDoesNotInheritFromOrImplement(service, implementation),
                   paramName);
     }
 }
        internal static IHtmlContent GenerateHtml <TModel, TProperty>(
            IHtmlHelper <TModel> htmlHelper,
            Expression <Func <TModel, TProperty> > propertyLambdaExpression,
            LabelViewModel labelOptions         = null,
            HintViewModel hintOptions           = null,
            FormGroupViewModel formGroupOptions = null,
            string classes = null,
            TextInputAppendixViewModel textInputAppendix = null,
            string type         = "text",
            string autocomplete = null
            )
            where TModel : GovUkViewModel
        {
            PropertyInfo property = ExpressionHelpers.GetPropertyFromExpression(propertyLambdaExpression);

            string propertyName = property.Name;

            TModel model = htmlHelper.ViewData.Model;

            string currentValue = ExtensionHelpers.GetCurrentValue(model, property, propertyLambdaExpression);

            string id = $"GovUk_{propertyName}";

            if (labelOptions != null)
            {
                labelOptions.For = id;
            }

            var textInputViewModel = new TextInputViewModel
            {
                Name              = $"GovUk_Text_{propertyName}",
                Id                = id,
                Value             = currentValue,
                Label             = labelOptions,
                Hint              = hintOptions,
                FormGroup         = formGroupOptions,
                Classes           = classes,
                TextInputAppendix = textInputAppendix,
                Type              = type,
                Attributes        = new Dictionary <string, string> {
                    { "autocomplete", autocomplete }
                }
            };

            if (model.HasErrorFor(property))
            {
                textInputViewModel.ErrorMessage = new ErrorMessageViewModel {
                    Text = model.GetErrorFor(property)
                };
            }

            return(htmlHelper.Partial("/GovUkDesignSystemComponents/TextInput.cshtml", textInputViewModel));
        }
Esempio n. 13
0
        internal static IHtmlContent GenerateHtml <TModel>(
            IHtmlHelper <TModel> htmlHelper,
            Expression <Func <TModel, string> > propertyLambdaExpression,
            int?rows = null,
            LabelViewModel labelOptions         = null,
            HintViewModel hintOptions           = null,
            FormGroupViewModel formGroupOptions = null
            )
            where TModel : GovUkViewModel
        {
            PropertyInfo property = ExpressionHelpers.GetPropertyFromExpression(propertyLambdaExpression);

            ThrowIfPropertyDoesNotHaveCharacterCountAttribute(property);

            string propertyName = property.Name;

            TModel model = htmlHelper.ViewData.Model;

            string currentValue = ExtensionHelpers.GetCurrentValue(model, property, propertyLambdaExpression);

            string id = $"GovUk_{propertyName}";

            if (labelOptions != null)
            {
                labelOptions.For = id;
            }

            int maximumCharacters = GetMaximumCharacters(property);

            var characterCountViewModel = new CharacterCountViewModel {
                Name      = $"GovUk_Text_{propertyName}",
                Id        = id,
                MaxLength = maximumCharacters,
                Value     = currentValue,
                Rows      = rows,
                Label     = labelOptions,
                Hint      = hintOptions,
                FormGroup = formGroupOptions
            };

            if (model.HasErrorFor(property))
            {
                characterCountViewModel.ErrorMessage = new ErrorMessageViewModel {
                    Text = model.GetErrorFor(property)
                };
            }

            return(htmlHelper.Partial("/GovUkDesignSystemComponents/CharacterCount.cshtml", characterCountViewModel));
        }
Esempio n. 14
0
        public HashSet <TransactionViewModel> GetBankAccountTransactions(BankAccount account)
        {
            HashSet <TransactionViewModel> transactions = new HashSet <TransactionViewModel>();

            foreach (var transaction in account.Transactions)
            {
                transaction.Category.Name = db.Categories.Find(transaction.CategoryId).Name;
                transactions.Add(new TransactionViewModel(
                                     transaction,
                                     ExtensionHelpers.GetCulture(User.Identity.GetCultureId(), User.Identity.GetNegFormatId()),
                                     db.Categories.ToList()
                                     ));
            }
            return(transactions);
        }
        internal static IHtmlContent GenerateHtml <TModel, TProperty>(
            IHtmlHelper <TModel> htmlHelper,
            Expression <Func <TModel, TProperty> > propertyLambdaExpression,
            LabelViewModel labelOptions         = null,
            HintViewModel hintOptions           = null,
            FormGroupViewModel formGroupOptions = null,
            string classes = null,
            TextInputAppendixViewModel textInputAppendix = null
            )
            where TModel : GovUkViewModel
        {
            var property = ExpressionHelpers.GetPropertyFromExpression(propertyLambdaExpression);

            var propertyName = property.Name;

            var model = htmlHelper.ViewData.Model;

            var id           = $"GovUk_{propertyName}";
            var currentValue = ExtensionHelpers.GetCurrentValue(model, property, propertyLambdaExpression);

            if (labelOptions != null)
            {
                labelOptions.For = id;
            }

            var textInputViewModel = new TextInputViewModel
            {
                Name              = $"GovUk_Text_{propertyName}",
                Id                = id,
                Value             = currentValue,
                Label             = labelOptions,
                Hint              = hintOptions,
                FormGroup         = formGroupOptions,
                Classes           = classes,
                TextInputAppendix = textInputAppendix
            };

            if (model.HasErrorFor(property))
            {
                textInputViewModel.ErrorMessage = new ErrorMessageViewModel {
                    Text = model.GetErrorFor(property)
                }
            }
            ;

            return(htmlHelper.Partial("~/Partials/TextInput.cshtml", textInputViewModel));
        }
    }
Esempio n. 16
0
        internal static void ServiceIsAssignableFromImplementations(Type serviceType,
                                                                    IEnumerable <Type> typesToRegister, string paramName, bool typeCanBeServiceType = false)
        {
            var invalidType = (
                from type in typesToRegister
                where !ExtensionHelpers.ServiceIsAssignableFromImplementation(serviceType, type)
                where !typeCanBeServiceType || type != serviceType
                select type)
                              .FirstOrDefault();

            if (invalidType != null)
            {
                throw new ArgumentException(
                          StringResources.SuppliedTypeDoesNotInheritFromOrImplement(serviceType, invalidType),
                          paramName);
            }
        }
        /// <summary>
        /// Lerps rectTransform to target position
        /// </summary>
        /// <param name="rectTransform">Rect transform of the object</param>
        /// <param name="targetPosition">End position of the Lerp</param>
        /// <param name="time">Time in seconds</param>
        /// <param name="owner">Class to run the lerp on</param>
        public static Coroutine LerpRectTransform(this RectTransform rectTransform, Vector3 targetPosition, float time, MonoBehaviour owner)
        {
            if (rectTransform == null)
            {
                return(null);
            }

            if (owner != null)
            {
                return(owner.StartCoroutine(ExtensionHelpers.LerpRectTransformPositions(rectTransform, targetPosition, time)));
            }
            else
            {
                Debug.Log("Our Owner is null");
                return(null);
            }
        }
        /// <summary>
        /// Lerps world space rotation to targeted rotation within speed (seconds)
        /// </summary>
        /// <param name="currentTransform">Transform with the starting rotation</param>
        /// <param name="targetRotation">End rotation of the lerp</param>
        /// <param name="time">Time in seconds</param>
        /// <param name="owner">Class to run the lerp on</param>
        /// <returns></returns>
        public static Coroutine LerpRotation(this Transform currentTransform, Vector3 targetRotation, float time, MonoBehaviour owner)
        {
            if (currentTransform == null)
            {
                return(null);
            }

            if (owner != null)
            {
                return(owner.StartCoroutine(ExtensionHelpers.LerpTransformRotations(currentTransform, targetRotation, time)));;
            }
            else
            {
                Debug.Log("Our Owner is null");
                return(null);
            }
        }
        internal static IHtmlContent GenerateHtml <TModel>(
            IHtmlHelper <TModel> htmlHelper,
            Expression <Func <TModel, string> > propertyLambdaExpression,
            int?rows = null,
            LabelViewModel labelOptions         = null,
            HintViewModel hintOptions           = null,
            FormGroupViewModel formGroupOptions = null
            )
            where TModel : GovUkViewModel
        {
            PropertyInfo property = ExpressionHelpers.GetPropertyFromExpression(propertyLambdaExpression);

            string propertyName = property.Name;

            TModel model = htmlHelper.ViewData.Model;

            string currentValue = ExtensionHelpers.GetCurrentValue(model, property, propertyLambdaExpression);

            string id = $"GovUk_{propertyName}";

            if (labelOptions != null)
            {
                labelOptions.For = id;
            }

            var textAreaViewModel = new TextAreaViewModel
            {
                Name      = $"GovUk_Text_{propertyName}",
                Id        = id,
                Value     = currentValue,
                Rows      = rows,
                Label     = labelOptions,
                Hint      = hintOptions,
                FormGroup = formGroupOptions
            };

            if (model.HasErrorFor(property))
            {
                textAreaViewModel.ErrorMessage = new ErrorMessageViewModel {
                    Text = model.GetErrorFor(property)
                };
            }

            return(htmlHelper.Partial("/GovUkDesignSystemComponents/Textarea.cshtml", textAreaViewModel));
        }
        /// <summary>
        /// Lerps color of the given textmeshprougui component within speed (seconds)
        /// </summary>
        /// <param name="currentImage">Image with the color variable</param>
        /// <param name="targetColor">End color of the lerp</param>
        /// <param name="time">Time in seconds</param>
        /// <param name="owner">Class to run the lerp on</param>
        /// <returns></returns>
        public static TextMeshProUGUI LerpColor(this TextMeshProUGUI currentImage, Color targetColor, float time, MonoBehaviour owner)
        {
            if (currentImage == null)
            {
                return(null);
            }

            if (owner != null)
            {
                owner.StartCoroutine(ExtensionHelpers.LerpColor(currentImage, targetColor, time));
                return(currentImage);
            }
            else
            {
                Debug.Log("Our Owner is null");
                return(null);
            }
        }
Esempio n. 21
0
    public static Transform ActivateCoroutineLerpTransformPositions(Transform currentTransform, MonoBehaviour owner, Vector3 targetPosition, float speed)
    {
        if (currentTransform == null)
        {
            return(null);
        }

        if (owner != null)
        {
            owner.StartCoroutine(ExtensionHelpers.LerpTransformPositions(currentTransform, targetPosition, speed));
            return(currentTransform);
        }
        else
        {
            Debug.Log("Our Owner is null");
            return(null);
        }
    }
Esempio n. 22
0
        public void LoadData()
        {
            //Search for training data set files
            this._trainingDataSetFiles = Directory.GetFiles(this._pathToTrainingSet, "*.json", SearchOption.AllDirectories).ToArray();

            //Clear list with filereports
            _fileReports.Clear();

            //Append data to file reports
            foreach (var data in _trainingDataSetFiles)
            {
                IList <FileReportRecovered> list = ExtensionHelpers.ListFromJson(File.ReadAllText(data));
                _fileReports = _fileReports.Concat(list).ToList();
            }

            foreach (var item in _fileReports)
            {
                _fileReportsConverted.Add(item.ConvertML());
            }
        }
Esempio n. 23
0
        protected ServiceTypeDecoratorInfo GetServiceTypeInfo(Expression originalExpression,
                                                              InstanceProducer registeredProducer, Func <Type, InstanceProducer> producerBuilder)
        {
            Type registeredServiceType = registeredProducer.ServiceType;

            var predicateCache = this.ThreadStaticServiceTypePredicateCache;

            if (!predicateCache.ContainsKey(registeredProducer))
            {
                Type implementationType =
                    ExtensionHelpers.DetermineImplementationType(originalExpression, registeredProducer);

                var producer = producerBuilder(implementationType);

                predicateCache[registeredProducer] =
                    new ServiceTypeDecoratorInfo(registeredServiceType, implementationType, producer);
            }

            return(predicateCache[registeredProducer]);
        }
Esempio n. 24
0
 public BankAccountDetailsViewModel GetBankAccountDetails(int?id)
 {
     if (id != null)
     {
         var account = db.BankAccounts.Find(id);
         if (account != null)
         {
             return(new BankAccountDetailsViewModel(
                        ExtensionHelpers.GetCulture(User.Identity.GetCultureId(), User.Identity.GetNegFormatId()),
                        account.Balance,
                        account.NickName,
                        db.BankNames.Find(account.BankNameId).Name,
                        db.BankAccountTypes.Find(account.BankAccountTypeId).Name,
                        db.Users.Find(account.OwnerId).FullName,
                        id.Value,
                        GetBankAccountTransactions(account)
                        ));
         }
     }
     return(null);
 }
    public override void Merge(IConventionContext context, Convention convention)
    {
        if (convention is FilterConvention filterConvention &&
            Definition is not null &&
            filterConvention.Definition is not null)
        {
            ExtensionHelpers.MergeDictionary(
                Definition.Bindings,
                filterConvention.Definition.Bindings);

            ExtensionHelpers.MergeListDictionary(
                Definition.Configurations,
                filterConvention.Definition.Configurations);

            filterConvention.Definition.Operations.AddRange(Definition.Operations);

            filterConvention.Definition.ProviderExtensions.AddRange(
                Definition.ProviderExtensions);

            filterConvention.Definition.ProviderExtensionsTypes.AddRange(
                Definition.ProviderExtensionsTypes);

            if (Definition.ArgumentName != FilterConventionDefinition.DefaultArgumentName)
            {
                filterConvention.Definition.ArgumentName = Definition.ArgumentName;
            }

            if (Definition.Provider is not null)
            {
                filterConvention.Definition.Provider = Definition.Provider;
            }

            if (Definition.ProviderInstance is not null)
            {
                filterConvention.Definition.ProviderInstance = Definition.ProviderInstance;
            }
        }
    }
Esempio n. 26
0
 internal ContainerControlledItem[] GetClosedContainerControlledItemsFor(Type closedGenericServiceType)
 {
     return(ExtensionHelpers.GetClosedGenericImplementationsFor(closedGenericServiceType,
                                                                this.GetItemsFor(closedGenericServiceType)));
 }
Esempio n. 27
0
        static void Main(string[] args)
        {
            #region Load files
            string[]            jsonFiles    = Directory.GetFiles(DataHelper.MLDataPath, "*.json", SearchOption.AllDirectories).ToArray();
            IList <IFileReport> _fileReports = new List <IFileReport>();

            foreach (var file in jsonFiles)
            {
                IList <FileReportRecovered> list = ExtensionHelpers.ListFromJson(File.ReadAllText(file));
                _fileReports = _fileReports.Concat(list).ToList();
            }

            //Show saved classes
            string[] fileClasses = _fileReports
                                   .Select(x => x.Class)
                                   .Distinct()
                                   .ToArray();

            Console.WriteLine("Loaded {0} reports", _fileReports.Count);
            Console.WriteLine();
            #endregion
            #region Process
            foreach (string fileClass in fileClasses)
            {
                Console.WriteLine("File class: {0}", fileClass);

                var allClassReports = _fileReports
                                      .Select(x => x)
                                      .Where(x => x.Class == fileClass)
                                      .ToList();

                Console.WriteLine("Count: {0}", allClassReports.Count);
                Console.WriteLine();

                var mimeReports = allClassReports
                                  .Select(x => x)
                                  .GroupBy(x => x.MimeType);

                foreach (var classReports in mimeReports)
                {
                    Console.WriteLine("##########");
                    Console.WriteLine("Mimetype: {0}", classReports.FirstOrDefault().MimeType);
                    Console.WriteLine("Count: {0}", classReports.Count());
                    Console.WriteLine();

                    /// Save entropy

                    /*var entropys = classReports
                     *  .Select(x => x.Entropy)
                     *  .ToList();
                     * ///
                     *
                     * File.WriteAllText(classReports.Count() + ".txt", string.Join("; \n", entropys.ToArray()));*/

                    #region PE stats
                    //Stats about PE
                    var peStats32 = classReports
                                    .Where(x => x.Is32b == true);
                    Console.WriteLine("{0} 32b", peStats32.Count());

                    var peStats64 = classReports
                                    .Where(x => x.Is64b == true);
                    Console.WriteLine("{0} 64b", peStats64.Count());

                    var peStatsDLL = classReports
                                     .Where(x => x.IsDll == true)
                                     .Count();
                    Console.WriteLine("{0} DLL", peStatsDLL);

                    var peStatsExe = classReports
                                     .Where(x => x.IsExe == true)
                                     .Count();
                    Console.WriteLine("{0} EXE", peStatsExe - peStatsDLL);

                    var peStatsDotnet = classReports
                                        .Where(x => x.IsDotNet == true)
                                        .Count();
                    Console.WriteLine("{0} .NET", peStatsDotnet);

                    var peStatsDriver = classReports
                                        .Where(x => x.IsDriver == true)
                                        .Count();
                    Console.WriteLine("{0} Driver", peStatsDriver);

                    var peStatsSigned = classReports
                                        .Where(x => x.IsSigned == true)
                                        .Count();
                    Console.WriteLine("{0} Signed", peStatsSigned);
                    Console.WriteLine();

                    var peStatsNumberOfSections = classReports
                                                  .Where(x => x.Sections != null && x.Sections.Count() != 0)
                                                  .Select(x => x.Sections.Count());

                    if (peStatsNumberOfSections.Count() != 0)
                    {
                        Console.WriteLine("{0} Average number of sections", peStatsNumberOfSections.Average());
                        Console.WriteLine("{0} Media number of sections", Median(peStatsNumberOfSections.Select(x => Convert.ToDouble(x))));
                        Console.WriteLine("{0} SD of sections", CalculateStandardDeviation(peStatsNumberOfSections.Select(x => Convert.ToDouble(x))));
                    }
                    var peStatsMime = classReports
                                      .Select(x => x.MimeType)
                                      .GroupBy(x => x)
                                      .OrderByDescending(x => x.Count())
                                      .ToDictionary(g => g.Key, G => G.Count());

                    foreach (var stat in peStatsMime.Take(5))
                    {
                        Console.WriteLine("{0} {1}", stat.Value, stat.Key);
                    }

                    Console.WriteLine();

                    // Stats about DLL
                    var dllStats = classReports
                                   .Where(x => x.Imports != null && x.Imports.Keys != null)
                                   .SelectMany(x => x.Imports.Keys)
                                   .GroupBy(x => x, StringComparer.CurrentCultureIgnoreCase)
                                   .OrderByDescending(x => x.Count())
                                   .ToDictionary(g => g.Key, g => g.Count());

                    foreach (var stat in dllStats.Take(15))
                    {
                        Console.WriteLine("{0} {1}", stat.Value, stat.Key);
                    }

                    Console.WriteLine();

                    // Stats about functions
                    var methodStats = classReports
                                      .Where(x => x.Imports != null && x.Imports.Values != null)
                                      .SelectMany(x => x.Imports.Values)
                                      .SelectMany(x => x)
                                      .Where(x => x != null)
                                      .GroupBy(x => x, (x, group) => new { Key = x, Value = group.Count() }) // (x, group) => new { Value = x, Count = group.Count();
                                      .OrderByDescending(x => x.Value);


                    foreach (var stat in methodStats.Take(30))
                    {
                        Console.WriteLine("{1} {0}", (stat.Key.Length > 20) ? stat.Key.Substring(0, 15) + ".." : stat.Key, stat.Value);
                    }

                    Console.WriteLine();
                    #endregion
                    #region Behavior stats
                    // Stats about behavior
                    var behaviorStats = classReports
                                        .SelectMany(x => x.Behavior)
                                        .GroupBy(x => x)
                                        .OrderByDescending(x => x.Count())
                                        .ToDictionary(g => g.Key, g => g.Count());

                    foreach (var stat in behaviorStats.Take(15))
                    {
                        Console.WriteLine("{0} {1}", stat.Value, stat.Key);
                    }

                    Console.WriteLine();
                    #endregion
                    #region Entropy
                    var entropyAverage = classReports
                                         .Select(x => x.Entropy);

                    Console.WriteLine("Entropy average: {0}", entropyAverage.Average());
                    Console.WriteLine("Entropy median: {0}", Median(entropyAverage));
                    Console.WriteLine("Entropy standard deviation: {0}", CalculateStandardDeviation(entropyAverage));


                    var entropyStats = classReports
                                       .Select(x => x.Entropy)
                                       .GroupBy(x => Math.Round(x * 2, MidpointRounding.AwayFromZero) / 2)
                                       .ToDictionary(x => x.Key, x => x.Count())
                                       .OrderBy(x => x.Key);

                    foreach (var entropy in entropyStats)
                    {
                        Console.WriteLine("{0} {1}", entropy.Value, entropy.Key);
                    }
                    Console.WriteLine();
                    #endregion
                    #region String stats
                    //Stats about Strings
                    var stringsMail = classReports
                                      .Where(x => x.Mails.Count() > 0);
                    Console.WriteLine("{0} contains mail", stringsMail.Count());

                    var strinsIP = classReports
                                   .Where(x => x.IPAddrs.Count() > 0);
                    Console.WriteLine("{0} contains ip", strinsIP.Count());

                    var stringsUrls = classReports
                                      .Where(x => x.Urls.Count() > 0);
                    Console.WriteLine("{0} contains urls", stringsUrls.Count());

                    Console.WriteLine();
                    #endregion
                    #region VirusTotal
                    var virusTotalPostives = classReports
                                             .Where(x => x.PositiveTests > 0);
                    Console.WriteLine("{0} has positive tests", virusTotalPostives.Count());
                    #endregion
                }
                //Append new line
                Console.WriteLine();

                /*
                 * var a = allClassReports
                 *  .Where(x => x.MimeType == "application/x-dosexec")
                 *  .Where(x => !x.Is32b && !x.Is64b)
                 *  .Select(x => x.Filename);
                 *
                 * foreach(var b in a)
                 * {
                 *  Console.WriteLine(b);
                 * }*/
            }
            #endregion
        }
Esempio n. 28
0
        public MainWindow()
        {
            InitializeComponent();

            _drinkCategories = Enum.GetValues(typeof(DrinkCategories)).Cast <DrinkCategories>().Select(v => v.ToString()).ToList();
            _fruitTypes      = Enum.GetValues(typeof(FruitTypes)).Cast <FruitTypes>().Select(v => v.ToString()).ToList();
            _sodaTypes       = Enum.GetValues(typeof(SodaTypes)).Cast <SodaTypes>().Select(v => v.ToString()).ToList();
            _alcoholTypes    = Enum.GetValues(typeof(AlcoholTypes)).Cast <AlcoholTypes>().Select(v => v.ToString()).ToList();
            _juiceTypes      = Enum.GetValues(typeof(JuiceTypes)).Cast <JuiceTypes>().Select(v => ExtensionHelpers.ToFriendlyString(v)).ToList();

            ComboBox_DrinkCategories.ItemsSource = _drinkCategories;
            ListBox_Fruits.ItemsSource           = _fruitTypes;
        }
Esempio n. 29
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                throw new Exception("Missing parameter");
            }

            //Search for training data set files
            var jsonFiles = Directory.GetFiles(DataHelper.MLDataPath, "*.json", SearchOption.AllDirectories).ToArray();
            IList <IFileReport> _fileReports = new List <IFileReport>();

            string[] files = Directory
                             .GetFiles(args[0], "*", SearchOption.AllDirectories)
                             .OrderBy(f => new FileInfo(f).Length)
                             .ToArray();

            //Append data to file reports
            foreach (var data in jsonFiles)
            {
                IList <FileReportRecovered> list = ExtensionHelpers.ListFromJson(File.ReadAllText(data));
                _fileReports = _fileReports.Concat(list).ToList();
            }

            int i = 0;

            foreach (var file in files)
            {
                try
                {
                    var pefile = new PE(file);
                    var sha256 = new Hashes(file).ToString("sha256");
                    //Console.WriteLine("{0} - Signed {1} {2}", file, pefile.IsSigned(), sha256);

                    if (pefile.ISPeFile())
                    {
                        var val = _fileReports.FirstOrDefault(x => string.Compare(x.SHA256, sha256) == 0) as FileReportRecovered;
                        if (val != null && pefile != null)
                        {
                            i++;
                            val.IsSigned = pefile.IsSigned();

                            if (val.IsSigned == true)
                            {
                                val.SignIssuer  = pefile.GetSignIssuer();
                                val.SignSubject = pefile.GetSignSubject();
                            }

                            Console.WriteLine("{0}={1}", val.Filename, file);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0}", e);
                }
            }

            Console.WriteLine("Found files: {0} of {1}", i, files.Length);

            WriteToFile(_fileReports);
        }