Example #1
0
 private static async Task SendMassMessage(string sender, byte[] message)
 {
     await Task.Run(() =>
     {
         foreach (var client in Clients.Values.ToArray())
         {
             try
             {
                 client.RefreshMainChat(sender, message);
             }
             catch (Exception e)
             {
                 Console.WriteLine(e.Message);
                 try
                 {
                     Console.WriteLine(Clients.Single(c => c.Value == client).Key);
                 }
                 catch (Exception ee)
                 {
                     Console.WriteLine(ee.Message);
                 }
             }
         }
     });
 }
Example #2
0
        public async Task EndTrivia(User winner)
        {
            _client.MessageReceived -= CheckTrivia;
            await Channel.SendMessage($"Trivia over, {winner.Name} has won with {_scoreboard.Single(kv => kv.Key == winner.Id).Value} points.");

            _client.GetTrivias().Remove(this);
        }
        public PropertySetting GetGridDynamicColumnSetting(Func <IUnitOfWork> lazyLoadedUnitOfWork, string gridName, object instance)
        {
            var setting    = new PropertySetting();
            var gridColumn = _gridDynamicColumns.SingleOrDefault(grid => grid.Key == gridName);

            if (gridColumn.Value != null)
            {
                if (gridColumn.Value.TimeStamp.AddHours(1) >= DateTime.Now)
                {
                    return new PropertySetting
                           {
                               AdditionPropertyDictionary = GetDynamicFieldAndAssignValue(lazyLoadedUnitOfWork, gridName, instance),
                               Properties = gridColumn.Value.StaticColumns,
                           }
                }
                ;

                GridDynamicColumn dynamicColumn;
                _gridDynamicColumns.TryRemove(gridName, out dynamicColumn);
                return(new PropertySetting
                {
                    AdditionPropertyDictionary = GetDynamicFieldAndAssignValue(lazyLoadedUnitOfWork, gridName, instance),
                    Properties = gridColumn.Value.StaticColumns,
                });
            }

            setting.AdditionPropertyDictionary = GetDynamicFieldAndAssignValue(lazyLoadedUnitOfWork, gridName, instance);
            setting.Properties = _gridDynamicColumns.Single(o => o.Key == gridName).Value.StaticColumns;
            return(setting);
        }
        public void RemoveConnection(CommunicationHandler communicationHandler)
        {
            var id = connections.Single(e => e.Value.Item1 == communicationHandler).Key;

            Tuple <CommunicationHandler, string> value;

            connections.TryRemove(id, out value);
        }
Example #5
0
        internal static void UnregisterEnumTypeGlobally <TEnum>() where TEnum : struct
        {
            var pgName = _globalEnumRegistrations
                         .Single(kv => kv.Value is EnumHandler <TEnum>)
                         .Key;
            TypeHandler _;

            _globalEnumRegistrations.TryRemove(pgName, out _);
        }
Example #6
0
    public override Task OnDisconnected(bool stopCalled)
    {
        RetainedApplication temp;
        var applicationId = RetainedApplications.Single(x => x.Value.ConnectionId == Context.ConnectionId).Key;

        RetainedApplications.TryRemove(applicationId, out temp);
        Clients.All.applicationReleased(applicationId);
        return(base.OnDisconnected(stopCalled));
    }
        private static object InvokeDotNetMethodCore(string registration, string callbackId, string methodArguments)
        {
            if (!ResolvedFunctions.TryGetValue(registration, out var registeredFunction))
            {
                throw new InvalidOperationException($"No method exists with registration number '{registration}'.");
            }

            if (!(registeredFunction is Func <string, object> invoker))
            {
                throw new InvalidOperationException($"The registered invoker has the wrong signature.");
            }

            var result = invoker(methodArguments);

            if (callbackId != null && !(result is Task))
            {
                var methodSpec = ResolvedFunctionRegistrations.Single(kvp => kvp.Value == registration);
                var options    = JsonUtil.Deserialize <MethodInvocationOptions>(methodSpec.Key);
                throw new InvalidOperationException($"'{options.Method.Name}' in '{options.Type.Name}' must return a Task.");
            }

            if (result is Task && callbackId == null)
            {
                var methodSpec = ResolvedFunctionRegistrations.Single(kvp => kvp.Value == registration);
                var options    = JsonUtil.Deserialize <MethodInvocationOptions>(methodSpec.Key);
                throw new InvalidOperationException($"'{options.Method.Name}' in '{options.Type.Name}' must not return a Task.");
            }

            if (result is Task taskResult)
            {
                // For async work, we just setup the callback on the returned task to invoke the appropiate callback in JavaScript.
                SetupResultCallback(callbackId, taskResult);

                // We just return null here as the proper result will be returned through invoking a JavaScript callback when the
                // task completes.
                return(null);
            }
            else
            {
                return(result);
            }
        }
        /// <summary>
        /// Reads a schema from a JSON token.
        /// </summary>
        /// <param name="element">
        /// The element to parse.
        /// </param>
        /// <param name="cache">
        /// An optional schema cache. The cache is populated as the schema is read and can be used
        /// to provide schemas for certain names or cache keys.
        /// </param>
        /// <param name="scope">
        /// The surrounding namespace, if any.
        /// </param>
        public override Schema Read(JsonElement element, ConcurrentDictionary <string, Schema> cache, string scope)
        {
            if (GetType(element) != JsonSchemaToken.Map)
            {
                throw new UnknownSchemaException("The map case can only be applied to valid map schema representations.");
            }

            var child = Reader.Read(GetValues(element), cache, scope);
            var key   = cache.Single(p => p.Value == child).Key;

            return(cache.GetOrAdd($"{JsonSchemaToken.Map}<{key}>", _ => new MapSchema(child)));
        }
