private static async Task <IAccount> GetExpandedAccount(
            string href,
            IClient client,
            IReadOnlyDictionary <string, bool> expansionOptions,
            CancellationToken cancellationToken)
        {
            var options = new Action <IRetrievalOptions <IAccount> >(opt =>
            {
                // TODO retrieve collections when collection caching is in SDK: applications, groupMemberships, groups
                if (expansionOptions.Any(e => e.Key.Equals("customData", StringComparison.OrdinalIgnoreCase) && e.Value))
                {
                    opt.Expand(acct => acct.GetCustomData());
                }

                if (expansionOptions.Any(e => e.Key.Equals("directory", StringComparison.OrdinalIgnoreCase) && e.Value))
                {
                    opt.Expand(acct => acct.GetDirectory());
                }

                if (expansionOptions.Any(e => e.Key.Equals("providerData", StringComparison.OrdinalIgnoreCase) && e.Value))
                {
                    opt.Expand(acct => acct.GetProviderData());
                }

                if (expansionOptions.Any(e => e.Key.Equals("tenant", StringComparison.OrdinalIgnoreCase) && e.Value))
                {
                    opt.Expand(acct => acct.GetTenant());
                }
            });

            return(await client.GetAccountAsync(href, options, cancellationToken));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CategoricalCellValueFormat{TValue}"/> class.
        /// </summary>
        /// <param name="valueToTextMap">A dictionary of values mapped to the text to use to represent those values.</param>
        /// <param name="missingValueText">OPTIONAL text to use when the cell is missing a value.  DEFAULT is to leave this text unspecified.</param>
        public CategoricalCellValueFormat(
            IReadOnlyDictionary <TValue, string> valueToTextMap,
            string missingValueText = null)
            : base(missingValueText)
        {
            if (valueToTextMap == null)
            {
                throw new ArgumentNullException(nameof(valueToTextMap));
            }

            if (!valueToTextMap.Any())
            {
                throw new ArgumentException(Invariant($"{nameof(valueToTextMap)} is an empty dictionary."));
            }

            if (valueToTextMap.Any(_ => string.IsNullOrWhiteSpace(_.Value)))
            {
                throw new ArgumentException(Invariant($"{nameof(valueToTextMap)} contains at least one key-value pair with a null value."));
            }

            if (valueToTextMap.Values.Concat(new[] { missingValueText }).Distinct().Count() != (valueToTextMap.Count + 1))
            {
                throw new ArgumentException(Invariant($"{nameof(valueToTextMap)} Values and {nameof(missingValueText)} are not distinct."));
            }

            this.ValueToTextMap = valueToTextMap;
        }
    public FinalizedActionProcessingResults ProcessActions(SystemWideValues systemWideValues, IReadOnlyDictionary <LeagueYear, IReadOnlyList <PickupBid> > allActiveBids,
                                                           IReadOnlyDictionary <LeagueYear, IReadOnlyList <DropRequest> > allActiveDrops, IEnumerable <Publisher> publishers, Instant processingTime, IReadOnlyDictionary <Guid, MasterGameYear> masterGameYearDictionary)
    {
        var publisherStateSet = new PublisherStateSet(publishers);
        var flatBids          = allActiveBids.SelectMany(x => x.Value);
        var invalidBids       = flatBids.Where(x => x.CounterPick && x.ConditionalDropPublisherGame is not null);

        if (invalidBids.Any())
        {
            throw new Exception("There are counter pick bids with conditional drops.");
        }

        string processName  = $"Drop/Bid Processing ({processingTime.ToEasternDate()})";
        Guid   processSetID = Guid.NewGuid();

        if (!allActiveBids.Any() && !allActiveDrops.Any())
        {
            var emptyResults = ActionProcessingResults.GetEmptyResultsSet(publisherStateSet);
            return(new FinalizedActionProcessingResults(processSetID, processingTime, processName, emptyResults));
        }

        ActionProcessingResults dropResults = ProcessDrops(allActiveDrops, publisherStateSet, processingTime);

        if (!allActiveBids.Any())
        {
            return(new FinalizedActionProcessingResults(processSetID, processingTime, processName, dropResults));
        }

        ActionProcessingResults bidResults = ProcessPickupsIteration(systemWideValues, allActiveBids, dropResults, processingTime, masterGameYearDictionary);

        return(new FinalizedActionProcessingResults(processSetID, processingTime, processName, bidResults));
    }
        /// <summary>
        /// Builds and returns a <see cref="INameExpression" /> instance which can be used to generate name from the provided expression
        /// </summary>
        /// <param name="sportEvent">A <see cref="ISportEvent" /> instance representing associated sport @event</param>
        /// <param name="specifiers">A <see cref="IReadOnlyDictionary{String, String}" /> representing specifiers of the associated market</param>
        /// <param name="operator">A <see cref="string" /> specifying the operator for which to build the expression</param>
        /// <param name="operand">An operand for the built expression</param>
        /// <returns>The constructed <see cref="INameExpression" /> instance</returns>
        public INameExpression BuildExpression(ISportEvent sportEvent, IReadOnlyDictionary <string, string> specifiers, string @operator, string operand)
        {
            if (sportEvent == null)
            {
                throw new ArgumentNullException(nameof(sportEvent));
            }
            if (string.IsNullOrEmpty(operand))
            {
                throw new ArgumentNullException(nameof(operand));
            }

            if (@operator == null)
            {
                EnsureSpecifiersNotNullOrEmpty(specifiers);
                Contract.Assume(specifiers != null && specifiers.Any());
                return(new CardinalNameExpression(_operandFactory.BuildOperand(specifiers, operand)));
            }

            switch (Array.IndexOf(NameExpressionHelper.DefinedOperators, @operator))
            {
            case 0:     //+
            {
                EnsureSpecifiersNotNullOrEmpty(specifiers);
                Contract.Assume(specifiers != null && specifiers.Any());
                return(new PlusNameExpression(_operandFactory.BuildOperand(specifiers, operand)));
            }

            case 1:     //-
            {
                EnsureSpecifiersNotNullOrEmpty(specifiers);
                Contract.Assume(specifiers != null && specifiers.Any());
                return(new MinusNameExpression(_operandFactory.BuildOperand(specifiers, operand)));
            }

            case 2:     //$
            {
                return(BuildEntityNameExpression(operand, sportEvent));
            }

            case 3:     //!
            {
                EnsureSpecifiersNotNullOrEmpty(specifiers);
                Contract.Assume(specifiers != null && specifiers.Any());
                return(new OrdinalNameExpression(_operandFactory.BuildOperand(specifiers, operand)));
            }

            case 4:     //%
            {
                EnsureSpecifiersNotNullOrEmpty(specifiers);
                Contract.Assert(specifiers != null && specifiers.Any());
                return(new PlayerProfileExpression(_profileCache, _operandFactory.BuildOperand(specifiers, operand)));
            }

            default:
            {
                throw new ArgumentException($"Operator {@operator} is not supported. Supported operators are: {string.Join(",", NameExpressionHelper.DefinedOperators)}", nameof(@operator));
            }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SlottedCell"/> class.
        /// </summary>
        /// <param name="slotIdToCellMap">A map of the slot's id to the cell contained in the slot.</param>
        /// <param name="defaultSlotId">The id of the slot to use when initially rendering the tree table.</param>
        /// <param name="id">OPTIONAL unique identifier of the cell.  DEFAULT is a cell with no unique identifier.</param>
        /// <param name="columnsSpanned">OPTIONAL number of columns spanned or null if none (cell occupies a single column).  DEFAULT is none.</param>
        /// <param name="details">OPTIONAL details about the cell.  DEFAULT is to omit any details.</param>
        public SlottedCell(
            IReadOnlyDictionary <string, INotSlottedCell> slotIdToCellMap,
            string defaultSlotId,
            string id          = null,
            int?columnsSpanned = null,
            string details     = null)
            : base(id, columnsSpanned, details)
        {
            if (slotIdToCellMap == null)
            {
                throw new ArgumentNullException(nameof(slotIdToCellMap));
            }

            if (!slotIdToCellMap.Any())
            {
                throw new ArgumentException(Invariant($"{nameof(slotIdToCellMap)} is an empty dictionary."));
            }

            if (slotIdToCellMap.Any(_ => _.Value == null))
            {
                throw new ArgumentException(Invariant($"{nameof(slotIdToCellMap)} contains at least one key-value pair with a null value."));
            }

            if (slotIdToCellMap.Any(_ => string.IsNullOrWhiteSpace(_.Key)))
            {
                throw new ArgumentException(Invariant($"{nameof(slotIdToCellMap)} contains at least one key-value pair with a white space key."));
            }

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

            if (string.IsNullOrWhiteSpace(defaultSlotId))
            {
                throw new ArgumentException(Invariant($"{nameof(defaultSlotId)} is white space."));
            }

            if (!slotIdToCellMap.ContainsKey(defaultSlotId))
            {
                throw new ArgumentException(Invariant($"{nameof(slotIdToCellMap)} does not contain the specified {nameof(defaultSlotId)}."));
            }

            if (slotIdToCellMap.Values.Any(_ => (_.ColumnsSpanned ?? 1) != (columnsSpanned ?? 1)))
            {
                throw new ArgumentException(Invariant($"{nameof(slotIdToCellMap)} contains a cell that does not span the same number of columns as this cell."));
            }

            this.SlotIdToCellMap = slotIdToCellMap;
            this.DefaultSlotId   = defaultSlotId;
        }
 /// <summary>
 /// Ensures that the provided <see cref="IReadOnlyDictionary{String, String}"/> is not a null reference or empty dictionary
 /// </summary>
 /// <param name="specifiers">The <see cref="IReadOnlyDictionary{String, String}"/> to be checked.</param>
 private static void EnsureSpecifiersNotNullOrEmpty(IReadOnlyDictionary <string, string> specifiers)
 {
     if (specifiers == null || !specifiers.Any())
     {
         throw new ArgumentException("value cannot be a null reference or an empty dictionary", nameof(specifiers));
     }
 }
Esempio n. 7
0
 public GameStats(IReadOnlyDictionary <string, string> statdict)
 {
     if (statdict == null || !statdict.Any())
     {
         this.stats = new Dictionary <string, string>()
         {
             { "duels_won", "0" },
             { "duels_lost", "0" },
             { "ttt_won", "0" },
             { "ttt_lost", "0" },
             { "chain4_won", "0" },
             { "chain4_lost", "0" },
             { "caro_won", "0" },
             { "caro_lost", "0" },
             { "numraces_won", "0" },
             { "quizes_won", "0" },
             { "races_won", "0" },
             { "hangman_won", "0" }
         };
     }
     else
     {
         this.stats = statdict;
     }
 }
        private async Task DisplayInstalledTemplatePackages(INewCommandInput commandInput, CancellationToken cancellationToken)
        {
            _ = commandInput ?? throw new ArgumentNullException(nameof(commandInput));
            cancellationToken.ThrowIfCancellationRequested();

            IEnumerable <IManagedTemplatePackage> managedTemplatePackages = await _engineEnvironmentSettings.SettingsLoader.TemplatePackagesManager.GetManagedTemplatePackagesAsync().ConfigureAwait(false);

            Reporter.Output.WriteLine(LocalizableStrings.TemplatePackageCoordinator_Uninstall_Info_InstalledItems);

            if (!managedTemplatePackages.Any())
            {
                Reporter.Output.WriteLine(LocalizableStrings.NoItems);
                return;
            }

            foreach (IManagedTemplatePackage managedSource in managedTemplatePackages)
            {
                Reporter.Output.WriteLine($"{managedSource.Identifier}".Indent());
                if (!string.IsNullOrWhiteSpace(managedSource.Version))
                {
                    Reporter.Output.WriteLine($"{LocalizableStrings.Version} {managedSource.Version}".Indent(level: 2));
                }

                IReadOnlyDictionary <string, string> displayDetails = managedSource.GetDetails();
                if (displayDetails?.Any() ?? false)
                {
                    Reporter.Output.WriteLine(LocalizableStrings.TemplatePackageCoordinator_Uninstall_Info_DetailsHeader.Indent(level: 2));
                    foreach (KeyValuePair <string, string> detail in displayDetails)
                    {
                        Reporter.Output.WriteLine($"{detail.Key}: {detail.Value}".Indent(level: 3));
                    }
                }

                IEnumerable <ITemplateInfo> templates = await managedSource.GetTemplates(_engineEnvironmentSettings).ConfigureAwait(false);

                if (templates.Any())
                {
                    Reporter.Output.WriteLine($"{LocalizableStrings.Templates}:".Indent(level: 2));
                    foreach (TemplateInfo info in templates)
                    {
                        string templateLanguage = info.GetLanguage();
                        string shortNames       = string.Join(",", info.ShortNameList);
                        if (!string.IsNullOrWhiteSpace(templateLanguage))
                        {
                            Reporter.Output.WriteLine($"{info.Name} ({shortNames}) {templateLanguage}".Indent(level: 3));
                        }
                        else
                        {
                            Reporter.Output.WriteLine($"{info.Name} ({shortNames})".Indent(level: 3));
                        }
                    }
                }

                // uninstall command:
                Reporter.Output.WriteLine($"{LocalizableStrings.TemplatePackageCoordinator_Uninstall_Info_UninstallCommandHint}".Indent(level: 2));
                Reporter.Output.WriteCommand(commandInput.UninstallCommandExample(managedSource.Identifier));

                Reporter.Output.WriteLine();
            }
        }
Esempio n. 9
0
        /// <summary>Composing URL from base URL and parameters</summary>
        /// <param name="uri">Base URL</param>
        /// <param name="parameters">Parameters (key/values)</param>
        /// <returns>Composed URL</returns>
        public static Uri ComposeUri(this Uri uri, IReadOnlyDictionary <string, string> parameters)
        {
            Check.ArgumentIsNull(uri, "uri");
            Check.ArgumentIsNull(parameters, "parameters");
            Check.Argument(parameters.Any(), "parameters.Any()");

            var queryBuilder = new StringBuilder();

            foreach (var parameter in parameters)
            {
                if (parameter.Value == null)
                {
                    continue;
                }

                queryBuilder.Append("&");
                queryBuilder.Append(parameter.Key);
                queryBuilder.Append("=");
                queryBuilder.Append(WebUtility.UrlEncode(parameter.Value));
            }

            if (queryBuilder.Length > 0)
            {
                queryBuilder[0] = '?';
            }

            return(new Uri(uri, queryBuilder.ToString()));
        }
        /// <summary>
        ///     Returns items that can be cleaned up.
        /// </summary>
        /// <param name="items">
        ///     Available items for cleanup. Each dictionary item represents an image with specific key (uri). The value of the dictionary item is a list of concrete instances 
        ///     of the image ordered by image size, from smallest to largest.
        /// </param>
        /// <param name="itemSizeEvaluator">
        ///     The evaluator to use for calculation a size of the item in cache. The bigger this number, the heavier item in a cache, the less such items we
        ///     need to remove to free desired space.
        /// </param>
        /// <param name="sizeToFree">
        ///     The total size to free.
        /// </param>
        /// <returns>
        ///     The list of items that can be cleaned up.
        /// </returns>
        protected override IEnumerable<CacheImageLoader.CacheItem> GetItemsToCleanupInternal(IReadOnlyDictionary<string, List<CacheImageLoader.CacheItem>> items, Func<CacheImageLoader.CacheItem, ulong> itemSizeEvaluator, ulong sizeToFree)
        {
            var itemsToDelete = new List<CacheImageLoader.CacheItem>();

            if (items.Any())
            {
                var itemsGroupedByKeys = items.Values;
                var releasedSize = (ulong)0;

                var maxGroupSize = itemsGroupedByKeys.Max(v => v.Count);
                var currentSize = maxGroupSize;

                while (currentSize > 0 && releasedSize < sizeToFree)
                {
                    foreach (var item in from groupedItems in itemsGroupedByKeys
                                         where groupedItems.Count >= currentSize
                                         select groupedItems[groupedItems.Count - currentSize])
                    {
                        itemsToDelete.Add(item);
                        releasedSize += itemSizeEvaluator(item);

                        if (releasedSize >= sizeToFree)
                        {
                            break;
                        }
                    }

                    currentSize--;
                }
            }

            return itemsToDelete;
        }
Esempio n. 11
0
        private IReadOnlyDictionary <string, object> FilterProperties([NotNull] IReadOnlyDictionary <string, object> properties)
        {
            if (exceptions == null || exceptions.Count == 0)
            {
                return(properties);
            }

            if (!properties.Any(prop => exceptions.Contains(prop.Key)))
            {
                return(properties);
            }

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

            foreach (var prop in properties)
            {
                if (exceptions.Contains(prop.Key))
                {
                    continue;
                }

                filteredProperties[prop.Key] = prop.Value;
            }

            return(filteredProperties);
        }
        private static void ValidateDictionary(IReadOnlyDictionary <string, bool> sortDictionary, string sortOptions)
        {
            Assert.IsNotEmpty(sortDictionary);

            var array = sortOptions.Split(',').Where(x => !string.IsNullOrWhiteSpace(x) && x.NullTrim() != "-").ToList();

            Assert.AreEqual(sortDictionary.Count, array.Count);

            foreach (var iteration in array)
            {
                var propertyName = iteration;
                var asc          = true;

                if (iteration.StartsWith("-", StringComparison.Ordinal))
                {
                    propertyName = iteration.Remove(0, 1);
                    asc          = false;
                }

                if (_whitelist.Any() && _whitelist.TryGetValue(propertyName, out var value))
                {
                    propertyName = value;
                }

                Assert.IsTrue(sortDictionary.ContainsKey(propertyName));
                Assert.AreEqual(sortDictionary[propertyName], asc);
            }
        }
Esempio n. 13
0
 private static bool AllValuesSame(IReadOnlyDictionary <string, List <string> > x, IReadOnlyDictionary <string, List <string> > y)
 {
     return(!x.Any(kvp =>
                   !y.ContainsKey(kvp.Key) ||
                   !AllValuesSame(kvp.Value, y[kvp.Key])
                   ) && y.All(kvp => x.ContainsKey(kvp.Key)));
 }
Esempio n. 14
0
 public SessionRecorderDefinition(string name, IReadOnlyDictionary <string, object> configuration = null)
 {
     Name          = name;
     Configuration = configuration != null && configuration.Any()
                     ? new ReadOnlyDictionary <string, object>(configuration?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value, StringComparer.CurrentCultureIgnoreCase))
                     : EmptyConfiguration;
 }
Esempio n. 15
0
 public SessionDeviceDefinition(DeviceType device, IReadOnlyDictionary <string, object> configuration = null)
 {
     Device        = device;
     Configuration = configuration != null && configuration.Any()
                     ? new ReadOnlyDictionary <string, object>(configuration?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value, StringComparer.CurrentCultureIgnoreCase))
                     : EmptyConfiguration;
 }
Esempio n. 16
0
        private static (List <Position> positions, List <string> positionIdsChangedFromHistory) MapPositions(
            Dictionary <string, Position> blobPositions, IReadOnlyDictionary <string, IPositionHistory> positionSnapshots)
        {
            if (!positionSnapshots.Any())
            {
                return(blobPositions.Values.ToList(), new List <string>());
            }

            var changedIds = new List <string>();
            var result     = new List <Position>();

            foreach (var(id, position) in blobPositions)
            {
                if (positionSnapshots.TryGetValue(id, out var positionHistory) &&
                    position.Merge(positionHistory))
                {
                    if (positionHistory.HistoryType == PositionTerminalStatus)
                    {
                        continue;
                    }

                    changedIds.Add(id);
                }
                result.Add(position);
            }

            foreach (var(id, positionHistory) in positionSnapshots
                     .Where(x => !blobPositions.Keys.Contains(x.Key) && x.Value.HistoryType != PositionTerminalStatus))
            {
                changedIds.Add(id);
                result.Add(positionHistory.FromHistory());
            }

            return(result, changedIds);
        }
Esempio n. 17
0
        private Task CmdHelpAsync(SocketCommandContext context, CancellationToken cancellationToken = default)
        {
            using IDisposable logScope = _log.BeginCommandScope(context, this);
            PiholeOptions options = _piholeOptions.CurrentValue;
            IReadOnlyDictionary <string, PiholeInstanceOptions> instances = options.GetUserAuthorizedInstances(context.User);

            // check user is authorized to manage any instance
            if (instances?.Any() != true)
            {
                return(context.ReplyAsync($"{_einherjiOptions.CurrentValue.FailureSymbol} You are not authorized to manage any of Kathara PiHole instance.", cancellationToken));
            }

            string       prefix = _commandsOptions.CurrentValue.Prefix;
            EmbedBuilder embed  = new EmbedBuilder()
                                  .WithThumbnailUrl("https://upload.wikimedia.org/wikipedia/en/thumb/1/15/Pi-hole_vector_logo.svg/1200px-Pi-hole_vector_logo.svg.png")
                                  .WithDescription("Management utility for PiHoles present in Kathara network");

            embed.AddField("Commands",
                           $"**{prefix}pihole <instance id>** - show info on specific PiHole instance\n" +
                           $"**{prefix}pihole <instance id> enable** - enable a specific PiHole instance\n" +
                           $"**{prefix}pihole <instance id> disable** - disable a specific PiHole instance for {options.DefaultDisableTime.TotalMinutes} minutes\n" +
                           $"**{prefix}pihole <instance id> disable <minutes>** - disable a specific PiHole instance for custom amount of minutes\n" +
                           $"**{prefix}pihole** - display this message and check which instances you can manage");
            embed.AddField("Instances you can manage", string.Join(", ", instances.Keys));

            return(context.ReplyAsync(null, false, embed.Build(), cancellationToken));
        }
        /// <summary>
        /// Create new <see cref="ParameterValueSet"/> for a <see cref="Parameter"/>
        /// </summary>
        /// <param name="parameter">The <see cref="Parameter"/></param>
        /// <param name="actualOption">The actual <see cref="CDP4Common.DTO.Option"/></param>
        /// <param name="transaction">The current transaction</param>
        /// <param name="partition">The current partition</param>
        /// <param name="securityContext">The security context</param>
        /// <param name="newOldActualStateMap">The map that links the new <see cref="ActualFiniteState"/> to the old ones</param>
        /// <param name="oldValueSets">The old <see cref="ParameterValueSet"/></param>
        /// <param name="newOldValueSetMap">The map that links the new to old <see cref="ParameterValueSet"/></param>
        private void CreateParameterValueSets(Parameter parameter, Guid?actualOption, NpgsqlTransaction transaction, string partition, ISecurityContext securityContext, IReadOnlyDictionary <ActualFiniteState, ActualFiniteState> newOldActualStateMap, IReadOnlyList <ParameterValueSet> oldValueSets, ref Dictionary <ParameterValueSet, ParameterValueSet> newOldValueSetMap)
        {
            if (newOldActualStateMap == null || !newOldActualStateMap.Any())
            {
                // the parameter lost the state dependency
                var oldValueSet = oldValueSets.FirstOrDefault(x => x.ActualOption == actualOption);
                var newValueset = this.CreateParameterValueSet(oldValueSet, parameter, actualOption, null, transaction, partition, securityContext);
                newOldValueSetMap.Add(newValueset, oldValueSet);
                return;
            }

            foreach (var newOldStatePair in newOldActualStateMap)
            {
                ParameterValueSet oldValueSet;
                if (newOldStatePair.Value == null)
                {
                    oldValueSet = null;
                }
                else
                {
                    oldValueSet =
                        oldValueSets.SingleOrDefault(
                            x =>
                            x.ActualOption == actualOption &&
                            x.ActualState == newOldStatePair.Value.Iid);
                }

                var newValueSet = this.CreateParameterValueSet(oldValueSet, parameter, actualOption, newOldStatePair.Key.Iid, transaction, partition, securityContext);
                newOldValueSetMap.Add(newValueSet, oldValueSet);
            }
        }
Esempio n. 19
0
        public bool TryDetectAdvancedInstaller(IReadOnlyDictionary <string, string> buildValues, out BuildInfo buildInfo)
        {
            buildInfo = null;

            if (buildValues == null || !buildValues.Any())
            {
                return(false);
            }

            if (!buildValues.TryGetValue("AdvancedInstaller", out var advInst))
            {
                return(false);
            }

            buildValues.TryGetValue("ProjectLicenseType", out var projLic);
            buildInfo = new BuildInfo
            {
                ProductLicense = projLic,
                ProductName    = "Advanced Installer",
                ProductVersion = advInst
            };

            if (buildValues.TryGetValue("OperatingSystem", out var os))
            {
                var win10Version = Windows10Parser.GetOperatingSystemFromNameAndVersion(os);
                buildInfo.OperatingSystem = win10Version.ToString();
            }

            return(true);
        }
        public LineProtocolPoint(
            string measurement,
            IReadOnlyDictionary <string, object> fields,
            MetricTags tags,
            DateTime?utcTimestamp = null)
        {
            if (string.IsNullOrEmpty(measurement))
            {
                throw new ArgumentException("A measurement name must be specified");
            }

            if (fields == null || fields.Count == 0)
            {
                throw new ArgumentException("At least one field must be specified");
            }

            if (fields.Any(f => string.IsNullOrEmpty(f.Key)))
            {
                throw new ArgumentException("Fields must have non-empty names");
            }

            if (utcTimestamp != null && utcTimestamp.Value.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("Timestamps must be specified as UTC");
            }

            Measurement  = measurement;
            Fields       = fields;
            Tags         = tags;
            UtcTimestamp = utcTimestamp;
        }
Esempio n. 21
0
        public bool TryDetectMsixHero(IReadOnlyDictionary <string, string> buildValues, out BuildInfo buildInfo)
        {
            buildInfo = null;

            if (buildValues == null || !buildValues.Any())
            {
                return(false);
            }

            if (!buildValues.TryGetValue("MsixHero", out var msixHero))
            {
                return(false);
            }

            buildInfo = new BuildInfo
            {
                ProductName    = "MSIX Hero",
                ProductVersion = msixHero
            };

            if (buildValues.TryGetValue("OperatingSystem", out var os))
            {
                var win10Version = Windows10Parser.GetOperatingSystemFromNameAndVersion(os);
                buildInfo.OperatingSystem = win10Version.ToString();
            }

            return(true);
        }
Esempio n. 22
0
        public bool TryDetectVisualStudio(IReadOnlyDictionary <string, string> buildValues, out BuildInfo buildInfo)
        {
            buildInfo = null;

            if (buildValues == null || !buildValues.Any())
            {
                return(false);
            }

            if (!buildValues.TryGetValue("VisualStudio", out var visualStudio))
            {
                return(false);
            }

            buildInfo = new BuildInfo
            {
                ProductName    = "Microsoft Visual Studio",
                ProductVersion = visualStudio,
            };

            if (buildValues.TryGetValue("OperatingSystem", out var win10))
            {
                var firstUnit = win10.Split(' ')[0];
                buildInfo.OperatingSystem = Windows10Parser.GetOperatingSystemFromNameAndVersion(firstUnit).ToString();
                buildInfo.Components      = new Dictionary <string, string>(buildValues);
            }

            return(true);
        }
Esempio n. 23
0
        private static List <string> GetSupportedDrivePreferenceOrder(
            IEnumerable <string> drivePreferenceOrder, IReadOnlyDictionary <string, NamedCacheSettings> namedCaches, ILogger logger)
        {
            if (drivePreferenceOrder == null)
            {
                return(null);
            }

            var finalPreferenceOrder = new List <string>();

            foreach (string drive in drivePreferenceOrder)
            {
                if (namedCaches.Any(kvp =>
                                    kvp.Value.CacheRootPath.StartsWith(drive, StringComparison.OrdinalIgnoreCase)))
                {
                    finalPreferenceOrder.Add(drive);
                }
                else
                {
                    logger.Debug(
                        "Drive '{0}' in preference order was discarded, because its not supported by any named cache",
                        drive);
                }
            }

            return(finalPreferenceOrder);
        }
        /// <inheritdoc />
        public object Deserialize(IReadOnlyDictionary <string, string> serializedPropertyBag, Type type)
        {
            new { type }.Must().NotBeNull();

            if (serializedPropertyBag == null)
            {
                return(SerializationConfigurationBase.NullSerializedStringValue);
            }

            if (!serializedPropertyBag.Any())
            {
                if (type.HasParameterlessConstructor())
                {
                    return(type.Construct());
                }
                else
                {
                    throw new SerializationException(Invariant($"Found no properties for type {type} and it also does not have a parameterless constructor."));
                }
            }

            var ret = this.ConstructAndFillProperties(type, serializedPropertyBag);

            return(ret);
        }
Esempio n. 25
0
 public FieldValidationError(IReadOnlyDictionary <string, string> fieldErrors, ErrorCode code = ErrorCode.FieldValidation) : base(ErrorType.ValidationError.ToString(), "Request validation failed.", (int)code, fieldErrors)
 {
     if (!fieldErrors.Any())
     {
         throw new ArgumentException("You must give at least one field error.", nameof(fieldErrors));
     }
 }
        /// <summary>
        ///     Returns items that can be cleaned up.
        /// </summary>
        /// <param name="items">
        ///     Available items for cleanup. Each dictionary item represents an image with specific key (uri). The value of the dictionary item is a list of concrete instances
        ///     of the image ordered by image size, from smallest to largest.
        /// </param>
        /// <param name="itemSizeEvaluator">
        ///     The evaluator to use for calculation a size of the item in cache. The bigger this number, the heavier item in a cache, the less such items we
        ///     need to remove to free desired space.
        /// </param>
        /// <param name="sizeToFree">
        ///     The total size to free.
        /// </param>
        /// <returns>
        ///     The list of items that can be cleaned up.
        /// </returns>
        protected override IEnumerable <CacheImageLoader.CacheItem> GetItemsToCleanupInternal(IReadOnlyDictionary <string, List <CacheImageLoader.CacheItem> > items, Func <CacheImageLoader.CacheItem, ulong> itemSizeEvaluator, ulong sizeToFree)
        {
            var itemsToDelete = new List <CacheImageLoader.CacheItem>();

            if (items.Any())
            {
                var itemsGroupedByKeys = items.Values;
                var releasedSize       = (ulong)0;

                var maxGroupSize = itemsGroupedByKeys.Max(v => v.Count);
                var currentSize  = maxGroupSize;

                while (currentSize > 0 && releasedSize < sizeToFree)
                {
                    foreach (var item in from groupedItems in itemsGroupedByKeys
                             where groupedItems.Count >= currentSize
                             select groupedItems[currentSize - 1])
                    {
                        itemsToDelete.Add(item);
                        releasedSize += itemSizeEvaluator(item);

                        if (releasedSize >= sizeToFree)
                        {
                            break;
                        }
                    }

                    currentSize--;
                }
            }

            return(itemsToDelete);
        }
Esempio n. 27
0
        private static Dictionary <UnitType, int> _calcTargetAfterUnits(
            Dictionary <UnitType, int> atackerUnits,
            IReadOnlyDictionary <UnitType, int> defendorUnits,
            Dictionary <UnitType, Dictionary <BattleStatTypes, IBattleStatsDouble> > atakerMods,
            Dictionary <UnitType, Dictionary <BattleStatTypes, IBattleStatsDouble> > defendorMods)
        {
            if (!atackerUnits.Any())
            {
                return(defendorUnits.ToDictionary(i => i.Key, i => i.Value));
            }

            if (!defendorUnits.Any())
            {
                return(new Dictionary <UnitType, int>());
            }

            //tmp mods - need inject from outer data

            var atackUnits = atackerUnits.Where(i => i.Value > 0)
                             .Select(i => new BattleUnit(i.Key, i.Value, atakerMods))
                             .ToList();

            var defenceUnits = defendorUnits.Where(i => i.Value > 0)
                               .ToDictionary(i => i.Key, i => new BattleUnit(i.Key, i.Value, defendorMods));

            foreach (var unit in atackUnits)
            {
                unit.Atack(defenceUnits);
            }

            return(defenceUnits.ToDictionary(i => i.Key, i => i.Value.GetActiveCount()));
        }
Esempio n. 28
0
        private static void CheckTypesOfPropertiesAreRegistered(IReadOnlyContainer container, Type type, IReadOnlyCollection <PropertyInfo> properties,
                                                                IReadOnlyDictionary <Type, object> unknownTypes)
        {
            Check.ArgumentIsNull(container, nameof(container));
            Check.ArgumentIsNull(type, nameof(type));
            Check.ArgumentIsNull(properties, nameof(properties));
            Check.ArgumentIsNull(unknownTypes, nameof(unknownTypes));

            var typesOfProperties =
                properties
                .Select(p => p.PropertyType)
                .ToArray();

            var unregisteredPropertyTypes =
                typesOfProperties
                .Where(t => !container.Contains(t))
                .ToArray();

            var missedPropertyTypes =
                unregisteredPropertyTypes
                .Where(t => !unknownTypes.Any(kv => t.IsAssignableFrom(kv.Key)))
                .ToArray();

            if (missedPropertyTypes.Any())
            {
                var stringOfTypes = string.Join(",", missedPropertyTypes.Select(t => t.ToString()));
                throw new ContainerException($"The property types ({stringOfTypes}) of type '{type}' are not registered in the container or not passed as unknown instances.");
            }
        }
Esempio n. 29
0
        public async Task <InAppPurchaseHelper> Setup()
        {
            // license
            if (Simulate)
            {
#if DEBUG
                await SetupSimulation();

                m_License = CurrentAppSimulator.LicenseInformation;
                m_Listing = await CurrentAppSimulator.LoadListingInformationAsync();

                CanPurchase = true;
#endif
            }
            else
            {
                try
                {
                    m_License = CurrentApp.LicenseInformation;
                    m_Listing = await CurrentApp.LoadListingInformationAsync();

                    CanPurchase = true;
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Setup/License [{0}, {1}, {2}]", this.Key, this.Simulate, e.Message));
                    CanPurchase = false;
                }
            }

            if (!CanPurchase)
            {
                return(this); // :(
            }
            try
            {
                // test setup
                m_License.LicenseChanged += () => { RaiseLicenseChanged(IsPurchased); };
                IReadOnlyDictionary <string, ProductLicense> _Licenses = m_License.ProductLicenses;
                if (!_Licenses.Any(x => x.Key.Equals(Key, StringComparison.CurrentCultureIgnoreCase)))
                {
                    throw new KeyNotFoundException(Key);
                }

                IReadOnlyDictionary <string, ProductListing> _Products = m_Listing.ProductListings;
                if (!_Products.Any(x => x.Key.Equals(Key, StringComparison.CurrentCultureIgnoreCase)))
                {
                    throw new KeyNotFoundException(Key);
                }

                // product
                m_Product = _Products[Key];
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("Setup/Tests [{0}, {1}, {2}]", this.Key, this.Simulate, e.Message));
                CanPurchase = false;
            }
            return(this);
        }
