Ejemplo n.º 1
0
    public JsonDataArray( JArray array, IDataHost host )
    {

      foreach ( var item in array.Select( item => JsonDataObject.ConvertValue( item, host ) ) )
        Add( item );

      _host = host;

    }
Ejemplo n.º 2
0
 //дописать десериализацию, тяжко
 private static List<Message> DeserializeMessages(JArray messagesArray)
 {
     DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
     List<Message> messagesList = messagesArray.Select(x => new Message
     {
         Id = (int)x["id"],
         Date = dtDateTime.AddSeconds((int)x["date"]).ToLocalTime(),
         Out = Boolean.Parse(x["out"].ToString()),
         UserId = (int)x["user_id"],
         ReadState = Boolean.Parse(x["read_state"].ToString()),
         Title = x["title"].ToString(),
         Body = x["body"].ToString(),
     }).ToList();
     return messagesList;
 }
Ejemplo n.º 3
0
 private static ShaMap ParseAccountState(JArray state)
 {
     var stateMap = new ShaMap();
     var entries = state.Select((t) =>
     {
         StObject so = t["json"];
         Assert.AreEqual(t["binary"].ToString(), so.ToHex(), t.ToString() + " " + so.ToJson());
         return new LedgerEntry(so);
     });
     foreach (var ledgerEntry in entries)
     {
         stateMap.AddItem(ledgerEntry.Index(), ledgerEntry);
     }
     return stateMap;
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Create a TreeNode and its subtrees for the <paramref name="obj"/> instance beeing a <see cref="JArray"/> instance.
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="depth"></param>
        /// <returns></returns>
        public static TreeNode Create(JArray obj, int depth)
        {
            var node = new JArrayTreeNode(obj);

            if (depth != 1)
            {
                int remainingDepth = (depth == UnlimitedDepth ? UnlimitedDepth : depth - 1);
                node.Nodes.AddRange(obj
                    .Select(o => Create((dynamic)o, remainingDepth))
                    .Cast<TreeNode>()
                    .ToArray()
                    );
            }

            return node;
        }
Ejemplo n.º 5
0
 public void Signatures(string name, JArray sig, bool isDER, bool isValid)
 {
     try
     {
         var derSig = sig.Select(x => (byte) x).ToArray();
         var s = ECDSASignature.FromDER(derSig);
         Assert.IsTrue(isValid);
     }
     catch (Exception e)
     {
         if (e is FormatException || e is EndOfStreamException)
             Assert.False(isValid);
         else
             Assert.Fail(name);
     }
 }
Ejemplo n.º 6
0
        private void AddMembersToParty(Party party, JArray members)
        {
            if (members == null) return;
            string[] items = members.Select(jv => (string)jv).ToArray();
            if (items.Length != party.Members.Length)
            {
                foreach (string member in items)
                {
                    PlayerCharacter character = Entity.GetEntity<Player>(Guid.Parse(member)).Character;

                    if (party.Leader == character) continue;

                    if (party.Members.Contains(character)) continue;
                    party.RemoveMember(character);
                }

                if (!items.Any())
                {
                    // Remove all members
                    foreach (PlayerCharacter member in party.Members)
                    {
                        if (party.Leader == member) continue;
                        party.RemoveMember(member);
                    }
                }
            }
            else
            {
                foreach (string entityId in items)
                {
                    PlayerCharacter groupmember = Entity.GetEntity<Player>(Guid.Parse(entityId)).Character;
                    Party groupMembersParty = Game.Zone.Parties.FirstOrDefault(x => x.Leader == groupmember);
                    party.RemoveInvite(groupMembersParty); // remove added Group from invites
                    party.MergeParty(groupMembersParty);
                }
            }
        }
Ejemplo n.º 7
0
 private List<Var> extractVars(JArray array) {
   if (array == null) {
     return new List<Var>();
   } else {
     return array.Select(obj => extractVar((JObject)obj)).ToList();
   }
 }
 public static List<MarketTrade> ParseMarketTrades(MarketId marketId, JArray tradesJson)
 {
     return tradesJson.Select(
         trade => ParseMarketTrade(marketId, (JObject)trade)
     ).ToList();
 }
Ejemplo n.º 9
0
        private FixtureOdds ParseFixtureOutcomes(JArray outcomes)
        {
            FixtureOdds res = null;
            foreach (var outcome in outcomes.Select(x => x.ToObjectOrDefault<JObject>()).Where(x => x != null))
            {
                var lbl = outcome.GetPropertyValue<string>("label");
                var odds = outcome.GetPropertyValue<double>("odds") / 1000;

                if (lbl == "1")
                {
                    res = res ?? new FixtureOdds();
                    res.HomeWin = odds;
                }
                else if (lbl == "X")
                {
                    res = res ?? new FixtureOdds();
                    res.Draw = odds;
                }
                else
                if (lbl == "2")
                {
                    res = res ?? new FixtureOdds();
                    res.AwayWin = odds;
                }
            }
            return res;
        }
Ejemplo n.º 10
0
        public void StartCreatingSModeCodeOperators(
            //input constants
           Dictionary<string, Dictionary<string, NomValue>> noms,
           List<JObject> sModeCodeOperators,
            //output
           ConcurrentDictionary<int, int> orgOperatorIdToLotId,
           ConcurrentDictionary<string, int> orgNamesEnToLotId,
           ConcurrentDictionary<int, JObject> orgLotIdToOrgNom,
            //cancellation
           CancellationTokenSource cts,
           CancellationToken ct)
        {
            try
            {
                this.sqlConnSCodes.Open();
            }
            catch (Exception)
            {
                cts.Cancel();
                throw;
            }

            foreach (JObject oper in sModeCodeOperators)
            {
                ct.ThrowIfCancellationRequested();

                try
                {
                    using (var dependencies = this.dependencyFactory())
                    {
                        var unitOfWork = dependencies.Value.Item1;
                        var lotRepository = dependencies.Value.Item2;
                        var caseTypeRepository = dependencies.Value.Item3;
                        var fileRepository = dependencies.Value.Item4;
                        var lotEventDispatcher = dependencies.Value.Item5;
                        var context = dependencies.Value.Item6;

                        List<NomValue> orgCaseTypes = new List<NomValue>() {
                            noms["organizationCaseTypes"].ByAlias("others")
                        };
                        string operName = oper.Get<string>("operatorName");
                        string operNameEN = oper.Get<string>("operatorNameEN");
                        string status = oper.Get<string>("status");
                        int operId = oper.Get<int>("operId");
                        string adrStr = oper.Get<string>("adrStr");
                        string adrCity = oper.Get<string>("adrCity");

                        int lotId;
                        Lot lotIndex;
                        if (operNameEN != null && orgNamesEnToLotId.ContainsKey(operNameEN))
                        {
                            orgOperatorIdToLotId.TryAdd(operId, orgNamesEnToLotId[operNameEN]);
                            lotId = orgNamesEnToLotId[operNameEN];
                        }
                        else if (orgNamesEnToLotId.ContainsKey(operName))
                        {
                            orgOperatorIdToLotId.TryAdd(operId, orgNamesEnToLotId[operName]);
                            lotId = orgNamesEnToLotId[operName];
                        }
                        else
                        {
                            var lot = lotRepository.CreateLot("Organization");

                            var organizationData = new
                            {
                                caseTypes = orgCaseTypes,
                                name = operName,
                                nameAlt = operName,
                                organizationKind = noms["organizationKinds"].ByCode("0"),
                                organizationType = noms["organizationTypes"].ByCode("N/A"),
                                valid = status == "1" ? noms["boolean"].ByCode("Y") : noms["boolean"].ByCode("N"),
                            };

                            lot.CreatePart("organizationData", organizationData, context);
                            lot.Commit(context, lotEventDispatcher);
                            unitOfWork.Save();
                            Console.WriteLine("Created organizationData part for organization smode code operator with name {0}", operName);

                            lotId = lot.LotId;

                            bool orgLotIdAdded = orgLotIdToOrgNom.TryAdd(lotId, Utils.ToJObject(
                                new
                                {
                                    nomValueId = lotId,
                                    name = operName,
                                    nameAlt = operNameEN ?? operName
                                }));

                            if (!orgLotIdAdded)
                            {
                                throw new Exception(string.Format("lotId {0} already present in orgLotIdToOrgNom dictionary", lotId));
                            }

                            if (!orgOperatorIdToLotId.ContainsKey(operId))
                            {
                                orgOperatorIdToLotId.TryAdd(operId, lotId);
                            }
                        }

                        string post = null;
                        string city = null;
                        if (!string.IsNullOrEmpty(adrCity))
                        {
                            var postCodeAndCity = new Regex(@"^(\D+)(\s)(\d+)$|^(\D+)$|^(\d+)(\s)(\D+)$");
                            Match match = postCodeAndCity.Match(adrCity);
                            if (match.Success)
                            {
                                post = !string.IsNullOrEmpty(match.Groups[3].Value) ? match.Groups[3].Value : match.Groups[5].Value;
                                city = !string.IsNullOrEmpty(match.Groups[1].Value) ? match.Groups[1].Value :
                                    (!string.IsNullOrEmpty(match.Groups[7].Value) ? match.Groups[7].Value : match.Groups[4].Value);
                            }
                        }

                        var settlement = !string.IsNullOrEmpty(city) ? noms["cities"].Where(v => v.Value.Name == city.Trim()).Select(v => v.Value).FirstOrDefault() : null;

                        lotIndex = lotRepository.GetLotIndex(lotId, fullAccess: true);
                        var partContent = Utils.ToJObject(new
                        {
                            __oldId = operId,
                            __migrTable = "sModeCodeOperatorAddress",
                            addressType = noms["addressTypes"].ByCode("TMP"),
                            valid = noms["boolean"].ByCode("Y"),
                            settlement = settlement,
                            postalCode = post,
                            address = string.Format("{0} {1}", adrStr, adrCity),
                            addressAlt = string.Format("{0} {1}", adrStr, adrCity)
                        });

                        PartVersion partVersion = null;
                        string caseTypeNomAlias = null;
                        if (lotIndex.Set.Alias == "Person")
                        {
                            partVersion  = lotIndex.CreatePart("personAddresses/*", partContent, context);
                            caseTypeNomAlias = "personCaseTypes";
                        }
                        else
                        {
                            partVersion = lotIndex.CreatePart("organizationAddresses/*", partContent, context);
                            caseTypeNomAlias = "organizationCaseTypes";
                        }

                        JArray files = new JArray(){
                            noms[caseTypeNomAlias].Values.Select(c =>
                                Utils.ToJObject(new
                                {
                                    isAdded = true,
                                    file = (object)null,
                                    caseType = Utils.ToJObject(c),
                                    bookPageNumber = (string)null,
                                    pageCount = (int?)null,
                                    applications =  new JArray()
                                }))
                            };
                        fileRepository.AddFileReferences(partVersion.Part, files.Select(f => f.ToObject<CaseDO>()));
                        unitOfWork.Save();
                        try
                        {
                            lotIndex.Commit(context, lotEventDispatcher);
                        }
                        //swallow the Cannot commit without modifications exception
                        catch (InvalidOperationException)
                        {
                        }
                        unitOfWork.Save();

                        Console.WriteLine("Migrated sModeCode operatorId : {0}", operId);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error in creation of organization with smode code operator name {0}", oper.Get<string>("operatorName"));
                    cts.Cancel();
                    throw;
                }
            }
        }
Ejemplo n.º 11
0
 static EdgeObjectState ParseObjectState(JArray items)
 {
     return ParseObjectState (items.Select(x=> (string)x).ToArray());
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Return array of optimized URLs
        /// </summary>
        /// <param name="fileRefs"></param>
        /// <param name="cdfType"></param>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected JArray GetOptimized(JArray fileRefs, ClientDependencyType cdfType, HttpContextBase httpContext)
        {
            var depenencies = fileRefs.Select(x =>
                {
                    var asString = x.ToString();
                    if (asString.StartsWith("/") == false)
                    {
                        if (Uri.IsWellFormedUriString(asString, UriKind.Relative))
                        {
                            var absolute = new Uri(httpContext.Request.Url, asString);
                            return new BasicFile(cdfType) { FilePath = absolute.AbsolutePath };
                        }
                        return null;
                    }
                    return new JavascriptFile(asString);
                }).Where(x => x != null);

            var urls = ClientDependencySettings.Instance.DefaultCompositeFileProcessingProvider.ProcessCompositeList(
                depenencies,
                cdfType,
                httpContext);

            var result = new JArray();
            foreach (var u in urls)
            {
                result.Add(u);
            }
            return result;
        }
 public static Field[] ParseFields(JArray a)
 {
     return a.Select(f =>
         {
             var fieldsArray = f.Value<JArray>("fields");
             if (fieldsArray == null)
             {
                 return new Field(f.Value<string>("name"), f.Value<string>("type"), f.Value<string>("mode"));
             }
             else
             {
                 return new Field(f.Value<string>("name"), f.Value<string>("type"), f.Value<string>("mode"), ParseFields(fieldsArray));
             }
         }).ToArray();
 }
Ejemplo n.º 14
0
 public void SetChemicalsData(JArray chemicalsData)
 {
     Chemicals = chemicalsData.Select(chemical => new JObject { { "ChemicalName", (string)chemical["ChemicalName"] }, { "ChemicalId", (string)chemical["ChemicalID"] } });
 }
Ejemplo n.º 15
0
        public void CanFollowGeneratedNavigationLinks(string acceptHeader)
        {
            //Arrange
            OneToOneParent[] entities = MetadataTestHelpers.CreateInstances<OneToOneParent[]>();
            OneToOneChild[] childEntities = entities.Select(x => x.Child).ToArray();
            JArray returnedChildEntities = new JArray();
            JArray returnedParentEntities;
            int[] returnedChildrenIdentities;
            string requestUrl = BaseAddress.ToLowerInvariant() + "/Relationships/OneToOneParent";
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
            request.SetAcceptHeader(acceptHeader);

            //Act
            HttpResponseMessage response = Client.SendAsync(request).Result;
            JObject result = response.Content.ReadAsJObject();          
            returnedParentEntities = (JArray)result["value"];
            for (int i = 0; i < returnedParentEntities.Count; i++)
            {
                string childUrl = (string)returnedParentEntities[i]["*****@*****.**"];
                HttpRequestMessage childRequest = new HttpRequestMessage(HttpMethod.Get, childUrl);
                HttpResponseMessage childResponse = Client.SendAsync(childRequest).Result;
                JObject childEntry = childResponse.Content.ReadAsJObject();
                returnedChildEntities.Add(childEntry);
            }
            returnedChildrenIdentities = returnedChildEntities.Select(x => (int)x["Id"]).ToArray();

            //Assert
            foreach (var returnedChildEntityId in returnedChildrenIdentities)
            {
                Assert.True(childEntities.Any(x => x.Id == returnedChildEntityId));
            }
        }
Ejemplo n.º 16
0
 private void AddOrRemoveInvites(Party party, JArray invites)
 {
     if (invites == null) return;
     string[] items = invites.Select(jv => (string)jv).ToArray();
     foreach (string entityId in items)
     {
         PlayerCharacter invite = Entity.GetEntity<Player>(Guid.Parse(entityId)).Character;
         Party partyOfInvitedMember =
             Game.Zone.Parties.FirstOrDefault(x => x.Members.Contains(invite) || x.Leader == invite);
         party.AddInvite(partyOfInvitedMember);
     }
 }
Ejemplo n.º 17
0
 private List<string> extractEffects(JArray array) {
   if (array == null) {
     return new List<string>();
   } else {
     return array.Select(obj => extractString(obj)).ToList();
   }
 }
Ejemplo n.º 18
0
 private List<Spell> extractSpells(JArray array) {
   return array.Select(obj => extractSpell((JObject)obj)).ToList();
 }
 /// <summary>
 /// Creates the fields list.
 /// </summary>
 /// <param name="fieldsArray">The fields array.</param>
 /// <returns>the fields list.</returns>
 private static List<MetadataField> CreateFieldsList(JArray fieldsArray)
 {
   return fieldsArray.Select(
     x => new MetadataField
     {
       FieldName = (string)x["fieldName"],
       DataType = (string)x["dataType"],
       Required = (bool)x["required"],
       Identity = (bool)x["identity"],
       Deprecated = (bool)x["deprecated"],
       Nullable = (bool)x["nullable"]
     }).ToList();
 }
Ejemplo n.º 20
0
 private void GenerateJoinRequests(PlayerCharacter groupLeader, JArray invites)
 {
     if (invites == null) return;
     foreach (string leaderid in invites.Select(y => (string)y).ToArray())
     {
         PlayerCharacter requestedGroupJoinLeader = Entity.GetEntity<Player>(Guid.Parse(leaderid)).Character;
         Party partyOfRequestedGroupJoinLeader = Game.Zone.Parties.FirstOrDefault(x => x.Leader == requestedGroupJoinLeader);
         Party ownParty = Game.Zone.Parties.FirstOrDefault(x => x.Leader == groupLeader);
         partyOfRequestedGroupJoinLeader?.AddJoinRequest(ownParty);
     }
 }
Ejemplo n.º 21
0
            /// <summary>
            /// Helper function to parse a <see cref="List{T}"/> of <see cref="Position"/>.
            /// </summary>
            /// <param name="array">
            /// Get JSON from this.
            /// </param>
            /// <returns>
            /// The parsed JSON.
            /// </returns>
            /// <exception cref="ArgumentException">
            /// Unexpected JSON.
            /// </exception>
            public static List<Position> ParseListPosition(JArray array)
            {
                if (array.Cast<JArray>().Any(l => l.Count < 2))
                {
                    throw new ArgumentException(
                    string.Format(
                    "Expected all points to have greater than two points, got {0} with zero and {1} with one",
                    array.Cast<JArray>().Count(l => l.Count == 0),
                    array.Cast<JArray>().Count(l => l.Count == 1)),
                    "array");
                }

                return array.Select(l => new Position(l)).ToList();
            }
Ejemplo n.º 22
0
 private List<object> extractArray(JArray array) {
   return array.Select(extractToken).ToList();
 }
Ejemplo n.º 23
0
    public SaveWorkState(ContextProvider contextProvider, JArray entitiesArray) {
      ContextProvider = contextProvider;
      var jObjects = entitiesArray.Select(jt => (dynamic)jt).ToList();
      var groups = jObjects.GroupBy(jo => (String)jo.entityAspect.entityTypeName).ToList();

      EntityInfoGroups = groups.Select(g => {
        var entityType = ContextProvider.LookupEntityType(g.Key);
        var entityInfos = g.Select(jo => ContextProvider.CreateEntityInfoFromJson(jo, entityType)).Cast<EntityInfo>().ToList();
        return new EntityGroup() { EntityType = entityType, EntityInfos = entityInfos };
      }).ToList();
    }
Ejemplo n.º 24
0
 public static IExpressionConstant Transform(JArray arr)
 {
     var list = arr.Select(el => Transform((dynamic) el))
         .Cast<IExpressionConstant>().ToList();
     return new ArrayValue(list);
 }
            /// <summary>
            /// Helper function to parse a <see cref="List{T}"/> of <see cref="List{T}"/> of <see cref="List{T}"/> of <see cref="Position"/>.
            /// </summary>
            /// <param name="array">
            /// Get JSON from this.
            /// </param>
            /// <returns>
            /// The parsed JSON.
            /// </returns>
            /// <exception cref="ArgumentException">
            /// Unexpected JSON.
            /// </exception>
            public static List<List<List<Position>>> ParseListListListPosition(JArray array)
            {
                if (array.Cast<JArray>().Any(p => p.Cast<JArray>().Any(r => r.Cast<JArray>().Any(l => l.Count < 2))))
                {
                    throw new ArgumentException(
                    string.Format(
                    "Expected all points to have greater than two points, got {0} with zero and {1} with one",
                    array.Cast<JArray>().Sum(p => p.Cast<JArray>().Sum(r => r.Cast<JArray>().Count(l => l.Count == 0))),
                    array.Cast<JArray>().Sum(p => p.Cast<JArray>().Sum(r => r.Cast<JArray>().Count(l => l.Count == 1)))),
                    "array");
                }

                return array.Select(p => p.Select(r => r.Select(l => new Position { P1 = (double)l[0], P2 = (double)l[1] }).ToList()).ToList()).ToList();
            }
Ejemplo n.º 26
0
 private IEnumerable<string> FormatStack(JArray stackTrace)
 {
     if (stackTrace != null)
     {
         return stackTrace.Select(f => FormatStackFrame(f as JObject)).ToList();
     }
     return null;
 }