Example #9
0
        /// <summary>
        /// Reads a schema from a JSON token.
        /// </summary>
        /// <param name="token">
        /// The token to parse.
        /// </param>
        /// <param name="cache">
        /// An optional schema cache. The cache is populated as the schema is read and can be used
        /// to provide schemas for certain names or cache keys.
        /// </param>
        /// <param name="scope">
        /// The surrounding namespace, if any.
        /// </param>
        public override Schema Read(JToken token, ConcurrentDictionary <string, Schema> cache, string scope)
        {
            if (!(token is JObject @object && (string)token[JsonAttributeToken.Type] == JsonSchemaToken.Map))
            {
                throw new ArgumentException("The map case can only be applied to valid map schema representations.");
            }

            var child = Reader.Read(GetValues(@object), cache, scope);
            var key   = cache.Single(p => p.Value == child).Key;

            return(cache.GetOrAdd($"{JsonSchemaToken.Map}<{key}>", _ => new MapSchema(child)));
        }
Example #10
0
        /// <summary>
        /// Refreshes the Model objects when a change operation has been performed in the corresponding entity object
        /// </summary>
        /// <param name="affectedRecords">Records affected by last operation</param>
        /// <param name="dbEntityEntries">The affected entities</param>
        protected void OnSaveChangesHandler(int affectedRecords, List <DbEntityEntry> dbEntityEntries)
        {
            foreach (var sourceEntity in dbEntityEntries
                     .Select(t => t.Entity)
                     .ToList())
            {
                var modelToSync = syncDictionary.Single(x => ReferenceEquals(x.Value, sourceEntity)).Key;

                //It will Sync the values on Model from Entity
                modelToSync = (IModel)DataMapper.MapTo(sourceEntity, modelToSync);

                IEntity entity;
                syncDictionary.TryRemove(modelToSync, out entity);
            }
        }
Example #11
0
        /// <summary>
        /// Reads a schema from a JSON token.
        /// </summary>
        /// <param name="token">
        /// The token to parse.
        /// </param>
        /// <param name="cache">
        /// An optional schema cache. The cache is populated as the schema is read and can be used
        /// to provide schemas for certain names or cache keys.
        /// </param>
        /// <param name="scope">
        /// The surrounding namespace, if any.
        /// </param>
        public override Schema Read(JToken token, ConcurrentDictionary <string, Schema> cache, string scope)
        {
            if (!(token is JArray array))
            {
                throw new ArgumentException("The union case can only be applied to valid union schema representations.");
            }

            var children = array.Children()
                           .Select(c => Reader.Read(c, cache, scope))
                           .ToList();

            var keys = children
                       .Select(s => cache.Single(p => p.Value == s).Key);

            return(cache.GetOrAdd($"[{string.Join(",", keys)}]", _ => new UnionSchema(children)));
        }
Example #12
0
        /// <summary>
        /// Reads a schema from a JSON token.
        /// </summary>
        /// <param name="element">
        /// The element to parse.
        /// </param>
        /// <param name="cache">
        /// An optional schema cache. The cache is populated as the schema is read and can be used
        /// to provide schemas for certain names or cache keys.
        /// </param>
        /// <param name="scope">
        /// The surrounding namespace, if any.
        /// </param>
        public override Schema Read(JsonElement element, ConcurrentDictionary <string, Schema> cache, string scope)
        {
            if (element.ValueKind != JsonValueKind.Array)
            {
                throw new UnknownSchemaException("The union case can only be applied to valid union schema representations.");
            }

            var children = element
                           .EnumerateArray()
                           .Select(child => Reader.Read(child, cache, scope))
                           .ToList();

            var keys = children
                       .Select(s => cache.Single(p => p.Value == s).Key);

            return(cache.GetOrAdd($"[{string.Join(",", keys)}]", _ => new UnionSchema(children)));
        }
