private List<ToDoItem> BuildList(List<ToDoItem> todoItems, JArray y)
 {
     foreach (var item in y.Children())
     {
         var itemProperties = item.Children<JProperty>();
         var element = itemProperties.FirstOrDefault(xx => xx.Name == "values");
         JProperty index = itemProperties.FirstOrDefault(xxx => xxx.Name == "index");
         JToken values = element.Value;
         var stringValues = from stringValue in values select stringValue;
         foreach (JToken thing in stringValues)
         {
             IEnumerable<string> rowValues = thing.Values<string>();
             string[] stringArray = rowValues.Cast<string>().ToArray();
             try
             {
                 ToDoItem todoItem = new ToDoItem(
                      Convert.ToInt32(index.Value),
                      stringArray[1],
                      stringArray[3],
                      stringArray[4],
                      stringArray[2],
                      stringArray[5],
                      stringArray[6],
                 stringArray[7]);
                 todoItems.Add(todoItem);
             }
             catch (FormatException f)
             {
                 Console.WriteLine(f.Message);
             }
         }
     }
     return todoItems;
 }
Пример #2
0
 /// <summary>
 /// Создать список объектов из json массива
 /// </summary>
 /// <param name="array"></param>
 /// <returns></returns>
 public static List<AbstractStorable> restoreArray(JArray array)
 {
     List<AbstractStorable> list = new List<AbstractStorable>();
     foreach (JObject obj in array.Children<JObject>())
     {
         list.Add(AbstractStorable.newInstance(obj));
     }
     return list;
 }
Пример #3
0
 /// <summary>
 /// Восстановить матрицу
 /// </summary>
 /// <param name="array"></param>
 /// <returns></returns>
 public static double[][] restoreMatrix(JArray array)
 {
     double[][] matrix = new double[array.Count][];
     int i = 0;
     foreach (JArray obj in array.Children<JArray>())
     {
         matrix[i] = restoreVector(obj);
         i++;
     }
     return matrix;
 }