Esempio n. 30
0
        public MetricsTextPoint(
            string measurement,
            IReadOnlyDictionary <string, object> fields,
            MetricTags tags,
            DateTime timestamp)
        {
            if (string.IsNullOrEmpty(measurement))
            {
                throw new ArgumentException("A measurement name must be specified");
            }

            if (fields == null || fields.Count == 0)
            {
                throw new ArgumentException("At least one field must be specified");
            }

            if (fields.Any(f => string.IsNullOrEmpty(f.Key)))
            {
                throw new ArgumentException("Fields must have non-empty names");
            }

            _timestamp = timestamp;

            Measurement = measurement;
            Fields      = fields;
            Tags        = tags;
        }
Esempio n. 31
0
        public static IEnumerable <(string SolutionFile, IReadOnlyDictionary <string, string> MissingProjects)> Execute(string targetDirectory, IEnumerable <string> lookupDirectories, bool fixSolutions)
        {
            IEnumerable <string> solutionsInDirectory = GetSolutionsInDirectory(targetDirectory);
            ConcurrentBag <(string SolutionFile, IReadOnlyDictionary <string, string> MissingProjects)> invalidSolutions = new ConcurrentBag <(string SolutionFile, IReadOnlyDictionary <string, string> MissingProjects)>();

            Parallel.ForEach(solutionsInDirectory, solutionFile =>
            {
                IReadOnlyDictionary <string, string> resultForSolution = EvaluateSolution(solutionFile);

                if (resultForSolution.Any())
                {
                    invalidSolutions.Add((solutionFile, resultForSolution));
                }
            }
                             );

            // Only incur this cost if we need to fix broken solutions
            if (fixSolutions && invalidSolutions.Any())
            {
                // THIS PROCESS IS EXPENSIVE; AVOID AT ALL COSTS!
                // At this point if we're going to fix the projects upload up our ProjectGuid Dictionary
                IReadOnlyDictionary <string, string> projectGuidLookup = LoadProjectGuids(lookupDirectories);

                Parallel.ForEach(invalidSolutions, invalidSolution =>
                {
                    FixSolution(invalidSolution.SolutionFile, invalidSolution.MissingProjects, projectGuidLookup);
                }
                                 );
            }

            return(invalidSolutions);
        }
 /// <summary>
 /// Determine if this device represents a Microsoft-provided HAL.
 /// </summary>
 /// <param name="properties"></param>
 /// <returns></returns>
 private static bool IsMicrosoftHal(IReadOnlyDictionary<string, object> properties)
 {
     return
         properties.Any(p => p.Value.ToString().Equals(HalDeviceClass) && p.Key.Equals(DeviceClassKey.Replace(',', ' '))) &&
         properties.Any(p => p.Key.Equals(DeviceDriverProviderKey.Replace(',', ' ')) && p.Value.Equals("Microsoft"));
 }
        public async Task<IRow[]> Query(IReadOnlyDictionary<string, string> columns)
        {
            if (null == columns)
            {
                throw new ArgumentNullException(CommaDelimitedFileAdapter.ArgumentNameColumns);
            }

            string query = 
                string.Format(
                    CultureInfo.InvariantCulture,
                    CommaDelimitedFileAdapter.QueryTemplate,
                    this.fileName);
            if (columns.Any())
            {
                IReadOnlyCollection<string> filters =
                    columns
                    .Select(
                        (KeyValuePair<string, string> item) =>
                            string.Format(
                                CultureInfo.InvariantCulture,
                                CommaDelimitedFileAdapter.FilterTemplate,
                                item.Key,
                                item.Value))
                    .ToArray();
                string filter =
                    string.Join(CommaDelimitedFileAdapter.DelimiterFilter, filters);

                query = string.Concat(query, CommaDelimitedFileAdapter.WhereClausePrefix, filter);
            }

            OleDbCommand commandQuery = null;
            try
            {
                commandQuery = new OleDbCommand(query, connection);
                DbDataReader reader = null;
                try
                {
                    reader = await commandQuery.ExecuteReaderAsync();
                    IList<IRow> rows = new List<IRow>();

                    while (reader.Read())
                    {
                        string rowKey = (string)reader[0];
                        Dictionary<string, string> rowColumns = 
                            new Dictionary<string, string>(this.headers.Count - 1);
                        for (int indexColumn = 1; indexColumn < this.headers.Count; indexColumn++)
                        {
                            string columnValue = reader[indexColumn] as string;
                            if (string.IsNullOrWhiteSpace(columnValue))
                            {
                                continue;
                            }

                            string columnHeader = this.headers.ElementAt(indexColumn);

                            rowColumns.Add(columnHeader, columnValue);
                        }

                        IRow row = new Row(rowKey, rowColumns);
                        rows.Add(row);
                    }

                    IRow[] results = rows.ToArray();
                    return results;
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                        reader = null;
                    }
                }
            }
            finally
            {
                if (commandQuery != null)
                {
                    commandQuery.Dispose();
                    commandQuery = null;
                }
            }
        }