Example #13
0
        private static void ProcessLSTPseRelativeObjects(List <Pse_RelativeObject> pseRelativeObjects, List <PlanetSideObject> identifiableObjects, PlanetSideObject ownerObject, ref int id)
        {
            foreach (var line in pseRelativeObjects)
            {
                if (!_objectsWithGuids.Contains(line.ObjectName.ToLower()))
                {
                    continue;
                }
                Console.WriteLine($"Processing sub-object {line.ObjectName}");

                var uber = _ubrData.Single(x =>
                                           x.Value.Entries.Select(y => y.Name).Contains(line.ObjectName.ToLower()));
                var mesh = UBRReader.GetMeshSystem(line.ObjectName, uber.Value);

                var(relativeObjectRotX, relativeObjectRotY)  = MathFunctions.RotateXY(line.RelX, line.RelY, MathFunctions.DegreesToRadians(ownerObject.YawDegrees));
                (float x, float y, float z)relativeObjectPos = (relativeObjectRotX + ownerObject.AbsX, relativeObjectRotY + ownerObject.AbsY, line.RelZ + ownerObject.AbsZ);

                var relativeObjectRotationDegrees = MathFunctions.PS1RotationToDegrees((int)line.Yaw);

                // Process any sub-objects in the ubr file for this relative object (e.g. bfr_door within bfr_building ubr)
                foreach (var meshItem in mesh.PortalSystem.MeshItems)
                {
                    if (!_objectsWithGuids.Contains(meshItem.AssetName))
                    {
                        continue;
                    }

                    var subObjectRotationDegrees = MathFunctions.TransformToRotationDegrees(meshItem.Transform);

                    var(subObjectRotX, subObjectRotY) = MathFunctions.RotateXY(meshItem.Transform[12], meshItem.Transform[13], MathFunctions.DegreesToRadians(ownerObject.YawDegrees + relativeObjectRotationDegrees));
                    identifiableObjects.Add(new PlanetSideObject
                    {
                        Id            = id,
                        ObjectName    = meshItem.AssetName,
                        ObjectType    = meshItem.AssetName,
                        Owner         = ownerObject.Id,
                        AbsX          = relativeObjectPos.x + subObjectRotX,
                        AbsY          = relativeObjectPos.y + subObjectRotY,
                        AbsZ          = relativeObjectPos.z + line.RelZ,
                        IsChildObject = true
                    });
                    id++;
                }
            }
        }
Example #14
0
        /// <summary>
        /// Reads a schema from a JSON token.
        /// </summary>
        /// <param name="element">
        /// The element to parse.
        /// </param>
        /// <param name="cache">
        /// An optional schema cache. The cache is populated as the schema is read and can be used
        /// to provide schemas for certain names or cache keys.
        /// </param>
        /// <param name="scope">
        /// The surrounding namespace, if any.
        /// </param>
        public override IJsonSchemaReadResult Read(JsonElement element, ConcurrentDictionary <string, Schema> cache, string?scope)
        {
            var result = new JsonSchemaReadResult();

            if (GetType(element) == JsonSchemaToken.Array)
            {
                var child = Reader.Read(GetItems(element), cache, scope);
                var key   = cache.Single(p => p.Value == child).Key;

                result.Schema = cache.GetOrAdd($"{JsonSchemaToken.Array}<{key}>", _ => new ArraySchema(child));
            }
            else
            {
                result.Exceptions.Add(new UnknownSchemaException("The array case can only be applied to valid array schema representations."));
            }

            return(result);
        }