Пример #4
0
        static void Main(string[] args)
        {
            string query = "select count(id) Enero from [apiDashboard].[dbo].[maFlow]   where DATEPART(month, payDatetime) = 01; select count(id) Febrero from [apiDashboard].[dbo].[maFlow]   where DATEPART(month, payDatetime) = 02";

            var client = new RestClient("http://localhost:64412/apiV1/");
            // client.Authenticator = new HttpBasicAuthenticator(username, password);

            var request = new RestRequest(string.Format("select?query={0}", query.Trim()), Method.GET);

            request.AddHeader("Accept", "application/json");
            request.AddHeader("CnnString", "RGF0YSBTb3VyY2U9Llxtc3NxbDIwMTQ7SW5pdGlhbCBDYXRhbG9nPWFwaURhc2hib2FyZDtQZXJzaXN0IFNlY3VyaXR5IEluZm89VHJ1ZTtVc2VyIElEPXNhO1Bhc3N3b3JkPWFz");
            request.AddHeader("Provider", "sqlserver");

            try
            {
                RestResponse response = client.Execute(request) as RestResponse;

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    dynamic data = JValue.Parse(response.Content);

                    if (data.REST_Service.Status_code.ToString() == "1")
                    {
                        foreach (dynamic item in data.Response)
                        {
                            Console.WriteLine("Command : {0}", item.Command.ToString());
                            JArray result = new JArray(item.Result);

                            foreach (JObject content in result.Children<JObject>())
                            {
                                foreach (JProperty prop in content.Properties())
                                {
                                    Console.WriteLine("{0} : {1}", prop.Name.ToString().Trim(), prop.Value.ToString().Trim());
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(data.REST_Service.Message.ToString());
                    }
                }
                else
                {
                    throw new Exception(response.StatusDescription);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Ocurrió un error [ {0} ]", ex.Message));
            }

            Console.ReadKey();
        }
        public static PatchDocument Load(JArray document) {
            var root = new PatchDocument();

            if (document == null)
                return root;

            foreach (var jOperation in document.Children().Cast<JObject>()) {
                var op = Operation.Build(jOperation);
                root.AddOperation(op);
            }

            return root;
        }
        /// <summary>
        /// Populates <paramref name="target"/> with values from <paramref name="source"/> and <paramref name="response"/>
        /// as defined by <paramref name="fieldMap"/>. It also returns a new <see cref="Newtonsoft.Json.Linq.JArray"/> with mapped values.
        /// </summary>
        /// <param name="source">The response body from which to get values.</param>
        /// <param name="response">The response object from which to get values.</param>
        /// <param name="fieldMap">A definition of field mappings.</param>
        /// <param name="target">The target object to populate with mapped key/values.</param>
        /// <param name="maxResults">The maximum number of results to return.</param>
        /// <returns>A new <see cref="Newtonsoft.Json.Linq.JArray"/> with mapped values.</returns>
        public JArray MapArray(JArray source, HttpWebResponse response, MappedFieldList fieldMap, ApplicationData target, int? maxResults = null)
        {
            int max = maxResults ?? int.MaxValue;
            JArray outArray = new JArray();
            IEnumerator<JObject> enumerator = source.Children<JObject>().GetEnumerator();
            int i = 0;
            while (enumerator.MoveNext() && i < max)
            {
                outArray.Add(this.MapObject(enumerator.Current, response, fieldMap, target));
                i++;
            }

            return outArray;
        }
Пример #7
0
        public static string GetFoxBoxscoreUrl(JArray scheduleJson, int awayTeamId, int homeTeamId)
        {
            var boxscoreUrl = string.Empty;

            foreach (var game in scheduleJson.Children())
            {
                if (game["AwayTeamId"].Value<int>() == awayTeamId && game["HomeTeamId"].Value<int>() == homeTeamId)
                {
                    var linksObj = game["Links"];
                    boxscoreUrl = linksObj["boxscore"].Value<string>();
                    break;
                }
            }

            return boxscoreUrl;
        }
Пример #8
0
        public MockedResultSet(JArray data, Func<JObject, bool> predicate = null, IEnumerable<JProperty> schema = null)
        {
            if (data == null)
            {
                Data = new JObject[0];
            }
            else
            {
                Data = data.Children().Cast<JObject>();
                if (predicate != null) Data = Data.Where(predicate);
            }

            if (schema == null && Data != null)
            {
                var list = Data.ToList();
                var first = list.FirstOrDefault();
                if (first != null) schema = first.Properties();
                Data = list;
            }
            Schema = schema;
        }
        public List<Forecast> ForecastsDataMapper(JObject jsonObject)
        {
            List<Forecast> forecasts = new List<Forecast>();

            JArray dataArray = new JArray(jsonObject["data"].Children());

            foreach (var item in dataArray.Children())
            {
                JObject itemJSON = JObject.Parse(item.ToString());

                Forecast forecast = new Forecast();

                forecast.ForecastDate = FieldMapperDateTime(itemJSON, "time");
                forecast.ForecastDateDisplay = forecast.ForecastDate.ToShortDateString();
                forecast.ForecastWeather = WeatherDataMapper(itemJSON, "summary", "temperatureMax");

                forecasts.Add(forecast);
            }

            return forecasts;
        }
        public List<Forecast> ForecastsDataMapper(JObject jsonObject)
        {
            List<Forecast> forecasts = new List<Forecast>();

            JArray dataArray = new JArray(jsonObject["forecastday"].Children());

            foreach (var item in dataArray.Children())
            {
                JObject itemJSON = JObject.Parse(item.ToString());

                Forecast forecast = new Forecast();

                forecast.ForecastDate = FieldMapperDateTime(JObject.Parse(itemJSON["date"].ToString()), "epoch");
                forecast.ForecastDateDisplay = forecast.ForecastDate.ToShortDateString();
                forecast.ForecastWeather = WeatherDataMapper(itemJSON, "conditions", "high", "fahrenheit");

                forecasts.Add(forecast);
            }

            return forecasts;
        }
        private void ReportInvalidStepValues(
            AnnotatedCodeLocation[] locations,
            JArray annotatedCodeLocationArray,
            string annotatedCodeLocationsPointer)
        {
            JObject[] annotatedCodeLocationObjects = annotatedCodeLocationArray.Children<JObject>().ToArray();

            for (int i = 0; i < locations.Length; ++i)
            {
                // Only report "invalid step value" for locations that actually specify
                // the "step" property (the value of the Step property in the object
                // model will be 0 for such steps, which is never valid), because we
                // already reported the missing "step" properties.
                if (LocationHasStep(annotatedCodeLocationObjects[i]) &&
                    locations[i].Step != i + 1)
                {
                    string invalidStepPointer = annotatedCodeLocationsPointer
                        .AtIndex(i).AtProperty(SarifPropertyName.Step);

                    LogResult(
                        invalidStepPointer,
                        nameof(RuleResources.SARIF009_InvalidStepValue),
                        (i + 1).ToInvariantString(),
                        (locations[i].Step).ToInvariantString());
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Get specified properties from an feed payload.
        /// </summary>
        /// <param name="feed">A feed.</param>
        /// <param name="elementName">An element name which is expected to get.</param>
        /// <returns>Returns a list of properties.</returns>
        public static List<JProperty> GetSpecifiedPropertiesFromFeedPayload(JArray feed, string elementName)
        {
            if (feed == null || elementName == null || elementName == string.Empty)
            {
                return props;
            }

            if (feed != null && feed.Type == JTokenType.Array)
            {
                foreach (JObject entry in feed.Children())
                {
                    props = GetSpecifiedPropertiesFromEntryPayload(entry, elementName);
                }
            }

            return props;
        }
Пример #13
0
        private static string GetStringFromArray(JArray array)
        {
            if (array.Count == 0)
                return "";

            bool isOneLine =
                array.Children()
                     .All(t => t.Type == JTokenType.Integer ||
                               t.Type == JTokenType.Float ||
                               t.Type == JTokenType.Boolean);
            if (isOneLine)
            {
                return string.Join(", ",
                                   array.Children().Select(c => c.ToString(Formatting.None)).ToArray());
            }
            else
            {
                return string.Join("\n",
                                   array.Children().Select(c => c.ToString(Formatting.None)).ToArray());
            }
        }
Пример #14
0
        public JArray translateToDisplayName(JArray array, string type)
        {
            var displayNames = crmService.GetAttributeDisplayName(type);
            var contactsWithDisplayNames = new JArray();

            foreach (var contact in array.Children<JObject>())
            {
                var newContact = new JObject();
                foreach (var keyValue in contact.Properties())
                {
                    if (displayNames.ContainsKey(keyValue.Name.ToString().ToLower()))
                    {
                        string displayName;
                        displayNames.TryGetValue(keyValue.Name.ToString().ToLower(), out displayName);

                        if (newContact.Property(displayName) == null)
                        {
                            newContact.Add(displayName, keyValue.Value);
                        }
                        else
                        {
                            newContact.Add(displayName + " 2", keyValue.Value);
                        }

                    }
                }
                contactsWithDisplayNames.Add(newContact);
            }

            return contactsWithDisplayNames;
        }
Пример #15
0
 /// <summary>
 /// Merge zweier Arrays
 /// </summary>
 /// <param name="iTarget"></param>
 /// <param name="iTemplate"></param>
 private void MergeTemplate(JArray iTarget, JArray iTemplate) {
     JsonMergeSettings lMergeSettings = new JsonMergeSettings();
     lMergeSettings.MergeArrayHandling = MergeArrayHandling.Union;
     if (iTemplate.First.Type == JTokenType.Array) {
         for (int i = 0; i < iTemplate.Count && i < iTarget.Count; i++) {
             //(iTarget[i] as JArray).Merge(iTemplate[i], lMergeSettings);
             //iTemplate[i].Remove();
             (iTemplate[i] as JArray).Merge(iTarget[i], lMergeSettings);
             iTarget[i].Remove();
         }
     }
     //iTarget.Merge(iTemplate, lMergeSettings);
     iTemplate.Merge(iTarget, lMergeSettings);
     iTarget.RemoveAll();
     iTarget.Add(iTemplate.Children());
 }
Пример #16
0
        // Assign price class to items
        public dynamic PostsalesdetailsPrice(JArray pPostedData)
        {
            var fitem = "";
            var fclass = "";

            foreach (JObject item in pPostedData.Children<JObject>())
            {
                fitem = item["fitem"].ToString();
                fclass = item["fpriceclass"].ToString();
                item["fprice"] = _db.itemsalesprices.Where(t => t.fitem == fitem && t.fclass == fclass).FirstOrDefault().fsaleprice;
            }

            return new
            {
                plist = pPostedData
            };
        }
 private IEnumerable<object[]> EnumerableOfArrays(JArray jarray)
 {
     foreach (var jtoken in jarray.Children())
     {
         if (jtoken.Type == JTokenType.Array)
         {
             yield return jtoken.Children().Select(t => t.ToObject<object>()).ToArray();
         }
         else
         {
             yield return new[] { jtoken.ToObject<object>() };
         }
     }
 }
Пример #18
0
        /// <summary>
        /// Parses a union token.
        /// </summary>
        /// <param name="unionToken">The union token.</param>
        /// <param name="parent">The parent.</param>
        /// <param name="namedSchemas">The named schemas.</param>
        /// <returns>
        /// Schema internal representation.
        /// </returns>
        /// <exception cref="System.Runtime.Serialization.SerializationException">Thrown when union schema type is invalid.</exception>
        private TypeSchema ParseUnionType(JArray unionToken, NamedSchema parent, Dictionary<string, NamedSchema> namedSchemas)
        {
            var types = new HashSet<string>();
            var schemas = new List<TypeSchema>();
            foreach (var typeAlternative in unionToken.Children())
            {
                var schema = this.Parse(typeAlternative, parent, namedSchemas);
                if (schema.Type == Token.Union)
                {
                    throw new SerializationException(
                        string.Format(CultureInfo.InvariantCulture, "Union schemas cannot be nested:'{0}'.", unionToken));
                }

                if (types.Contains(schema.Type))
                {
                    throw new SerializationException(
                        string.Format(CultureInfo.InvariantCulture, "Unions cannot contains schemas of the same type: '{0}'.", schema.Type));
                }

                types.Add(schema.Type);
                schemas.Add(schema);
            }

            return new UnionSchema(schemas, typeof(object));
        }
Пример #19
0
        public JArray TranslatePropertiesToDisplayName(JArray array, string type)
        {
            var displayNames = crmService.GetAttributeDisplayName(type).ToList();
            var contactsWithDisplayNames = new JArray();

            foreach (var contact in array.Children<JObject>())
            {
                var newContact = new JObject();
                foreach (var property in contact.Properties())
                {
                    var displayName = displayNames.SingleOrDefault(d => d.LogicalName == property.Name.ToLower());
                    if(displayName == null)
                        continue;

                    if (newContact.Property(displayName.DisplayName) == null)
                    {
                        newContact.Add(displayName.DisplayName, property.Value);
                    }
                    else
                    {
                        var suffix = 2;
                        while (newContact.Property(displayName.DisplayName + ' ' + suffix) != null)
                            suffix++;

                        newContact.Add(displayName.DisplayName + ' ' + suffix, property.Value);
                    }
                }
                contactsWithDisplayNames.Add(newContact);
            }

            return contactsWithDisplayNames;
        }
        private void ReportMissingStepProperty(
            JArray annotatedCodeLocationArray,
            string annotatedCodeLocationsPointer)
        {
            JObject[] annotatedCodeLocationObjects = annotatedCodeLocationArray.Children<JObject>().ToArray();
            if (annotatedCodeLocationObjects.Length > 0)
            {
                JObject[] locationsWithStep = GetLocationsWithStep(annotatedCodeLocationObjects);

                // It's ok if there are no steps, but if any location has a step property,
                // all locations must have it.
                if (locationsWithStep.Length > 0 &&
                    locationsWithStep.Length < annotatedCodeLocationObjects.Length)
                {
                    int missingStepIndex = FindFirstLocationWithMissingStep(annotatedCodeLocationObjects);
                    Debug.Assert(missingStepIndex != -1, "Couldn't find location with missing step.");

                    string missingStepPointer = annotatedCodeLocationsPointer.AtIndex(missingStepIndex);

                    LogResult(missingStepPointer, nameof(RuleResources.SARIF009_StepNotPresentOnAllLocations));
                }
            }
        }
Пример #21
0
        public void Children()
        {
            JArray a =
                new JArray(
                    5,
                    new JArray(1),
                    new JArray(1, 2),
                    new JArray(1, 2, 3)
                    );

            Assert.AreEqual(4, a.Count());
            Assert.AreEqual(3, a.Children<JArray>().Count());
        }
 public static QueryEntityVersionsRequest FromJArray(JArray jArray)
 {
     var constraints = jArray.Children().Select(child => JsonConvert.DeserializeObject<WireConstraint>(child.ToString())).ToList();
     return new QueryEntityVersionsRequest(constraints);
 }