Пример #1
1
        public JObject CreateEDDNMessage(JournalFSDJump journal)
        {
            if (!journal.HasCoordinate)
                return null;

            JObject msg = new JObject();

            msg["header"] = Header();
            msg["$schemaRef"] = "http://schemas.elite-markets.net/eddn/journal/1/test";

            JObject message = new JObject();

            message["StarSystem"] = journal.StarSystem;
            message["Government"] = journal.Government;
            message["timestamp"] = journal.EventTimeUTC.ToString("yyyy-MM-ddTHH:mm:ssZ");
            message["Faction"] = journal.Faction;
            message["Allegiance"] = journal.Allegiance;
            message["StarPos"] = new JArray(new float[] { journal.StarPos.X, journal.StarPos.Y, journal.StarPos.Z });
            message["Security"] = journal.Security;
            message["event"] = journal.EventTypeStr;
            message["Economy"] = journal.Economy;

            msg["message"] = message;
            return msg;
        }
Пример #2
1
 public ItemListStatic(JObject basicO,
     JObject dataO,
     JArray groupsA,
     JArray treeA,
     string type,
     string version,
     JObject originalObject)
 {
     data = new Dictionary<string, ItemStatic>();
     groups = new List<GroupStatic>();
     tree = new List<ItemTreeStatic>();
     if (basicO != null)
     {
         basic = HelperMethods.LoadBasicDataStatic(basicO);
     }
     if (dataO != null)
     {
         LoadData(dataO.ToString());
     }
     if (groupsA != null)
     {
         LoadGroups(groupsA);
     }
     if (treeA != null)
     {
         LoadTree(treeA);
     }
     this.type = type;
     this.version = version;
     this.originalObject = originalObject;
 }
 private static JToken SerializeRef(Ref reference)
 {
     var result = new JObject();
     result["$type"] = "ref";
     result["value"] = new JArray(reference.AsRef().Select(SerializationHelper.SerializeItem).ToList());
     return result;
 }
Пример #4
0
        public void BulkImport()
        {
            var collection = new JArray { null, null, null, null };
            var actual = Fixture().BulkImport(collection);

            Assert.NotNull(actual);
        }
Пример #5
0
        private string BuildOriginNumbersContent(Linq.JArray originNumbersObj)
        {
            Debug.Assert(originNumbersObj != null);
            string content = "";

            for (int iRow = 0; iRow < originNumbersObj.Count; ++iRow)
            {
                Linq.JArray lineArray = originNumbersObj[iRow] as Linq.JArray;
                Debug.Assert(lineArray != null);

                Debug.Assert(lineArray.Count == 10);

                string lineContent = "[";
                for (int iCol = 0; iCol < lineArray.Count; ++iCol)
                {
                    lineContent += lineArray[iCol].ToString();

                    if (iCol != lineArray.Count - 1)
                    {
                        lineContent += ", ";
                    }
                }

                lineContent += "]\n";
                content     += lineContent;
            }

            return(content);
        }
Пример #6
0
        private void PrintInfoToTabs(string jsonString)
        {
            if (jsonString == "")
            {
                return;
            }

            Linq.JObject jObj = Linq.JObject.Parse(jsonString);

            if (jObj == null)
            {
                System.Console.WriteLine("parse json result failed!");
                return;
            }

            Linq.JObject bigSmallAnalyzeResultJObj = jObj["BigSmall"] as Linq.JObject;
            BigSmallTabContent.Text = BuildAnalyzeTypeInfo(bigSmallAnalyzeResultJObj);


            Linq.JObject oddEvenAnalyzeResultJObj = jObj["OddEven"] as Linq.JObject;
            OddEvenTabContent.Text = BuildAnalyzeTypeInfo(oddEvenAnalyzeResultJObj);

            Linq.JObject numBigSmallAnalyzeResultJObj = jObj["NumBigSmall"] as Linq.JObject;
            NumBigSmallTabContent.Text = BuildAnalyzeTypeInfo(numBigSmallAnalyzeResultJObj);

            Linq.JObject numOddEvenAnalyzeResultJObj = jObj["NumOddEven"] as Linq.JObject;
            NumOddEvenTabContent.Text = BuildAnalyzeTypeInfo(numOddEvenAnalyzeResultJObj);

            Linq.JArray originNumbersObj = jObj["OriginNumbers"] as Linq.JArray;
            OriginNumbersTabContent.Text = BuildOriginNumbersContent(originNumbersObj);
        }
Пример #7
0
        public async static Task <bool> SendMessageAsync(string receiverId, string message)
        {
            try
            {
                AddResponse(receiverId, message);

                Newtonsoft.Json.Linq.JObject updateInformation = new Newtonsoft.Json.Linq.JObject();

                updateInformation.Add("SenderId", App.ViewModel.CurrentUser.InstallationId);
                updateInformation.Add("ReceiverId", receiverId);
                updateInformation.Add("Message", message);

                Newtonsoft.Json.Linq.JArray tags = new Newtonsoft.Json.Linq.JArray();

                tags.Add(receiverId);

                updateInformation.Add("Tags", tags);

                JToken result = await FavoritesManager.DefaultManager.CurrentClient.InvokeApiAsync("sendShortMessageToTag", updateInformation);
            }
            catch (Exception ex)
            {
            }

            return(true);
        }
Пример #8
0
 public static List<SysObj> Prep(JArray list)
 {
     SysObj sys = null;
     var setting = new JsonSerializerSettings();
     setting.NullValueHandling = NullValueHandling.Ignore;
     List<SysObj> systems = new List<SysObj>();
     List<SysObj> result = new List<SysObj>();
     for (int cnt = 0; cnt < list.Count; cnt++)
     {
         sys = JsonConvert.DeserializeObject<SysObj>(list[cnt].ToString(), setting);
         if (string.IsNullOrEmpty(sys.security))
             sys.security = "None";
         if (string.IsNullOrEmpty(sys.power))
             sys.power = "None";
         if (string.IsNullOrEmpty(sys.primary_economy))
             sys.primary_economy = "None";
         if (string.IsNullOrEmpty(sys.simbad_ref))
             sys.simbad_ref = "";
         if (string.IsNullOrEmpty(sys.power_state))
             sys.power_state = "None";
         if (string.IsNullOrEmpty(sys.state))
             sys.state = "None";
         if (string.IsNullOrEmpty(sys.allegiance))
             sys.allegiance = "None";
         if (string.IsNullOrEmpty(sys.government))
             sys.government = "None";
         if (string.IsNullOrEmpty(sys.faction))
             sys.faction = "None";
         if (sys.needs_permit.Equals(null))
             sys.needs_permit = 0;
         systems.Add(sys);
     }
     return systems;
 }