Example #15
0
        /// <summary>
        /// This happens when an app closes its connection normally.
        /// </summary>
        private async void OnTaskCancelled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            System.Diagnostics.Debug.WriteLine("MessageRelay was cancelled, removing " + _thisConnectionGuid + " from the list of active connections.");
            RemoveConnection(_thisConnectionGuid);

            if (Connections.Count == 1)
            {
                // Last open connection is the fulltrust process, lets close it
                // This should be done better and handle fulltrust process crashes
                var value = new ValueSet() { { "Arguments", "Terminate" } };
                await SendMessageAsync(Connections.Single(), value);
            }

            if (_backgroundTaskDeferral != null)
            {
                _backgroundTaskDeferral.Complete();
                _backgroundTaskDeferral = null;
            }
        }
 protected void SendClientResponse(ServiceBusMessage result, Action <dynamic, ServiceBusMessage> action)
 {
     ActionHelper.TryCatchWithLoggerGeneric(() =>
     {
         if (result == null)
         {
             _logger.WriteWarning(new LogMessage("SendClientResponse result is null"), LogCategories);
             return;
         }
         dynamic modeCommunication = Clients.All;
         if (string.IsNullOrEmpty(result.CorrelationId) || !_connections.Any(f => f.Value.Equals(result.CorrelationId)) || (modeCommunication = Clients.Client(_connections.Single(f => f.Value.Equals(result.CorrelationId)).Key)) == null)
         {
             _logger.WriteWarning(new LogMessage("SendClientResponse unknown correlationId. Setted broadcast mode communication"), LogCategories);
             modeCommunication = Clients.All;
         }
         else
         {
             _logger.WriteDebug(new LogMessage(string.Concat("SendClientResponse found CorrelationId identifier -> ", result.CorrelationId, ". Setted direct mode communication")), LogCategories);
         }
         action(modeCommunication, result);
     }, _logger, _logCategories);
 }
        private void ExternalServiceManagerOnExternalServiceUpdated(object sender, UpdatedItem <ExternalServiceData> e)
        {
            if (e.Item.Type != LightningNodeService.LightningNodeServiceType)
            {
                return;
            }
            if (_cancellationTokens.ContainsKey(e.Item.Id))
            {
                _cancellationTokens[e.Item.Id].Cancel();
            }
            switch (e.Action)
            {
            case UpdatedItem <ExternalServiceData> .UpdateAction.Added:
                _externalServices.TryAdd(e.Item.Id,
                                         new LightningNodeService(e.Item, _nbXplorerClientProvider, _nbXplorerSummaryProvider,
                                                                  _socketFactory));
                break;

            case UpdatedItem <ExternalServiceData> .UpdateAction.Removed:
                _externalServices.TryRemove(e.Item.Id, out var _);
                break;

            case UpdatedItem <ExternalServiceData> .UpdateAction.Updated:
                _externalServices.TryUpdate(e.Item.Id, new LightningNodeService(e.Item, _nbXplorerClientProvider,
                                                                                _nbXplorerSummaryProvider,
                                                                                _socketFactory), null);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            if (_externalServices.ContainsKey(e.Item.Id))
            {
                _ = ListenForPayment(_cts, _externalServices.Single(pair => pair.Key.Equals(e.Item.Id)));
            }
        }
 public void Dispose_CalledWheMultipleStreamsInTheSession_ExpectOnlyDisposedStreamIsRemovedFromTheSessionCollection()
 {
     var sessionCollection = new ConcurrentDictionary<Guid, IEventStream>();
     using (var nonDisposedStream = new NEventStoreSessionStream(sessionCollection, DummyEventStream()))
     {
         var stream = new NEventStoreSessionStream(sessionCollection, DummyEventStream());
         stream.Dispose();
         sessionCollection.Single().Value.Should().BeSameAs(nonDisposedStream);
     }
 }
Example #19
0
 private string GetPrivateKeyFromPublicKey(string publicKey)
 {
     return(_mapPublicKeyToPrivateKey.Single(p => p.Key == publicKey).Value);
 }
Example #20
0
 public TEntity GetEntityOf(TController controller)
 => _entityControllersCache.Single(pair => pair.Value.Equals(controller)).Key;
Example #21
0
        private string GetPrivateKeyFromConnectionId(Guid connectionId)
        {
            var publicKey = _mapConnectionsToPublicKey.Single(c => c.Key == connectionId).Value;

            return(GetPrivateKeyFromPublicKey(publicKey));
        }
Example #22
0
        private KeyValuePair <int, Server> GetLeader()
        {
            var leaderServer = _servers.Single(x => x.Value.Node.State is Leader);

            return(leaderServer);
        }
Example #23
0
 public ILBuilder GetIL(Func <IMethodSymbolInternal, bool> predicate)
 {
     return(Methods.Single(p => predicate(p.Key)).Value.ILBuilder);
 }
        public void ProcessGroundForcesWikiHtmlFiles(ConcurrentDictionary<string, HtmlDocument> vehicleWikiPagesContent, ConcurrentDictionary<string, string> localFileChanges, Dictionary<string, GroundVehicle> vehicleDetails, List<HtmlNode> vehicleWikiEntryLinks, List<string> errorsList, int indexPosition, int expectedNumberOfLinks, bool createJsonFiles, bool createHtmlFiles, bool createExcelFile)
        {
            try
            {
                _consoleManager.WriteLineInColour(ConsoleColor.Yellow, "Press ENTER to begin extracting data from the vehicle pages.");
                _consoleManager.WaitUntilKeyIsPressed(ConsoleKey.Enter);

                foreach (string vehicleWikiPageLinkTitle in vehicleWikiPagesContent.Keys)
                {
                    // Page to traverse
                    HtmlDocument vehicleWikiPage = vehicleWikiPagesContent.Single(x => x.Key == vehicleWikiPageLinkTitle).Value;
                    // Get the header that holds the page title | document.getElementsByClassName('firstHeading')[0].firstChild.innerText
                    HtmlNode pageTitle = vehicleWikiPage.DocumentNode.Descendants().Single(d => d.Id == "firstHeading").FirstChild;
                    // Get the div that holds all of the content under the title section | document.getElementById('bodyContent')
                    HtmlNode wikiBody = vehicleWikiPage.DocumentNode.Descendants().Single(d => d.Id == "bodyContent");
                    // Get the div that holds the content on the RHS of the page where the information table is | document.getElementById('bodyContent').getElementsByClassName('right-area')
                    HtmlNode rightHandContent = wikiBody.Descendants("div").SingleOrDefault(d => d.Attributes["class"] != null && d.Attributes["class"].Value.Contains("right-area"));

                    // Get the able that holds all of the vehicle information | document.getElementsByClassName('flight-parameters')[0]
                    HtmlNode infoBox = rightHandContent != null
                        ? rightHandContent.Descendants("table").SingleOrDefault(d => d.Attributes["class"].Value.Contains("flight-parameters"))
                        : null;

                    // Name
                    string vehicleName = _stringHelper.RemoveInvalidCharacters(System.Net.WebUtility.HtmlDecode(vehicleWikiPageLinkTitle));

                    // Link
                    HtmlNode urlNode = vehicleWikiEntryLinks.SingleOrDefault(v => v.InnerText.Equals(vehicleName));
                    string relativeUrl = urlNode != null
                        ? urlNode.Attributes["href"].Value.ToString()
                        : "";
                    string vehicleWikiEntryFullUrl = new Uri(new Uri(ConfigurationManager.AppSettings["BaseWikiUrl"]), relativeUrl).ToString();

                    // Fail fast and create error if there is no info box
                    if (infoBox == null)
                    {
                        _consoleManager.WriteLineInColour(ConsoleColor.Red, $"Error processing item {indexPosition} of {expectedNumberOfLinks}", false);
                        _consoleManager.WriteBlankLine();

                        errorsList.Add($"No Information found for '{vehicleName}' - {vehicleWikiEntryFullUrl}");

                        _consoleManager.ResetConsoleTextColour();
                        indexPosition++;
                        continue;
                    }
                    else
                    {
                        // Setup local vars
                        Dictionary<string, string> vehicleAttributes = new Dictionary<string, string>();
                        HtmlNodeCollection rows = infoBox.SelectNodes("tr");

                        _consoleManager.WriteTextLine($"The following values were found for {vehicleName}");

                        _webCrawler.GetAttributesFromInfoBox(vehicleAttributes, rows);

                        _consoleManager.ResetConsoleTextColour();

                        // Country
                        string countryRawValue = vehicleAttributes.Single(k => k.Key == "Country").Value.ToString();
                        CountryEnum vehicleCountry = _vehicleCountryHelper.GetVehicleCountryFromName(countryRawValue).CountryEnum;

                        // Weight
                        string weightRawValue = vehicleAttributes.Single(k => k.Key == "Weight").Value.ToString();
                        int weightWithoutUnits = int.Parse(Regex.Match(weightRawValue, @"\d+").Value);
                        string weightUnitsAbbreviation = (Regex.Matches(weightRawValue, @"\D+").Cast<Match>()).Last().Value.Trim();
                        VehicleWeightUnitHelper vehicleWeightUnit = _vehicleWeightUnitHelper.GetWeightUnitFromAbbreviation(weightUnitsAbbreviation);

                        // Vehicle class
                        string typeRawValue = vehicleAttributes.Single(k => k.Key == "Type").Value.ToString();
                        GroundVehicleTypeHelper vehicleType = _vehicleTypeHelper.GetGroundVehicleTypeFromName(typeRawValue);

                        // Rank
                        int rankRawValue = int.Parse(vehicleAttributes.Single(k => k.Key == "Rank").Value.ToString());
                        int vehicleRank = rankRawValue;

                        // Battle rating
                        double ratingRawValue = double.Parse(vehicleAttributes.Single(k => k.Key == "Rating").Value.ToString());
                        double vehicleBattleRating = ratingRawValue;

                        // Engine power
                        string enginePowerRawValue = vehicleAttributes.Single(k => k.Key == "Engine power").Value.ToString();
                        int enginePowerWithoutUnits = int.Parse(Regex.Match(enginePowerRawValue, @"\d+").Value);
                        string enginePowerUnitsAbbreviation = (Regex.Matches(enginePowerRawValue, @"\D+").Cast<Match>()).Last().Value.Trim();
                        VehicleEnginePowerUnitHelper vehicleEngineUnit = _vehicleEnginePowerUnitHelper.GetEngineUnitFromAbbreviation(enginePowerUnitsAbbreviation);

                        // Max speed
                        string maxSpeedRawValue = vehicleAttributes.Single(k => k.Key == "Max speed").Value.ToString();
                        double maxSpeedWithoutUnits = double.Parse(Regex.Match(maxSpeedRawValue, @"\d+\.*\d*").Value);
                        string maxSpeedUnits = (Regex.Matches(maxSpeedRawValue, @"\D+").Cast<Match>()).Last().Value.Trim();
                        VehicleSpeedUnitHelper vehicleSpeedUnit = _vehicleSpeedUnitHelper.GetSpeedUnitFromAbbreviation(maxSpeedUnits);

                        // Hull armour
                        string hullArmourRawValue = vehicleAttributes.Single(k => k.Key == "Hull armour thickness").Value.ToString();
                        string vehicleHullArmourThickness = hullArmourRawValue;

                        // Superstructure armour
                        string superstructureArmourRawValue = vehicleAttributes.Single(k => k.Key == "Superstructure armour thickness").Value.ToString();
                        string vehicleSuperstructureArmourThickness = superstructureArmourRawValue;

                        // Repair time
                        string freeRepairTimeRawValue = vehicleAttributes.Single(k => k.Key == "Time for free repair").Value.ToString();
                        List<Match> freeRepairTimeList = (Regex.Matches(freeRepairTimeRawValue, @"\d+").Cast<Match>()).ToList();
                        int freeRepairTimeHours = int.Parse(freeRepairTimeList.First().Value);
                        int freeRepairTimeMinutes = int.Parse(freeRepairTimeList.Last().Value);
                        TimeSpan vehicleFreeRepairTime = new TimeSpan(freeRepairTimeHours, freeRepairTimeMinutes, 0);

                        // Max repair cost
                        string maxRepairCostRawValue = vehicleAttributes.Single(k => k.Key == "Max repair cost*").Value.ToString();
                        string maxRepairCostWithoutUnits = Regex.Match(maxRepairCostRawValue, @"\d+").Value;
                        string maxRepairCostUnits = (Regex.Matches(maxRepairCostRawValue, @"\D+").Cast<Match>()).Last().Value.Trim();
                        long vehicleMaxRepairCost = long.Parse(maxRepairCostWithoutUnits);
                        VehicleCostUnitHelper vehicleRepairCostUnit = _vehicleCostUnitHelper.GetCostUnitFromAbbreviation(maxRepairCostUnits);

                        // Purchase cost
                        string purchaseCostRawValue = vehicleAttributes.Single(k => k.Key == "Cost*").Value.ToString();
                        string purchaseCostWithoutUnits = Regex.Match(purchaseCostRawValue, @"\d+").Value;
                        string purchaseCostUnits = (Regex.Matches(purchaseCostRawValue, @"\D+").Cast<Match>()).Last().Value.Trim();
                        long vehiclePurchaseCost = long.Parse(purchaseCostWithoutUnits);
                        VehicleCostUnitHelper vehiclePurchaseCostUnit = _vehicleCostUnitHelper.GetCostUnitFromAbbreviation(purchaseCostUnits);

                        // Last modified
                        HtmlNode lastModifiedSection = vehicleWikiPage.DocumentNode.Descendants().SingleOrDefault(x => x.Id == ConfigurationManager.AppSettings["LastModifiedSectionId"]);
                        string lastModified = lastModifiedSection?.InnerHtml;

                        // Populate objects
                        GroundVehicle groundVehicle = new GroundVehicle
                        {
                            Name = vehicleName,
                            Country = vehicleCountry,
                            Weight = weightWithoutUnits,
                            VehicleType = (VehicleTypeEnum)vehicleType.Id,
                            Rank = vehicleRank,
                            BattleRating = vehicleBattleRating,
                            EnginePower = enginePowerWithoutUnits,
                            MaxSpeed = maxSpeedWithoutUnits,
                            HullArmourThickness = vehicleHullArmourThickness,
                            SuperstructureArmourThickness = vehicleSuperstructureArmourThickness,
                            TimeForFreeRepair = vehicleFreeRepairTime,
                            MaxRepairCost = vehicleMaxRepairCost,
                            PurchaseCost = vehiclePurchaseCost,
                            PurchaseCostUnit = vehiclePurchaseCostUnit,
                            MaxRepairCostUnit = vehicleRepairCostUnit,
                            MaxSpeedUnit = vehicleSpeedUnit,
                            WeightUnit = vehicleWeightUnit,
                            EnginePowerUnit = vehicleEngineUnit,
                            LastModified = lastModified
                        };

                        // Update the local storage if requested
                        if (createJsonFiles)
                        {
                            _logger.UpdateLocalStorageForOfflineUse(localFileChanges, vehicleWikiPage, vehicleName, LocalWikiFileTypeEnum.JSON, groundVehicle);
                        }

                        if (createHtmlFiles)
                        {
                            _logger.UpdateLocalStorageForOfflineUse(localFileChanges, vehicleWikiPage, vehicleName, LocalWikiFileTypeEnum.HTML, null);
                        }

                        //WikiEntry entry = new WikiEntry(vehicleName, vehicleWikiEntryFullUrl, VehicleTypeEnum.Ground, vehicleInfo);

                        // Add the found information to the master list
                        vehicleDetails.Add(vehicleName, groundVehicle);

                        _consoleManager.WriteLineInColour(ConsoleColor.Green, $"Processed item {indexPosition} of {expectedNumberOfLinks} successfully");
                        _consoleManager.WriteBlankLine();
                    }

                    indexPosition++;
                }

                if (createExcelFile)
                {
                    _excelLogger.CreateExcelFile(vehicleDetails);
                }
            }
            catch (Exception ex)
            {
                _consoleManager.WriteException(ex.Message);
            }
        }
Example #25
0
        public void ProcessGroundForcesWikiHtmlFiles(ConcurrentDictionary <string, HtmlDocument> vehicleWikiPagesContent, ConcurrentDictionary <string, string> localFileChanges, Dictionary <string, GroundVehicle> vehicleDetails, List <HtmlNode> vehicleWikiEntryLinks, List <string> errorsList, int indexPosition, int expectedNumberOfLinks, bool createJsonFiles, bool createHtmlFiles, bool createExcelFile)
        {
            try
            {
                _consoleManager.WriteLineInColour(ConsoleColor.Yellow, "Press ENTER to begin extracting data from the vehicle pages.");
                _consoleManager.WaitUntilKeyIsPressed(ConsoleKey.Enter);

                foreach (string vehicleWikiPageLinkTitle in vehicleWikiPagesContent.Keys)
                {
                    // Page to traverse
                    HtmlDocument vehicleWikiPage = vehicleWikiPagesContent.Single(x => x.Key == vehicleWikiPageLinkTitle).Value;
                    // Get the header that holds the page title | document.getElementsByClassName('firstHeading')[0].firstChild.innerText
                    HtmlNode pageTitle = vehicleWikiPage.DocumentNode.Descendants().Single(d => d.Id == "firstHeading").FirstChild;
                    // Get the div that holds all of the content under the title section | document.getElementById('bodyContent')
                    HtmlNode wikiBody = vehicleWikiPage.DocumentNode.Descendants().Single(d => d.Id == "bodyContent");
                    // Get the div that holds the content on the RHS of the page where the information table is | document.getElementById('bodyContent').getElementsByClassName('right-area')
                    HtmlNode rightHandContent = wikiBody.Descendants("div").SingleOrDefault(d => d.Attributes["class"] != null && d.Attributes["class"].Value.Contains("right-area"));

                    // Get the able that holds all of the vehicle information | document.getElementsByClassName('flight-parameters')[0]
                    HtmlNode infoBox = rightHandContent?.Descendants("table").SingleOrDefault(d => d.Attributes["class"].Value.Contains("flight-parameters"));

                    // Name
                    string vehicleName = _stringHelper.RemoveInvalidCharacters(WebUtility.HtmlDecode(vehicleWikiPageLinkTitle));

                    // Link
                    HtmlNode urlNode                 = vehicleWikiEntryLinks.SingleOrDefault(v => v.InnerText.Equals(vehicleName));
                    string   relativeUrl             = urlNode?.Attributes["href"].Value ?? "";
                    string   vehicleWikiEntryFullUrl = new Uri(new Uri(ConfigurationManager.AppSettings["BaseWikiUrl"]), relativeUrl).ToString();

                    // Fail fast and create error if there is no info box
                    if (infoBox == null)
                    {
                        _consoleManager.WriteLineInColour(ConsoleColor.Red, $"Error processing item {indexPosition} of {expectedNumberOfLinks}", false);
                        _consoleManager.WriteBlankLine();

                        errorsList.Add($"No Information found for '{vehicleName}' - {vehicleWikiEntryFullUrl}");

                        _consoleManager.ResetConsoleTextColour();
                        indexPosition++;
                        continue;
                    }
                    else
                    {
                        // Setup local vars
                        Dictionary <string, string> vehicleAttributes = new Dictionary <string, string>();
                        HtmlNodeCollection          rows = infoBox.SelectNodes("tr");

                        _consoleManager.WriteTextLine($"The following values were found for {vehicleName}");

                        _webCrawler.GetAttributesFromInfoBox(vehicleAttributes, rows);

                        _consoleManager.ResetConsoleTextColour();

                        // Country
                        string      countryRawValue = vehicleAttributes.Single(k => k.Key == "Country").Value;
                        CountryEnum vehicleCountry  = _vehicleCountryHelper.GetVehicleCountryFromName(countryRawValue).CountryEnum;

                        // Weight
                        string weightRawValue                     = vehicleAttributes.Single(k => k.Key == "Weight").Value;
                        int    weightWithoutUnits                 = Int32.Parse(Regex.Match(weightRawValue, @"\d+").Value);
                        string weightUnitsAbbreviation            = (Regex.Matches(weightRawValue, @"\D+").Cast <Match>()).Last().Value.Trim();
                        VehicleWeightUnitHelper vehicleWeightUnit = _vehicleWeightUnitHelper.GetWeightUnitFromAbbreviation(weightUnitsAbbreviation);

                        // Vehicle class
                        string typeRawValue = vehicleAttributes.Single(k => k.Key == "Type").Value;
                        GroundVehicleTypeHelper vehicleType = _vehicleTypeHelper.GetGroundVehicleTypeFromName(typeRawValue);

                        // Rank
                        int rankRawValue = Int32.Parse(vehicleAttributes.Single(k => k.Key == "Rank").Value);
                        int vehicleRank  = rankRawValue;

                        // Battle rating
                        double ratingRawValue      = Double.Parse(vehicleAttributes.Single(k => k.Key == "Rating").Value);
                        double vehicleBattleRating = ratingRawValue;

                        // Engine power
                        string enginePowerRawValue                     = vehicleAttributes.Single(k => k.Key == "Engine power").Value;
                        int    enginePowerWithoutUnits                 = Int32.Parse(Regex.Match(enginePowerRawValue, @"\d+").Value);
                        string enginePowerUnitsAbbreviation            = (Regex.Matches(enginePowerRawValue, @"\D+").Cast <Match>()).Last().Value.Trim();
                        VehicleEnginePowerUnitHelper vehicleEngineUnit = _vehicleEnginePowerUnitHelper.GetEngineUnitFromAbbreviation(enginePowerUnitsAbbreviation);

                        // Max speed
                        string maxSpeedRawValue                 = vehicleAttributes.Single(k => k.Key == "Max speed").Value;
                        double maxSpeedWithoutUnits             = Double.Parse(Regex.Match(maxSpeedRawValue, @"\d+\.*\d*").Value);
                        string maxSpeedUnits                    = (Regex.Matches(maxSpeedRawValue, @"\D+").Cast <Match>()).Last().Value.Trim();
                        VehicleSpeedUnitHelper vehicleSpeedUnit = _vehicleSpeedUnitHelper.GetSpeedUnitFromAbbreviation(maxSpeedUnits);

                        // Hull armour
                        string hullArmourRawValue         = vehicleAttributes.Single(k => k.Key == "Hull armour thickness").Value;
                        string vehicleHullArmourThickness = hullArmourRawValue;

                        // Superstructure armour
                        string superstructureArmourRawValue         = vehicleAttributes.Single(k => k.Key == "Superstructure armour thickness").Value;
                        string vehicleSuperstructureArmourThickness = superstructureArmourRawValue;

                        // Repair time
                        string       freeRepairTimeRawValue = vehicleAttributes.Single(k => k.Key == "Time for free repair").Value;
                        List <Match> freeRepairTimeList     = (Regex.Matches(freeRepairTimeRawValue, @"\d+").Cast <Match>()).ToList();
                        int          freeRepairTimeHours    = Int32.Parse(freeRepairTimeList.First().Value);
                        int          freeRepairTimeMinutes  = Int32.Parse(freeRepairTimeList.Last().Value);
                        TimeSpan     vehicleFreeRepairTime  = new TimeSpan(freeRepairTimeHours, freeRepairTimeMinutes, 0);

                        // Max repair cost
                        string maxRepairCostRawValue                = vehicleAttributes.Single(k => k.Key == "Max repair cost*").Value;
                        string maxRepairCostWithoutUnits            = Regex.Match(maxRepairCostRawValue, @"\d+").Value;
                        string maxRepairCostUnits                   = (Regex.Matches(maxRepairCostRawValue, @"\D+").Cast <Match>()).Last().Value.Trim();
                        long   vehicleMaxRepairCost                 = Int64.Parse(maxRepairCostWithoutUnits);
                        VehicleCostUnitHelper vehicleRepairCostUnit = _vehicleCostUnitHelper.GetCostUnitFromAbbreviation(maxRepairCostUnits);

                        // Purchase cost
                        string purchaseCostRawValue     = vehicleAttributes.Single(k => k.Key == "Cost*").Value;
                        string purchaseCostWithoutUnits = Regex.Match(purchaseCostRawValue, @"\d+").Value;
                        string purchaseCostUnits        = (Regex.Matches(purchaseCostRawValue, @"\D+").Cast <Match>()).Last().Value.Trim();
                        long   vehiclePurchaseCost      = Int64.Parse(purchaseCostWithoutUnits);
                        VehicleCostUnitHelper vehiclePurchaseCostUnit = _vehicleCostUnitHelper.GetCostUnitFromAbbreviation(purchaseCostUnits);

                        // Last modified
                        HtmlNode lastModifiedSection = vehicleWikiPage.DocumentNode.Descendants().SingleOrDefault(x => x.Id == ConfigurationManager.AppSettings["LastModifiedSectionId"]);
                        string   lastModified        = lastModifiedSection?.InnerHtml;

                        // Populate objects
                        GroundVehicle groundVehicle = new GroundVehicle
                        {
                            Name                          = vehicleName,
                            Country                       = vehicleCountry,
                            Weight                        = weightWithoutUnits,
                            VehicleType                   = (VehicleTypeEnum)vehicleType.Id,
                            Rank                          = vehicleRank,
                            BattleRating                  = vehicleBattleRating,
                            EnginePower                   = enginePowerWithoutUnits,
                            MaxSpeed                      = maxSpeedWithoutUnits,
                            HullArmourThickness           = vehicleHullArmourThickness,
                            SuperstructureArmourThickness = vehicleSuperstructureArmourThickness,
                            TimeForFreeRepair             = vehicleFreeRepairTime,
                            MaxRepairCost                 = vehicleMaxRepairCost,
                            PurchaseCost                  = vehiclePurchaseCost,
                            PurchaseCostUnit              = vehiclePurchaseCostUnit,
                            MaxRepairCostUnit             = vehicleRepairCostUnit,
                            MaxSpeedUnit                  = vehicleSpeedUnit,
                            WeightUnit                    = vehicleWeightUnit,
                            EnginePowerUnit               = vehicleEngineUnit,
                            LastModified                  = lastModified
                        };

                        // Update the local storage if requested
                        if (createJsonFiles)
                        {
                            _logger.UpdateLocalStorageForOfflineUse(localFileChanges, vehicleWikiPage, vehicleName, LocalWikiFileTypeEnum.Json, groundVehicle);
                        }

                        if (createHtmlFiles)
                        {
                            _logger.UpdateLocalStorageForOfflineUse(localFileChanges, vehicleWikiPage, vehicleName, LocalWikiFileTypeEnum.Html);
                        }

                        //WikiEntry entry = new WikiEntry(vehicleName, vehicleWikiEntryFullUrl, VehicleTypeEnum.Ground, vehicleInfo);

                        // Add the found information to the master list
                        vehicleDetails.Add(vehicleName, groundVehicle);

                        _consoleManager.WriteLineInColour(ConsoleColor.Green, $"Processed item {indexPosition} of {expectedNumberOfLinks} successfully");
                        _consoleManager.WriteBlankLine();
                    }

                    indexPosition++;
                }

                if (createExcelFile)
                {
                    _excelLogger.CreateExcelFile(vehicleDetails);
                }
            }
            catch (Exception ex)
            {
                _consoleManager.WriteException(ex.Message);
            }
        }
 public Guid GetOwner(Guid compositeObjectId)
 {
     return(compositeObjectsByOwners.Single(entry => entry.Value.ContainsKey(compositeObjectId)).Key);
 }
 public void Constructor_Called_ExpectStreamAddsItselfToTheSessionCollection()
 {
     var sessionCollection = new ConcurrentDictionary<Guid, IEventStream>();
     using (var stream = new NEventStoreSessionStream(sessionCollection, DummyEventStream()))
     {
         sessionCollection.Single().Value.Should().BeSameAs(stream);
     }
 }
Example #28
0
 public TController GetControllerOf(TViewModel viewModel)
 => _controllersViewModelsCash.Single(pair => pair.Value.Equals(viewModel)).Key;