Пример #9
0
        public String GeneralBasicDemo(String file)
        {
            var image = File.ReadAllBytes(file);
            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            //var result = ocr.GeneralBasic(image);
            //Console.WriteLine(result);
            // 如果有可选参数
            var options = new Dictionary <string, object> {
                { "language_type", "CHN_ENG" },
                { "detect_direction", "true" },
                { "detect_language", "true" },
                { "probability", "true" }
            };
            // 带参数调用通用文字识别, 图片参数为本地图片
            var result = ocr.GeneralBasic(image, options);

            Console.WriteLine(result);
            String end = null;

            rt.log_id           = result["log_id"].ToString();
            rt.direction        = result["direction"].ToString();
            rt.words_result_num = Int32.Parse(result["words_result_num"].ToString());
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            jArray = result.Value <JArray>("words_result");
            JObject jObject;

            for (int i = 0; i < jArray.Count; i++)
            {
                jObject  = JObject.Parse(jArray[i].ToString());
                rt.words = rt.words + jObject["words"].ToString() + "\r\n";
            }
            return(rt.words);
        }
Пример #10
0
        /// <summary>
        ///     Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter" /> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var coordinateElements = value as List<IPosition>;
            if (coordinateElements != null && coordinateElements.Count > 0)
            {
                var coordinateArray = new JArray();

                foreach (var position in coordinateElements)
                {
                    // TODO: position types should expose a double[] coordinates property that can be used to write values 
                    var coordinates = (GeographicPosition)position;
                    var coordinateElement = new JArray(coordinates.Longitude, coordinates.Latitude);
                    if (coordinates.Altitude.HasValue)
                    {
                        coordinateElement = new JArray(coordinates.Longitude, coordinates.Latitude, coordinates.Altitude);
                    }

                    coordinateArray.Add(coordinateElement);
                }

                serializer.Serialize(writer, coordinateArray);
            }
            else
            {
                serializer.Serialize(writer, value);
            }
        }
Пример #11
0
        private List <object> QueryOneHopData(long from_cellid, string info, int hop_num)
        {
            List <object> ret = new List <object>();

            //Artists:Name(Performance:1&Gender:male
            string[] line          = info.Split(new char[] { '(' }, StringSplitOptions.RemoveEmptyEntries);
            string   edge_property = line[0];
            string   constrint     = (line.Count() == 2) ? line[1] : null;

            string[] edge_property_arr = edge_property.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
            string   edge     = edge_property_arr[0];
            string   property = edge_property_arr[1];

            string query_path = "\"/entity1/" + edge + "/entity2\"";

            string  request_body  = "{ \"path\": " + query_path + ",  \"entity1\" : {\n\t\"match\": { \"CellId\": " + from_cellid + " }  },  \"entity2\" : {\"select\": [ \"" + property + "\" ]  },}";
            var     json_response = ExecuteRequest(request_body);
            dynamic response      = JsonConvert.DeserializeObject(json_response.Content);

            Newtonsoft.Json.Linq.JArray response_res = response.Results;
            var paths = response_res.ToObject <List <List <Dictionary <string, object> > > >();

            foreach (var ress in paths)
            {
                ret.Add(ress[hop_num]["Name"]);
            }
            return(ret);
        }
Пример #12
0
        // TODO: Implement paging
        public async Task<AccountAddressContainer> GetAccountAddresses()
        {
            var url = GetAccountAddressesUrl();
            var response = await GetAuthenticatedResource(url);

            var addresses = 
                new JArray(response["addresses"]).SelectMany(t => t)
                .Select(a =>
                {
                    var currentAddress = a["address"];
                    var address = currentAddress["address"].Value<string>();
                    var callbackUrl = currentAddress["callback_url"].Value<string>();
                    var label = currentAddress["label"].Value<string>();
                    var createdAt = currentAddress["created_at"].Value<DateTime>();
                    
                    return new AccountAddress(address, callbackUrl, label, createdAt);
                });

            var totalCount = response["total_count"].Value<int>();
            var pageCount = response["num_pages"].Value<int>();
            var currentPage = response["current_page"].Value<int>();

            return new AccountAddressContainer(addresses, 
                totalCount, 
                pageCount, 
                currentPage
            );
        }
Пример #13
0
        public static Tuple<string, string> SplitShowsByGenre(string json, string genre)
        {
            JArray selectedShowsJson = new JArray();
            JArray otherShowsJson = new JArray();

            foreach (JObject showJson in JArray.Parse(json))
            {
                bool genreFound = false;
                foreach (JValue genreJson in showJson.Value<JArray>("genres"))
                {
                    if (genreJson.ToString() == genre)
                    {
                        selectedShowsJson.Add(showJson);
                        genreFound = true;
                        break;
                    }
                }
                if (!genreFound)
                {
                    otherShowsJson.Add(showJson);
                }
            }

            return new Tuple<string, string>(selectedShowsJson.ToString(Formatting.None), otherShowsJson.ToString(Formatting.None));
        }
Пример #14
0
    public void AddToSelf()
    {
      JArray a = new JArray();
      a.Add(a);

      Assert.IsFalse(ReferenceEquals(a[0], a));
    }
Пример #15
0
 /// <summary> Gives a list of open private rooms.
 /// Received: ORS { "channels": [object] }
 /// e.g. "channels": [{"name":"ADH-300f8f419e0c4814c6a8","characters":0,"title":"Ariel's Fun Club"}] etc. etc.
 /// Send  As: ORS</summary>
 internal static void ORS(SystemCommand C)
 {
     Newtonsoft.Json.Linq.JArray AllChannelData = Newtonsoft.Json.Linq.JArray.Parse(C.Data["channels"].ToString());
     if (AllChannelData.Count > 0)
     {
         try{
             List <Dictionary <string, object> > _AllChannelData = AllChannelData.ToObject <List <Dictionary <string, object> > >();
             for (int l = 0; l < _AllChannelData.Count; l++)
             {
                 Dictionary <string, object> currentChannel = _AllChannelData[l];                        //removal of whole-list lookup for, uh, about 100 public channels and 1000+ privates...
                 string cTitle = currentChannel["title"].ToString();
                 if (Core.channels.Count(x => x.Name == cTitle) == 0)
                 {
                     Channel ch = new Channel(cTitle, currentChannel["name"].ToString(), int.Parse(currentChannel["characters"].ToString()));
                 }
             }
         }
         catch (Exception ex) { Core.ErrorLog.Log(String.Format("Private Channel parsing failed:\n\t{0}\n\t{1}\n\t{2}", ex.Message, ex.InnerException, ex.StackTrace)); }
     }
     new IO.SystemCommand("STA { \"status\": \"online\", \"statusmsg\": \"Running CogitoMini v" + Config.AppSettings.Version + "\" }").Send();
     foreach (string cn in Core.XMLConfig["autoJoin"].Split(';'))
     {
         if (Core.channels.Count(x => x.Name == cn) > 0)
         {
             Core.channels.First(y => y.Name == cn).Join();
         }
     }
 }
Пример #16
0
            protected Request(RHost host, Message message) {
                Id = message.Id;
                MessageName = message.Name;
                Json = message.Json;

                host._requests[Id] = this;
            }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            JArray array = new JArray();
            IList list = (IList)value;
            if (list.Count > 0)
            {
                JArray keys = new JArray();

                JObject first = JObject.FromObject(list[0], serializer);
                foreach (JProperty prop in first.Properties())
                {
                    keys.Add(new JValue(prop.Name));
                }
                array.Add(keys);

                foreach (object item in list)
                {
                    JObject obj = JObject.FromObject(item, serializer);
                    JArray itemValues = new JArray();
                    foreach (JProperty prop in obj.Properties())
                    {
                        itemValues.Add(prop.Value);
                    }
                    array.Add(itemValues);
                }
            }
            array.WriteTo(writer);
        }
        public object AddOrEdit([FromBody] Newtonsoft.Json.Linq.JArray form)
        {
            dynamic openExchangeRate = form[0].ToObject <ExpandoObject>(JsonHelper.GetJsonSerializer());
            List <EntityParser.CustomField> customFields = form[1].ToObject <List <EntityParser.CustomField> >(JsonHelper.GetJsonSerializer());

            if (openExchangeRate == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
            }

            try
            {
                return(this.OpenExchangeRateRepository.AddOrEdit(openExchangeRate, customFields));
            }
            catch (UnauthorizedException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (MixERPException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage
                {
                    Content    = new StringContent(ex.Message),
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
            catch
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }
        public static void WriteTo(Bundle bundle, JsonWriter writer, bool summary = false)
        {
            if (bundle == null) throw new ArgumentException("Bundle cannot be null");

            JObject result = new JObject();

            result.Add(new JProperty(JsonDomFhirReader.RESOURCETYPE_MEMBER_NAME, "Bundle"));

            if (!String.IsNullOrWhiteSpace(bundle.Title))
                result.Add(new JProperty(BundleXmlParser.XATOM_TITLE, bundle.Title));
            if (SerializationUtil.UriHasValue(bundle.Id)) result.Add(new JProperty(BundleXmlParser.XATOM_ID, bundle.Id));
            if (bundle.LastUpdated != null) 
                result.Add(new JProperty(BundleXmlParser.XATOM_UPDATED, bundle.LastUpdated));

            if (!String.IsNullOrWhiteSpace(bundle.AuthorName))
                result.Add(jsonCreateAuthor(bundle.AuthorName, bundle.AuthorUri));
            if (bundle.TotalResults != null) result.Add(new JProperty(BundleXmlParser.XATOM_TOTALRESULTS, bundle.TotalResults.ToString()));
          
            if (bundle.Links.Count > 0)
                result.Add(new JProperty(BundleXmlParser.XATOM_LINK, jsonCreateLinkArray(bundle.Links)));
            if (bundle.Tags != null && bundle.Tags.Count() > 0)
                result.Add( TagListSerializer.CreateTagCategoryPropertyJson(bundle.Tags));

            var entryArray = new JArray();

            foreach (var entry in bundle.Entries)
                entryArray.Add(createEntry(entry,summary));

            result.Add(new JProperty(BundleXmlParser.XATOM_ENTRY, entryArray));

            result.WriteTo(writer);
        }
Пример #20
0
        public static void GetTranslations(TranslateCommand translateCommand)
        {
            foreach (string lang in translateCommand.Translations.Keys)
            {
                int counter = 0;
                Newtonsoft.Json.Linq.JArray requestTexts = new Newtonsoft.Json.Linq.JArray();

                while (counter <= 24 && counter < translateCommand.Translations[lang].Stories.Count)
                {
                    JObject text = new JObject();
                    text.Add("Text", translateCommand.Translations[lang].Stories[counter].Title);
                    requestTexts.Add(text);
                    counter++;
                }

                List <string> translations = GetTranslation(requestTexts, lang, translateCommand.DisplayLanguage).Result;

                if (translations.Count > 0)
                {
                    for (int i = 0; i < translations.Count; i++)
                    {
                        translateCommand.Translations[lang].Stories[i].TranslatedTitle = translations[i];
                    }
                }
            }
        }
Пример #21
0
        public DocumentSearchResponse GetProductIDs(JArray relatedItems)
        {
            // Execute search to find all the related products
            try
            {
                SearchParameters sp = new SearchParameters()
                {
                    SearchMode = SearchMode.Any,
                    // Limit results
                    Select = new List<String>() {"product_id","brand_name","product_name","srp","net_weight","recyclable_package",
                        "low_fat","units_per_case","product_subcategory","product_category","product_department","url", "recommendations"},
                };

                // Filter based on the product ID's
                string productIdFilter = null;
                foreach (var item in relatedItems)
                {
                    productIdFilter += "product_id eq '" + item.ToString() + "' or ";
                }
                productIdFilter = productIdFilter.Substring(0, productIdFilter.Length - 4);
                sp.Filter = productIdFilter;

                return _indexClient.Documents.Search("*", sp);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error querying index: {0}\r\n", ex.Message.ToString());
            }
            return null;
        }
 public JArray processer(string jsonStr)
 {
     String type = "";
     String key = "";
     String userID = "";
     JArray jsa = JArray.Parse(jsonStr);
     JObject json = JObject.Parse(jsa[0].ToString());
     type = json["type"].ToString();
     type = json["type"].ToString();
     userID = json["userID"].ToString();
     SmallClassDao sdao = new SmallClassDao();
     List<Model> smdlist = sdao.getModel(type, key, userID);
     List<SmallClassModel> smlist = new List<SmallClassModel>();
     foreach (Model m in smdlist)
     {
         smlist.Add((SmallClassModel)m);
     }
     JArray jsonArray = new JArray();
     foreach (SmallClassModel sm in smlist)
     {
         JObject jsonObject = new SmallClassRowMapper().mappingRow(sm);
         jsonArray.Add(jsonObject);
     }
     return jsonArray;
 }
Пример #23
0
        /// <summary>
        /// 反序列化方式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static List <T> Convert <T>(string json, JsonToolType type)
        {
            List <T> list = null;

            switch (type)
            {
            case JsonToolType.Newtonsoft:
                JsonReader reader = new JsonTextReader(new StringReader(json));
                Newtonsoft.Json.Linq.JArray array = (JArray)JToken.ReadFrom(reader);
                list = array.ToObject <List <T> >();
                break;

            case JsonToolType.Swifter:
                list = JsonFormatter.DeserializeObject <List <T> >(json);
                break;

            case JsonToolType.FastJson:
                list = fastJSON.JSON.ToObject <List <T> >(json);
                break;

            default:
                break;
            }
            return(list);
        }
Пример #24
0
        public IHttpActionResult Get(string name)
        {
            var json = string.Empty;
            var account = CloudStorageAccount.Parse(Config.Get("DeepStorage.OutputConnectionString"));
            var blobClient = account.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(Config.Get("DeepStorage.HdpContainerName"));

            var prefix = string.Format("{0}.json/part-r-", name);
            var matchingBlobs = container.ListBlobs(prefix, true);
            foreach (var part in matchingBlobs.OfType<CloudBlockBlob>())
            {
                json += part.DownloadText() + Environment.NewLine;
            }

            var outputArray = new JArray();
            foreach (var line in json.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries))
            {
                dynamic raw = JObject.Parse(line);
                var formatted = new JArray();
                formatted.Add((string)raw.eventName);
                formatted.Add((long)raw.count);
                outputArray.Add(formatted);
            }

            return Ok(outputArray);
        }
Пример #25
0
        public void ProcessBytes(Session _Session, ref JArray _Data)
        {
            try
            {
                IncomingPacket IncomingPacket = new IncomingPacket(_Data);

                if (IncomingEvents.ContainsKey(IncomingPacket.opcode))
                {
                    IIncomingPacketEvent Event = IncomingEvents[IncomingPacket.opcode];

                    if (_Session != null)
                    {
                        Event.Invoke(_Session, IncomingPacket);
                    }
                }
                else
                {
                    LogConsole.Show(LogType.ERROR, "[Opcode]: {0}", (ClientOpcode)IncomingPacket.opcode);
                }
            }
            catch (Exception e)
            {
                LogConsole.Show(LogType.DEBUG, "[ProcessByte]: {0}", e.Message);
            }
        }
Пример #26
0
        public JArray ColorCodes()
        {
            try
            {
                JArray array = new JArray();
                var fileName = "colorNames.txt";
                var filePath = HttpContext.Current.Server.MapPath("~/File/Resource/") + fileName;
                string line;

                // Read the file and display it line by line.
                System.IO.StreamReader file =
                   new System.IO.StreamReader(filePath);
                while ((line = file.ReadLine()) != null)
                {
                    string[] color = line.Split(' ');
                    //string name = color[0].Trim();
                    string value = color[1].Trim();
                    JObject obj = new JObject();
                    obj.Add("key", value);
                    array.Add(obj);
                }

                file.Close();
                return array;
            }
            catch (Exception)
            {
                return null;
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                dynamic jsonConfig = new JObject();

                var sizeX = int.Parse(SizeXBox.Text);
                jsonConfig.sizeX = sizeX;
                var sizeY = int.Parse(SizeYBox.Text);
                jsonConfig.sizeY = sizeY;

                var markerIds = new JArray();

                var startId = int.Parse(MarkerIdsBox.Text);
                for (int i = 0; i < sizeX * sizeY; i++)
                {
                    markerIds.Add(startId + i);
                }

                jsonConfig.markerIds = markerIds;
                jsonConfig.imgFilename = ImgFilenameBox.Text;
                jsonConfig.configFilename = ConfigFilenameBox.Text;
                jsonConfig.dictionaryName = ArucoDictionaries.SelectedItem as string;
                jsonConfig.pixelSize = int.Parse(PixelSizeBox.Text);
                jsonConfig.interMarkerDistance = float.Parse(InterMarkerDistanceBox.Text);

                ImageProcessing.GenerateMarkerMap(jsonConfig.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
Пример #28
0
 public BuildQueue(Newtonsoft.Json.Linq.JArray arr)
 {
     if (arr != null)
     {
         CityId = arr[0].ToString();
     }
 }
        public List<ItemRecommendation> GetItemRankings(string userId, string[] itemIds)
        {
            if (!itemIds.Any())
            {
                throw new InvalidOperationException("Must have at least one itemId");
            }
            var request = new JObject();
            request[Constants.UserId] = userId;
            var jItems = new JArray();
            foreach (var itemId in itemIds)
            {
                jItems.Add(itemId);
            }
            request[Constants.ItemIds] = jItems;
            var body = request.ToString(Formatting.None);
            var response = (JObject)Execute(Constants.EngineResource, Method.POST, body);
            if (response[Constants.IsOriginal].Value<bool>())
            {
                return new List<ItemRecommendation>();
            }
            var recommendations = new List<ItemRecommendation>();
            foreach (var item in response[Constants.Items])
            {
                var property = item.First.Value<JProperty>();
                var recommendation = new ItemRecommendation
                {
                    ItemId = property.Name,
                    Score = item.First.First.Value<float>()
                };
                recommendations.Add(recommendation);
            }
            return recommendations;

        }   
Пример #30
0
        public object AddOrEdit([FromBody] Newtonsoft.Json.Linq.JArray form)
        {
            dynamic googleAccessToken = form[0].ToObject <ExpandoObject>(JsonHelper.GetJsonSerializer());
            List <Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject <List <Frapid.DataAccess.Models.CustomField> >(JsonHelper.GetJsonSerializer());

            if (googleAccessToken == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
            }

            try
            {
                return(this.GoogleAccessTokenRepository.AddOrEdit(googleAccessToken, customFields));
            }
            catch (UnauthorizedException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (DataAccessException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage
                {
                    Content    = new StringContent(ex.Message),
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
#if !DEBUG
            catch
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
#endif
        }
Пример #31
0
        public object AddOrEdit([FromBody] Newtonsoft.Json.Linq.JArray form)
        {
            dynamic flag = form[0].ToObject <ExpandoObject>(JsonHelper.GetJsonSerializer());
            List <Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject <List <Frapid.DataAccess.Models.CustomField> >(JsonHelper.GetJsonSerializer());

            if (flag == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
            }

            try
            {
                flag.user_id    = this._UserId;
                flag.flagged_on = System.DateTime.UtcNow;

                return(this.FlagRepository.AddOrEdit(flag, customFields));
            }
            catch (UnauthorizedException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }
Пример #32
0
 /// <summary>
 /// Parse the property editors from the json array
 /// </summary>
 /// <param name="jsonEditors"></param>
 /// <returns></returns>
 internal static IEnumerable<PropertyEditor> GetPropertyEditors(JArray jsonEditors)
 {
     return JsonConvert.DeserializeObject<IEnumerable<PropertyEditor>>(
         jsonEditors.ToString(), 
         new PropertyEditorConverter(),
         new PreValueFieldConverter());
 }
Пример #33
0
 private void TraverseArray(JArray array)
 {
     foreach (JToken item in array)
     {
         ProcessElement(item);
     }
 }
Пример #34
0
 public static JArray Diff(JArray source, JArray target, out bool changed, bool nullOnRemoved = false)
 {
     changed = source.Count != target.Count;
     var diffs = new JToken[target.Count];
     var commonLen = Math.Min(diffs.Length, source.Count);
     for (int i = 0; i < commonLen; i++)
     {
         if (target[i].Type == JTokenType.Object && source[i].Type == JTokenType.Object)
         {
             var subchanged = false;
             diffs[i] = Diff((JObject)source[i], (JObject)target[i], out subchanged, nullOnRemoved);
             if (subchanged) changed = true;
         }
         else if (target[i].Type == JTokenType.Array && source[i].Type == JTokenType.Array)
         {
             var subchanged = false;
             diffs[i] = Diff((JArray)source[i], (JArray)target[i], out subchanged, nullOnRemoved);
             if (subchanged) changed = true;
         }
         else
         {
             diffs[i] = target[i];
             if (!JToken.DeepEquals(source[i], target[i]))
                 changed = true;
         }
     }
     for (int i = commonLen; i < diffs.Length; i++)
     {
         diffs[i] = target[i];
         changed = true;
     }
     return new JArray(diffs);
 }
Пример #35
0
        public string AnalyzeScores(string localizationCode, string messages)
        {
            JsonSerializer serializer = new JsonSerializer();
            TextReader reader = new StringReader(messages);
            JArray jArray = (JArray)serializer.Deserialize(reader, typeof(JArray));

            JArray scoreResults = new JArray();

            for (int index = 0; index < jArray.Count; index++ )
            {
                JToken entry = jArray[index];
                IMessage message = new Message
                {
                     Content = new StringBuilder( entry["text"].ToString()),
                     Metadata = new StringBuilder(entry.ToString())
                };

                double score =  this.AnalyzeScore(localizationCode, message);

                entry["Score"] = score;

                scoreResults.Add(entry);
            }

            TextWriter writer = new StringWriter();

            serializer.Serialize(writer, scoreResults);

            string mergedJsonResult = writer.ToString();

            return mergedJsonResult;
        }
        private async void button_send_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            JArray ja = new JArray();

            foreach (var a in ((ListView)listView_friends).SelectedItems)
            {
                classes.Friend friendToSendSnapTo = (classes.Friend)(a);
                ja.Add(friendToSendSnapTo.username);
            }

            String JSON = await a.sendSnap(main.static_user, main.static_pass, pb, ja.ToString(), snap_file, int.Parse(slider_time.Value.ToString()));

            //Frame.Navigate(typeof(snap_screen));

            JObject jo = JObject.Parse(JSON);

            if (jo["status"].ToString() == "True")
            {
                h.showSingleButtonDialog("Snap uploaded", "Snap uploaded successfully!", "Dismiss");
            }
            else
            {
                h.showSingleButtonDialog("Server error [" + jo["code"] + "]", ((jo["message"] != null) ? jo["message"].ToString() : "No server message was provided"), "Dismiss");
            }

        }
Пример #37
0
 /// <summary>
 /// Loads member list
 /// </summary>
 /// <param name="a">json list of members</param>
 void LoadMemberList(JArray a)
 {
     for (int i = 0; i < a.Count; i++)
     {
         memberList.Add(new TeamMemberInfo((long)a[i]["inviteDate"], (long?)a[i]["joinDate"], (long)a[i]["playerId"], (string)a[i]["status"]));
     }
 }
Пример #38
0
 public PlayerStatsSummaryList(JArray playerStatSummariesA, long summonerId, CreepScore.Season season)
 {
     playerStatSummaries = new List<PlayerStatsSummary>();
     LoadPlayerStatSummaries(playerStatSummariesA);
     this.summonerId = summonerId;
     this.season = season;
 }
Пример #39
0
        public JObject serializeObject()
        {
            JObject obj = new JObject();

            obj.Add("Name", _name);
            obj.Add("Material", this._material.serializeObject());

            JObject multipartObj = new JObject();
            multipartObj.Add("UseMultipart", isMultipart);
            multipartObj.Add("Part", numberOfPart);
            multipartObj.Add("TotalParts", numberOfParts);
            obj.Add("Multipart", multipartObj);

            if(_meshes.Count != 0){
                JArray meshesNode = new JArray();

                for (int i = 0; i < _meshes.Count; i++)
                {
                    Mesh m = _meshes[i];
                    meshesNode.Add(m.serializeObject());
                }
                obj.Add("Meshes", meshesNode);

                return obj;
            }
            return null;
        }
Пример #40
0
        public int position_source;   //  int	Origin of this state’s position: 0 = ADS-B, 1 = ASTERIX, 2 = MLAT*/


        // not sure I like this, as we are very schema sensitive, but there is no other way to get this.
        // ToDo: need to check the api definition for potential handling requirement of null values etc
        // maybe need to give some thought to what the null values should represent,
        // and if we want to propagate these nulls...
        // currently quick and dirty setting strings to empty, bool to false and numbers to 0
        public static State ConvertJArray(Newtonsoft.Json.Linq.JArray array)
        {
            if (array.Count < 17)
            {
                throw new Exception("unexpected number of elements in Json Array retrieved from service");
            }
            State result = new State();

            result.icao24          = CheckJArrayValue(array[0]) ? array.Value <string>(0) : "";
            result.callsign        = CheckJArrayValue(array[1]) ? array.Value <string>(1) : "";
            result.origin_country  = CheckJArrayValue(array[2]) ? array.Value <string>(2) : "";
            result.time_position   = CheckJArrayValue(array[3]) ? array.Value <int>(3) : 0;
            result.last_contact    = CheckJArrayValue(array[4]) ? array.Value <int>(4) : 0;
            result.longitude       = CheckJArrayValue(array[5]) ? array.Value <float>(5) : 0;
            result.latitude        = CheckJArrayValue(array[6]) ? array.Value <float>(6) : 0;
            result.baro_altitude   = CheckJArrayValue(array[7]) ? array.Value <float>(7) : 0;
            result.on_ground       = CheckJArrayValue(array[8]) ? array.Value <bool>(8) : false;
            result.velocity        = CheckJArrayValue(array[9]) ? array.Value <float>(9) : 0;
            result.true_track      = CheckJArrayValue(array[10]) ? array.Value <float>(10) : 0;
            result.vertical_rate   = CheckJArrayValue(array[11]) ? array.Value <float>(11) : 0;
            result.sensors         = CheckJArrayValue(array[12]) ? array.Value <int[]>(12) : new int [0];
            result.geo_altitude    = CheckJArrayValue(array[13]) ? array.Value <float>(13) : 0;
            result.squawk          = CheckJArrayValue(array[14]) ? array.Value <string>(14) : "";
            result.spi             = CheckJArrayValue(array[15]) ? array.Value <bool>(15) : false;
            result.position_source = CheckJArrayValue(array[16]) ? array.Value <int>(16) : 0;
            return(result);
        }
Пример #41
0
        private static TestCase CreateTestCase(JArray items)
        {
            var template = items[0].Value<string>();
            var isInvalid = false;
            var expecteds = new List<string>();

            if (items[1].Type == JTokenType.Array)
            {
                expecteds.AddRange(items[1].Select(x => x.Value<string>()));
            }
            else if (items[1].Type == JTokenType.String)
            {
                expecteds.Add(items[1].Value<string>());
            }
            else if (items[1].Type == JTokenType.Boolean)
            {
                isInvalid = !items[1].Value<bool>();
            }
            else
            {
                throw new FormatException("Invalid testcases format");
            }

            return new TestCase
            {
                Template = template,
                IsInvalid = isInvalid,
                Expecteds = expecteds
            };
        }
Пример #42
0
        public static void AfterSeleniumTestScenario()
        {
            var time = DateTime.UtcNow;

            var currentFeature = (JObject) FeatureContext.Current["currentFeature"];
            var scenarios = (JArray) currentFeature["scenarios"];
            var scenario = new JObject();
            scenario["title"] = ScenarioContext.Current.ScenarioInfo.Title;
            scenario["startTime"] = FeatureContext.Current["time"].ToString();
            scenario["endTime"] = time.ToString();
            scenario["tags"] = new JArray(ScenarioContext.Current.ScenarioInfo.Tags);

            var err = ScenarioContext.Current.TestError;
            if (err != null)
            {
                var error = new JObject();
                error["message"] = ScenarioContext.Current.TestError.Message;
                error["stackTrace"] = ScenarioContext.Current.TestError.StackTrace;
                scenario["error"] = error;
                scenario["status"] = "error";
            }
            else {
                scenario["status"] = "ok";
            }
            scenarios.Add(scenario);
        }
Пример #43
0
        public void ProcessRequest(HttpContext context)
        {
            if (context.Session["Authentication"] == null)
                throw new Exception("Ошибка обновления");

            int ShopId = Convert.ToInt32(context.Session["ShopId"]);
            int ArticleId = Convert.ToInt32(context.Request["ArticleId"]);

            var dsStatistic = new dsStatistic();
            (new DataSets.dsStatisticTableAdapters.taSalesHistory()).Fill
                (dsStatistic.tbSalesHistory, ShopId, ArticleId);

            var JHistory = new JArray();
            foreach (dsStatistic.tbSalesHistoryRow rw in dsStatistic.tbSalesHistory)
                JHistory.Add(new JObject(
                    new JProperty("Дата_продажи",rw.Дата_продажи),
                    new JProperty("Номер_чека", rw.Номер_чека),
                    new JProperty("Количество", rw.Количество),
                    new JProperty("ПрИнфо", rw.ПрИнфо),
                    new JProperty("Инфо", rw.Инфо)
                    ));

            var JObject = new JObject(
                new JProperty("Код_артикула", ArticleId),
                new JProperty("История", JHistory));

            context.Response.ContentType = "application/json";
            context.Response.Write(JObject.ToString());
        }
 private void VisitArray(Newtonsoft.Json.Linq.JArray array)
 {
     for (int index = 0; index < array.Count; index++)
     {
         EnterContext(index.ToString());
         VisitToken(array[index]);
         ExitContext();
     }
 }
Пример #45
0
 public override JToken getOutput()
 {
     Newtonsoft.Json.Linq.JArray timeArray = new Newtonsoft.Json.Linq.JArray();
     for (int ii = 0; ii < TimeSeriesLength; ++ii)
     {
         o_TimeSeriesIndex = ii;
         timeArray.Add(new Newtonsoft.Json.Linq.JArray(Value));
     }
     resetTimeSeries();
     return(timeArray);
 }
Пример #46
0
 /// <summary>
 /// 返回一个json数组
 /// </summary>
 /// <param name="jobject"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static JArray GetArray(this Newtonsoft.Json.Linq.JObject jobject, string key)
 {
     Newtonsoft.Json.Linq.JArray jv = jobject[key] as Newtonsoft.Json.Linq.JArray;
     if (jv != null && jv.Count > 0)
     {
         return(jv);
     }
     else
     {
         return(null);
     }
 }
Пример #47
0
        void ReadCoin(Enumeraveis.Moedas moeda)
        {
            String  JSON  = Request(moeda, "ticker", richTicker);
            JObject JCoin = JsonConvert.DeserializeObject <JObject>(JSON);
            Ticker  tick  = JsonConvert.DeserializeObject <Ticker>(JCoin["ticker"].ToString());

            minValue = tick.low;
            maxValue = tick.high;

            String s = Request(Enumeraveis.Moedas.BTC, "trades", richTrade);

            JArray JTrades = JsonConvert.DeserializeObject <JArray>(s);

            foreach (object item in JTrades)
            {
                Negociacoes trade        = JsonConvert.DeserializeObject <Negociacoes>(item.ToString());
                BitCoinData _bitCoinData = new BitCoinData();
                _bitCoinData.Date        = trade.date;
                _bitCoinData.Transaction = trade.tid;
                _bitCoinData.Amount      = (float)trade.amount;
                _bitCoinData.Price       = (float)trade.price;
                _bitCoinData.Type        = (trade.type == "sell") ? 1 : 0;

                input.Add(_bitCoinData);

                if (richTrade.InvokeRequired)
                {
                    richTrade.Invoke(new Action(() => richTrade.Text += "\r\n"));
                }
                else
                {
                    richTrade.Text += Convert.ToInt32(_bitCoinData.Date) +
                                      _bitCoinData.Price + ", " +
                                      _bitCoinData.Amount + ", " +
                                      _bitCoinData.Transaction + "\r\n";
                }
            }

            #region Criação da Base de Teste diária
            if (!File.Exists(TrainBitcoinDataPath))
            {
                btnMercadoBitCoin_Click(this, new EventArgs());
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText(TrainBitcoinDataPath))
                {
                    Console.WriteLine(maxValue);
                }
            }


            #endregion
        }
Пример #48
0
        private void login()
        {
            try
            {
                Console.WriteLine("Logging in...");

                var         client  = new RestClient("https://json.ibroadcast.com/s/JSON/");
                RestRequest request = new RestRequest(Method.POST);
                request.RequestFormat = DataFormat.Json;
                request.AddHeader("Content-Type", "application/json");
                request.AddParameter("text/json", userdetails, ParameterType.RequestBody);

                var response = client.Execute(request);

                if (System.Net.HttpStatusCode.OK != response.StatusCode)
                {
                    Console.WriteLine("{0} failed.\nresponse.Code: {1}\nresponse.StatusDescription: {2}", System.Reflection.MethodBase.GetCurrentMethod().Name, response.StatusCode, response.StatusDescription);
                    Environment.Exit(-1);
                }

                bool    result  = false;
                dynamic dynJson = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(response.Content);

                result = (bool)dynJson.result;
                if (!result)
                {
                    Console.WriteLine("{0}", (String)dynJson.message);
                    Environment.Exit(-1);
                }

                userId    = (String)dynJson.user.id;
                userToken = (String)dynJson.user.token;
                Newtonsoft.Json.Linq.JArray supported = dynJson.supported;

                Console.WriteLine("Login successful");

                foreach (JObject jObj in supported)
                {
                    dynamic dynObj = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(jObj.ToString());
                    String  ext    = (String)dynObj.extension;
                    if (!extensions.Contains(ext)) //is extension unique? (ex: .flac x 3 in response)
                    {
                        extensions.Add(ext);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} failed. Please check your email address, password combination. Exception: {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, e.Message);
                Environment.Exit(-1);
            }
        }
Пример #49
0
        private void SelecFilmByGenre(bool minusFilter = true, string minusFilterValue = "мульт")
        {
            Newtonsoft.Json.Linq.JArray  temp    = new Newtonsoft.Json.Linq.JArray();
            Newtonsoft.Json.Linq.JObject tempObj = new Newtonsoft.Json.Linq.JObject();
            string genre = "";

            foreach (var j in allFilm)
            {
                try
                {
                    tempObj = j["ThisCard"] as Newtonsoft.Json.Linq.JObject;
                    genre   = tempObj.Value <string>("Genre").ToLower();
                    if (genre.Contains(selectedGenre) || string.IsNullOrEmpty(selectedGenre))
                    {
                        if (minusFilter)
                        {
                            if (!genre.Contains(minusFilterValue))
                            {
                                temp.Add(j);
                            }
                        }
                        else
                        {
                            temp.Add(j);
                        }
                    }
                }
                catch
                {
                    continue;
                }
            }

            Films = new JObject[temp.Count];



            int u = 0;

            foreach (var t in temp)
            {
                Films[u] = (JObject)t;
                u++;
            }

            if (Films.Length > 0)
            {
                SetSelectedFilms(0);
                label5.Text = Films.Length.ToString();
            }
        }
Пример #50
0
        public Form1()
        {
            InitializeComponent();
            set = new Settings();

            exeDrive = "D";//Application.ExecutablePath[0].ToString();
            var d = JObject.Parse(File.ReadAllText(string.Format("{0}:\\filmList.json", exeDrive)));
            var s = JObject.Parse(File.ReadAllText(string.Format("{0}:\\migasettings.json", exeDrive)));

            filmFolder = s.Value <string>("filmfolder");

            allFilm = d["data"] as JArray;
            radioButton5.Checked = true;
        }
Пример #51
0
        public static string GetIdSceneInfoChild(string msg, string nodeName)
        {
            dynamic jsonData = JsonConvert.DeserializeObject(msg);

            Newtonsoft.Json.Linq.JArray children = jsonData.data.data.data.children;
            foreach (dynamic d in children)
            {
                if (d.name == nodeName)
                {
                    return(d.uuid);
                }
            }
            return(null);
        }
Пример #52
0
 public HookProcessor(Newtonsoft.Json.Linq.JArray hooks)
 {
     if (hooks != null && hooks.Count > 0)
     {
         foreach (var x in hooks)
         {
             HookListener listener = ConstructListener(x as JObject);
             if (listener != null)
             {
                 InstalledHooks.Add(listener);
             }
         }
     }
 }
Пример #53
0
        private Dictionary <string, PromocodeInformation> ReadPromocodesInformation(Newtonsoft.Json.Linq.JArray promocodes)
        {
            var promocodesDictionary = new Dictionary <string, PromocodeInformation>();
            var provider             = new LoyaltyDBProvider();

            foreach (string promocode in promocodes)
            {
                if (!promocodesDictionary.ContainsKey(promocode))
                {
                    promocodesDictionary[promocode] = provider.ExecuteSelectQuery(@"SELECT ""ContactId"", ""IsUsed"", ""PoolId"", ""Id"" FROM public.""PromoCode"" Where ""Code"" = '{0}'", ReadPromocodeInformation, promocode);
                }
            }

            return(promocodesDictionary);
        }
Пример #54
0
        private void loadFileNames(ResponseObject obj, string path, Newtonsoft.Json.Linq.JArray objectTypes)
        {
            string[] dirs = Directory.GetDirectories(path);

            string[] files1 = Directory.GetFiles(path, "*.json", SearchOption.TopDirectoryOnly);
            string[] files2 = Directory.GetFiles(path, "*.test.jsx", SearchOption.TopDirectoryOnly);
            var      files  = files1.Union(files2).ToArray();

            if (dirs.Length > 0 || files.Length > 0)
            {
                obj.items = new List <ResponseObject>();
            }
            foreach (var dir in dirs)
            {
                var newItemName = Path.GetFileName(dir);
                if (obj.name == "root" && newItemName == "vendor")
                {
                    continue;
                }
                var newDirItem = new ResponseObject();
                newDirItem.name     = newItemName;
                newDirItem.isFolder = true;

                loadFileNames(newDirItem, dir, objectTypes);

                obj.items.Add(newDirItem);
            }
            foreach (var file in files)
            {
                //FileInfo info = new FileInfo(file);
                var newFileItem = new ResponseObject();
                newFileItem.name = Path.GetFileName(file);

                if (objectTypes.Count > 0)
                {
                    var words    = newFileItem.name.Split(".");
                    var itemType = words[words.Length - 2]; // "Заявки.table.json"
                    if (objectTypes.ToObject <string[]>().Contains(itemType))
                    {
                        obj.items.Add(newFileItem);
                    }
                }
                else
                {
                    obj.items.Add(newFileItem);
                }
            }
        }   //Newtonsoft.Json.Linq.JArray
Пример #55
0
        public async Task CreateDeepnetFromRemoteSource()
        {
            // Prepare connection
            Client c = new Client(userName, apiKey);

            // Create source
            Source.Arguments args = new Source.Arguments();
            args.Add("remote", "http://static.bigml.com/csv/iris.csv");
            Source s = await c.CreateSource(args);

            s = await c.Wait <Source>(s.Resource);

            Assert.AreEqual(s.StatusMessage.StatusCode, Code.Finished);

            // Create dataset
            DataSet.Arguments argsDS = new DataSet.Arguments();
            argsDS.Add("source", s.Resource);
            DataSet ds = await c.CreateDataset(argsDS);

            ds = await c.Wait <DataSet>(ds.Resource);

            Assert.AreEqual(ds.StatusMessage.StatusCode, Code.Finished);

            // Create deepnet
            Deepnet.Arguments argsDn = new Deepnet.Arguments();
            argsDn.Add("dataset", ds.Resource);
            Deepnet dn = await c.CreateDeepnet(argsDn);

            dn = await c.Wait <Deepnet>(dn.Resource);

            Assert.AreEqual(dn.StatusMessage.StatusCode, Code.Finished);

            // test UPDATE method
            Newtonsoft.Json.Linq.JObject changes = new Newtonsoft.Json.Linq.JObject();
            Newtonsoft.Json.Linq.JArray  tags    = new Newtonsoft.Json.Linq.JArray();
            tags.Add("Bindings C# test");
            changes.Add("tags", tags);
            dn = await c.Update <Deepnet>(dn.Resource, changes);

            Assert.AreEqual(dn.Code, System.Net.HttpStatusCode.Accepted);

            // test DELETE method
            await c.Delete(s);

            await c.Delete(ds);

            await c.Delete(dn);
        }
Пример #56
0
        /// <summary>
        /// returns all the users from the given response
        /// </summary>
        /// <param name="msg">the message gotten from the server, without the length prefix</param>
        /// <returns></returns>
        public static PC[] GetUsers(string msg)
        {
            dynamic jsonData = JsonConvert.DeserializeObject(msg);

            Newtonsoft.Json.Linq.JArray data = jsonData.data;
            PC[] res     = new PC[data.Count];
            int  counter = 0;

            foreach (dynamic d in data)
            {
                res[counter] = new PC((string)d.clientinfo.host, (string)d.clientinfo.user);
                counter++;
            }

            return(res);
        }
Пример #57
0
    IEnumerator upmov()
    {
        UnityWebRequest www = UnityWebRequest.Get("https://api.themoviedb.org/3/movie/upcoming?api_key=" + key + "&language=en-US&page=1");

        yield return(www.Send());

        if (www.isError)
        {
            //pesan.text ="ip localhost:8085" + www.error;
            Debug.Log("ip 10.205.6.138:8085" + www.error);
        }
        else
        {
            string  hasil = www.downloadHandler.text;
            JObject json  = JObject.Parse(hasil);
            //Debug.Log(json.GetValue("Status"));
            Newtonsoft.Json.Linq.JArray cb = (Newtonsoft.Json.Linq.JArray)json["results"];
            var result0 = (JObject)cb[0];
            var result1 = (JObject)cb[1];
            var result2 = (JObject)cb[2];

            string url = "https://image.tmdb.org/t/p/w500/" + result0.GetValue("poster_path").ToString();
            texu = new Texture2D(4, 4, TextureFormat.DXT1, false);
            using (WWW www2 = new WWW(url)){
                yield return(www2);

                www2.LoadImageIntoTexture(texu);
                u1.GetComponent <Renderer> ().material.mainTexture = texu;
            }
            string url1 = "https://image.tmdb.org/t/p/w500/" + result1.GetValue("poster_path").ToString();
            texu1 = new Texture2D(4, 4, TextureFormat.DXT1, false);
            using (WWW www2 = new WWW(url1)){
                yield return(www2);

                www2.LoadImageIntoTexture(texu1);
                u2.GetComponent <Renderer> ().material.mainTexture = texu1;
            }
            string url2 = "https://image.tmdb.org/t/p/w500/" + result2.GetValue("poster_path").ToString();
            texu2 = new Texture2D(4, 4, TextureFormat.DXT1, false);
            using (WWW www2 = new WWW(url2)){
                yield return(www2);

                www2.LoadImageIntoTexture(texu2);
                u3.GetComponent <Renderer> ().material.mainTexture = texu2;
            }
        }
    }
Пример #58
0
        public string HttpGetForTrades(string URI, RichTextBox textBox)
        {
            WebClient cliente = new WebClient();

            cliente.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            string s = string.Empty;


            int    since   = sinceParam;
            string helpURI = URI;

            for (int i = 0; i < lerJSONs; i++)
            {
                URI = helpURI + "?since=" + since;

                Stream       data   = cliente.OpenRead(URI);
                StreamReader reader = new StreamReader(data);
                s = reader.ReadToEnd();
                JArray      trades       = JsonConvert.DeserializeObject <JArray>(s);
                BitCoinData _bitCoinData = new BitCoinData();

                foreach (object item in trades)
                {
                    Negociacoes trade = JsonConvert.DeserializeObject <Negociacoes>(item.ToString());
                    _bitCoinData             = new BitCoinData();
                    _bitCoinData.Date        = trade.date;
                    _bitCoinData.Transaction = trade.tid;
                    _bitCoinData.Amount      = (float)trade.amount;
                    _bitCoinData.Price       = (float)trade.price;
                    _bitCoinData.Type        = (trade.type == "sell") ? 1 : 0;

                    input.Add(_bitCoinData);
                }
                if (textBox.InvokeRequired)
                {
                    textBox.Invoke(new Action(() => textBox.Text += s + "\r\n"));
                }
                else
                {
                    textBox.Text += s + "\r\n";
                }
                since = Convert.ToInt32(_bitCoinData.Transaction);
                data.Close();
                reader.Close();
            }
            return(s);
        }
Пример #59
0
        public static DataTable JsonToDataTable(string json, string tableName)
        {
            bool      columnsCreated = false;
            DataTable dt             = new DataTable(tableName);

            Newtonsoft.Json.Linq.JObject root  = Newtonsoft.Json.Linq.JObject.Parse(json);
            Newtonsoft.Json.Linq.JArray  items = (Newtonsoft.Json.Linq.JArray)root[tableName];

            Newtonsoft.Json.Linq.JObject item   = default(Newtonsoft.Json.Linq.JObject);
            Newtonsoft.Json.Linq.JToken  jtoken = default(Newtonsoft.Json.Linq.JToken);

            for (int i = 0; i <= items.Count - 1; i++)
            {
                // Create the columns once
                if (columnsCreated == false)
                {
                    item   = (Newtonsoft.Json.Linq.JObject)items[i];
                    jtoken = item.First;

                    while (jtoken != null)
                    {
                        dt.Columns.Add(new DataColumn(((Newtonsoft.Json.Linq.JProperty)jtoken).Name.ToString()));
                        jtoken = jtoken.Next;
                    }

                    columnsCreated = true;
                }

                // Add each of the columns into a new row then put that new row into the DataTable
                item   = (Newtonsoft.Json.Linq.JObject)items[i];
                jtoken = item.First;

                // Create the new row, put the values into the columns then add the row to the DataTable
                DataRow dr = dt.NewRow();

                while (jtoken != null)
                {
                    dr[((Newtonsoft.Json.Linq.JProperty)jtoken).Name.ToString()] = ((Newtonsoft.Json.Linq.JProperty)jtoken).Value.ToString();
                    jtoken = jtoken.Next;
                }

                dt.Rows.Add(dr);
            }

            return(dt);
        }
Пример #60
0
        public async Task CreateLogisticRegressionFromRemoteSource()
        {
            Client c = new Client(userName, apiKey);

            Source.Arguments args = new Source.Arguments();
            args.Add("remote", "https://static.bigml.com/csv/iris.csv");
            args.Add("name", "C# tests - Iris");

            Source s = await c.CreateSource(args);

            s = await c.Wait <Source>(s.Resource);

            Assert.AreEqual(s.StatusMessage.StatusCode, Code.Finished);

            DataSet.Arguments argsDS = new DataSet.Arguments();
            argsDS.Add("source", s.Resource);
            DataSet ds = await c.CreateDataset(argsDS);

            ds = await c.Wait <DataSet>(ds.Resource);

            Assert.AreEqual(ds.StatusMessage.StatusCode, Code.Finished);

            LogisticRegression.Arguments argsTM = new LogisticRegression.Arguments();
            argsTM.Add("dataset", ds.Resource);
            LogisticRegression lr = await c.CreateLogisticRegression(argsTM);

            lr = await c.Wait <LogisticRegression>(lr.Resource);

            // test it is finished
            Assert.AreEqual(lr.StatusMessage.StatusCode, Code.Finished);

            // test update method
            Newtonsoft.Json.Linq.JObject changes = new Newtonsoft.Json.Linq.JObject();
            Newtonsoft.Json.Linq.JArray  tags    = new Newtonsoft.Json.Linq.JArray();
            tags.Add("Bindings C# test");
            changes.Add("tags", tags);
            lr = await c.Update <LogisticRegression>(lr.Resource, changes);

            Assert.AreEqual(lr.Code, System.Net.HttpStatusCode.Accepted);

            await c.Delete(s);

            await c.Delete(ds);

            await c.Delete(lr);
        }