public string Get(int id)
        {
            var json = System.IO.File.ReadAllText(jsonFile);

            HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

            try
            {
                var jObject = JObject.Parse(json);
                if (jObject != null)
                {
                    JArray students = (JArray)jObject["students"];
                    if (students.FirstOrDefault(obj => obj["id"].Value <int>() == id) != null)
                    {
                        return(students.FirstOrDefault(obj => obj["id"].Value <int>() == id).ToString());
                    }
                    else
                    {
                        return("NULL");
                    }
                    // return students[index].ToString();
                }
                else
                {
                    Console.WriteLine("jObject is null");
                    // return "NULL";
                    return("NULL");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return("Exception occured");
            }
        }
Example #2
0
        private static void DrawAdditionalWrapImage(JArray AssetProperties)
        {
            JToken largePreviewImage = AssetProperties.FirstOrDefault(x => string.Equals(x["name"].Value <string>(), "LargePreviewImage"));
            JToken smallPreviewImage = AssetProperties.FirstOrDefault(x => string.Equals(x["name"].Value <string>(), "SmallPreviewImage"));

            if (largePreviewImage != null || smallPreviewImage != null)
            {
                JToken assetPathName =
                    largePreviewImage != null ? largePreviewImage["tag_data"]["asset_path_name"] :
                    smallPreviewImage != null ? smallPreviewImage["tag_data"]["asset_path_name"] : null;

                if (assetPathName != null)
                {
                    string texturePath = FoldersUtility.FixFortnitePath(assetPathName.Value <string>());
                    using (Stream image = AssetsUtility.GetStreamImageFromPath(texturePath))
                    {
                        if (image != null)
                        {
                            BitmapImage bmp = new BitmapImage();
                            bmp.BeginInit();
                            bmp.CacheOption  = BitmapCacheOption.OnLoad;
                            bmp.StreamSource = image;
                            bmp.EndInit();
                            bmp.Freeze();

                            IconCreator.ICDrawingContext.DrawImage(bmp, new Rect(275, 272, 122, 122));
                        }
                    }
                }
            }
        }
Example #3
0
        //finds a single person
        public Person Find(int id)
        {
            var person = _table.FirstOrDefault(p => p.ToObject <Person>().Id == id);

            if (person == null)
            {
                return(null);
            }
            JsonSerializer serializer  = new JsonSerializer();
            Person         firstPerson = (Person)serializer.Deserialize(new JTokenReader(person), typeof(Person));

            return(firstPerson);
        }
Example #4
0
        /// <summary>
        /// Finds an entity with a specified id.
        /// </summary>
        /// <returns>
        /// An entity with a specified id or defaut if not found.
        /// </returns>
        /// <param name="id">An interger number.</param>
        /// See <see cref="Dataset.FindAsync()"/> to getAll asyncronously.
        public E Find(object id)
        {
            var entity = _rows.FirstOrDefault(e => e.ToObject <E>().Id == id);

            if (entity == null)
            {
                return(default(E));
            }
            JsonSerializer serializer = new JsonSerializer();
            E firstEntity             = (E)serializer.Deserialize(new JTokenReader(entity), typeof(E));

            return(firstEntity);
        }
Example #5
0
        private string GetUIAppUrl(string folder)
        {
            var appUrl = appGatewayConfig.FirstOrDefault(f => f["ui_folder"].ToString() == folder);

            if (appUrl != null)
            {
                return(appUrl[CommonConst.CommonField.DATA].ToString());
            }
            else
            {
                return(string.Empty);
            }
        }
Example #6
0
        private string GetSubtitle(JObject json, string language = null)
        {
            JArray subtitles = (JArray)json["subtitles"];
            JToken subtitle  = null;
            string srt       = string.Empty;

            if (language != null)
            {
                subtitle = subtitles.FirstOrDefault(s => s["label"] != null && s["label"].Value <string>() == language);
            }
            else if (subtitleChoice == Subtitle.Förvald_URPlay)
            {
                subtitle = subtitles.FirstOrDefault(s => s["default"] != null && s["default"].Value <bool>());
            }
            else if (subtitleChoice == Subtitle.Svenska)
            {
                subtitle = subtitles.FirstOrDefault(s => s["label"] != null && s["label"].Value <string>() == Subtitle.Svenska.ToString());
            }
            if (subtitle != null)
            {
                XmlDocument xDoc          = GetWebData <XmlDocument>(subtitle["file"].Value <string>());
                var         errorElements = xDoc.SelectNodes("//meta[@name = 'error']");
                if (errorElements == null || errorElements.Count <= 0)
                {
                    string srtFormat = "{0}\r\n{1}0 --> {2}0\r\n{3}\r\n\r\n";
                    string begin;
                    string end;
                    string text;
                    string textPart;
                    int    line = 1;
                    foreach (XmlElement p in xDoc.GetElementsByTagName("p"))
                    {
                        text  = string.Empty;
                        begin = p.GetAttribute("begin");
                        end   = p.GetAttribute("end");
                        XmlNodeList textNodes = p.SelectNodes(".//text()");
                        foreach (XmlNode textNode in textNodes)
                        {
                            textPart = textNode.InnerText;
                            textPart.Trim();
                            text += string.IsNullOrEmpty(textPart) ? "" : textPart + "\r\n";
                        }
                        srt += string.Format(srtFormat, line++, begin, end, text);
                    }
                }
            }
            return(srt);
        }
Example #7
0
        public static string GetMemberCard(long GroupId, long memberCount, long RobotQQ, string skey, string p_skey, int bkn, long uin)
        {
            string html = GetMemberCardXHR(GroupId, memberCount, RobotQQ, skey, p_skey, bkn);

            if (string.IsNullOrWhiteSpace(html))
            {
                return(null);
            }

            try
            {
                JObject jObject = (JObject)JsonConvert.DeserializeObject(html);
                JArray  mems    = (JArray)jObject["mems"];
                JToken  mem     = mems.FirstOrDefault(x => x["uin"].ToString() == uin.ToString());
                if (mem == null)
                {
                    return(null);
                }

                if (!mem.Contains("card"))
                {
                    return(null);
                }

                return(mem["card"].ToString());
            }
            catch { return(null); }
        }
Example #8
0
        public async Task Create_WithValidClient_AndThenReturnAll_IncludesNewClient(string clientName, string acctMgrEmail, string acctMgrName)
        {
            var client = _factory.CreateClient(
                new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false,
                BaseAddress       = new Uri("http://localhost")
            });

            // Create client
            var requestContent = new StringContent(@"{'name': '" + clientName + "','accountManagerEmail': '" + acctMgrEmail + "','accountManagerName' : '" + acctMgrName + "'}");

            requestContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            await client.PostAsync("http://localhost/api/clients", requestContent);

            // Get all clients
            var response = await client.GetAsync("http://localhost/api/clients");

            var content = await response.Content.ReadAsStringAsync();

            JArray clientsJson = JArray.Parse(content);

            response.EnsureSuccessStatusCode(); // Status Code 200-299
            clientsJson.FirstOrDefault(c => (string)c["name"] == clientName).Should().NotBeNull();
        }
Example #9
0
        public IActionResult SaveResource([FromBody] dynamic jsonData, string id, string org, string app)
        {
            id = id.Split('-')[0];
            JObject json = jsonData;

            JArray resources = json["resources"] as JArray;

            string[] duplicateKeys = resources.GroupBy(obj => obj["id"]).Where(grp => grp.Count() > 1).Select(grp => grp.Key.ToString()).ToArray();
            if (duplicateKeys.Length > 0)
            {
                return(BadRequest($"Text keys must be unique. Please review keys: {string.Join(", ", duplicateKeys)}"));
            }

            JArray sorted = new JArray(resources.OrderBy(obj => obj["id"]));

            json["resources"].Replace(sorted);

            // updating application metadata with appTitle.
            JToken appTitleToken = resources.FirstOrDefault(x => x.Value <string>("id") == "ServiceName");

            if (!(appTitleToken == null))
            {
                string appTitle = appTitleToken.Value <string>("value");
                _repository.UpdateAppTitle(org, app, id, appTitle);
            }

            _repository.SaveLanguageResource(org, app, id, json.ToString());

            return(Json(new
            {
                Success = true,
                Message = "Språk lagret",
            }));
        }
        private void btn_teacher_delete_Click(object sender, EventArgs e)
        {
            var json = File.ReadAllText(jsonFile);

            try
            {
                var    jObject           = JObject.Parse(json);
                JArray experiencesArrary = (JArray)jObject["result"];


                var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["student_name"].Value <string>() == cmb_student_name.Text);

                experiencesArrary.Remove(companyToDeleted);

                string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);

                File.WriteAllText(jsonFile, output);
                load_table();
                MessageBox.Show("Delete Successfully student result");

                txt_teacher_sgpa.Text   = "";
                cmb_teacher_course.Text = "";
                cmb_student_name.Text   = "";
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #11
0
        /// <summary>
        /// Is this a child build job.  If so return the ID of the parent job and base url
        /// </summary>
        internal static bool IsChildJob(JArray actions, out string baseUrl, out int parentBuildId)
        {
            baseUrl       = null;
            parentBuildId = 0;

            var obj = actions.FirstOrDefault(x => x["causes"] != null);

            if (obj == null)
            {
                return(false);
            }

            var array = (JArray)obj["causes"];

            if (array.Count == 0)
            {
                return(false);
            }

            var data = array[0];

            baseUrl       = data.Value <string>("upstreamUrl");
            parentBuildId = data.Value <int>("upstreamBuild");
            return(baseUrl != null && parentBuildId != 0);
        }
Example #12
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            JObject jo     = JObject.Load(reader);
            var     schema = JsonConvert.DeserializeObject <Schema>(jo.ToString(),
                                                                    GetSettings(serializer));

            var requiredList = new List <string>();
            //Per JSON schema 4.0, each node uses the "IsRequired" field (an array) to call out mandatory properties.
            var requiredProperties = new JArray(schema.Required);

            foreach (var requiredProperty in requiredProperties)
            {
                requiredList.Add((string)requiredProperty);
            }
            schema.Required = requiredList;
            if (schema.Properties != null)
            {
                foreach (var key in schema.Properties.Keys)
                {
                    Schema value          = schema.Properties[key];
                    bool   inRequiredList = (requiredProperties.FirstOrDefault(p => (string)p == key) != null);
                    value.IsRequired = inRequiredList;
                }
            }

            return(schema);
        }
Example #13
0
        public static Member GetMemberById(string idTrip, string idMember)
        {
            var result = new Member();

            string jsonFilePath = "./Data/trips.json";
            var    json         = File.ReadAllText(jsonFilePath);

            try
            {
                JArray trips        = JArray.Parse(json);
                var    tripDetail   = trips.FirstOrDefault(obj => obj["Id"].Value <String>() == idTrip);
                JArray membersArray = (JArray)tripDetail["Members"];

                var memberToGet = membersArray.FirstOrDefault(obj => obj["Id"].Value <string>() == idMember);
                result.Id       = memberToGet["Id"].ToString();
                result.Name     = memberToGet["Name"].ToString();
                result.Avatar   = memberToGet["Avatar"].ToString();
                result.Donation = memberToGet["Donation"].ToString();
            }
            catch (Exception)
            {
                throw;
            }

            return(result);
        }
Example #14
0
        void Delete()
        {
            var json = File.ReadAllText(p2);

            try
            {
                var    jObject      = JObject.Parse(json);
                JArray FacultyArray = (JArray)jObject["Faculties"];
                JArray studentArray = (JArray)jObject["students"];
                var    Name         = this.textBox10.Text.ToString();


                var StudentDeleted  = studentArray.FirstOrDefault(obj => obj["fac"].Value <String>() == Name.ToString());
                var FacultyoDeleted = FacultyArray.FirstOrDefault(obj => obj.Value <String>() == Name.ToString());

                FacultyArray.Remove(FacultyoDeleted);
                studentArray.Remove(StudentDeleted);

                string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(p2, output);
                MessageBox.Show("Deleted Successfully!!");
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #15
0
        public static Expense GetExpenseById(string idTrip, string idExpense)
        {
            var result = new Expense();

            string jsonFilePath = "./Data/trips.json";
            var    json         = File.ReadAllText(jsonFilePath);

            try
            {
                JArray trips         = JArray.Parse(json);
                var    tripDetail    = trips.FirstOrDefault(obj => obj["Id"].Value <String>() == idTrip);
                JArray expensesArray = (JArray)tripDetail["Expenses"];

                var expenseToGet = expensesArray.FirstOrDefault(obj => obj["Id"].Value <string>() == idExpense);
                result.Id   = expenseToGet["Id"].ToString();
                result.Name = expenseToGet["Name"].ToString();
                result.Cost = expenseToGet["Cost"].ToString();
            }
            catch (Exception)
            {
                throw;
            }

            return(result);
        }
        private void btn_admin_delete_Click(object sender, EventArgs e)
        {
            var json = File.ReadAllText(jsonFile);

            try
            {
                var    jObject           = JObject.Parse(json);
                JArray experiencesArrary = (JArray)jObject["admin"];


                var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["id"].Value <string>() == txt_admin_user_name.Text);

                experiencesArrary.Remove(companyToDeleted);

                string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(jsonFile, output);

                LoadAdminData();

                MessageBox.Show("Delete Successfully admin");
                txt_admin_pass.Text      = "";
                txt_admin_user_name.Text = " ";
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #17
0
        /// <summary>
        /// Check that each book's quantity in the basket can be provided by the store.
        /// </summary>
        /// <param name="basket">List of books.</param>
        /// <exception cref="NotEnoughInventoryException">The store (inventory) can't fulfill the order.</exception>
        private void CheckInventoryQuantities(IEnumerable <INameQuantity> basket)
        {
            JArray inventory = (JArray)StoreData["Catalog"];
            var    missing   = new List <NameQuantity>();

            foreach (var fromBasket in basket)
            {
                var inInventory = inventory.FirstOrDefault(book =>
                                                           book.Value <string>("Name") == fromBasket.Name);

                if (inInventory == null)
                {
                    missing.Add(new NameQuantity(
                                    fromBasket.Name,
                                    fromBasket.Quantity));
                }
                else
                {
                    int maxQuantity = inInventory.Value <int>("Quantity");

                    if (fromBasket.Quantity > maxQuantity)
                    {
                        missing.Add(new NameQuantity(
                                        fromBasket.Name,
                                        fromBasket.Quantity - maxQuantity));
                    }
                }
            }

            if (missing.Count > 0)
            {
                throw new NotEnoughInventoryException(missing);
            }
        }
        private static void ConvertScheduledTime(JArray history)
        {
            if (history == null)
            {
                return;
            }

            var orchestrationStartedEvent = history.FirstOrDefault(h => h.Value <string>("EventType") == "ExecutionStarted");

            foreach (var e in history)
            {
                if (e["ScheduledTime"] != null)
                {
                    // Converting to UTC and explicitly formatting as a string (otherwise default serializer outputs it as a local time)
                    var scheduledTime = e.Value <DateTime>("ScheduledTime").ToUniversalTime();
                    e["ScheduledTime"] = scheduledTime.ToString("o");

                    // Also adding DurationInMs field
                    var timestamp = e.Value <DateTime>("Timestamp").ToUniversalTime();
                    var duration  = timestamp - scheduledTime;
                    e["DurationInMs"] = duration.TotalMilliseconds;
                }

                // Also adding duration of the whole orchestration
                if (e.Value <string>("EventType") == "ExecutionCompleted" && orchestrationStartedEvent != null)
                {
                    var scheduledTime = orchestrationStartedEvent.Value <DateTime>("Timestamp").ToUniversalTime();
                    var timestamp     = e.Value <DateTime>("Timestamp").ToUniversalTime();
                    var duration      = timestamp - scheduledTime;
                    e["DurationInMs"] = duration.TotalMilliseconds;
                }
            }
        }
Example #19
0
        private TwitchVideo GetTwitchVideoFromId(string id)
        {
            using (WebClient webClient = CreateApiWebClient())
            {
                try
                {
                    webClient.QueryString.Add("id", id);

                    string result = webClient.DownloadString(VIDEOS_URL);

                    JObject videosResponseJson = JObject.Parse(result);

                    if (videosResponseJson != null)
                    {
                        JArray videosJson = videosResponseJson.Value <JArray>("data");

                        if (videosJson != null)
                        {
                            JToken videoJson = videosJson.FirstOrDefault();

                            if (videoJson != null)
                            {
                                return(ParseVideo(videoJson));
                            }
                        }
                    }
                }
                catch (WebException ex)
                {
                    if (ex.Response is HttpWebResponse resp && resp.StatusCode == HttpStatusCode.NotFound)
                    {
                        return(null);
                    }
Example #20
0
        //Deletar Pessoa
        public void DeletarPessoa(Pessoa pessoa, string arquivoJson)
        {
            var json = File.ReadAllText(arquivoJson);

            try
            {
                var    jObject           = JObject.Parse(json);
                JArray arrayExperiencias = (JArray)jObject["pessoas"];

                if (!string.IsNullOrEmpty(pessoa.CPF))
                {
                    var nomePessoa     = string.Empty;
                    var PessoaADeletar = arrayExperiencias.FirstOrDefault(obj => obj["CPF"].Value <string>() == pessoa.CPF);

                    arrayExperiencias.Remove(PessoaADeletar);

                    string saida = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
                    File.WriteAllText(arquivoJson, saida);
                }
                else
                {
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #21
0
        private void DeleteCompany()
        {
            var json = File.ReadAllText(jsonFile);

            try
            {
                var    jObject           = JObject.Parse(json);
                JArray experiencesArrary = (JArray)jObject["experiences"];
                Console.Write("Enter Company ID to Delete Company : ");
                var companyId = Convert.ToInt32(Console.ReadLine());

                if (companyId > 0)
                {
                    var companyName      = string.Empty;
                    var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["companyid"].Value <int>() == companyId);

                    experiencesArrary.Remove(companyToDeleted);

                    string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
                    File.WriteAllText(jsonFile, output);
                }
                else
                {
                    Console.Write("Invalid Company ID, Try Again!");
                    UpdateCompany();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #22
0
        public List <InicializacionTradeMark> DeleteTM()
        {
            var jsonfile = @"C:\Users\axel.lautaro.umansky\source\repos\Practica_SoloDeportes\Practica_SoloDeportes\Jsons\TradeMarkjson.json";
            var json     = File.ReadAllText(jsonfile);

            try
            {
                var    DeleteTM  = JObject.Parse(json);
                JArray ArrayJSon = (JArray)DeleteTM["TradeMark"];
                var    TMID      = 17;
                if (TMID > 0)
                {
                    var TMDes = string.Empty;
                    var TMDE  = ArrayJSon.FirstOrDefault(obj => obj["id"].Value <int>() == TMID);
                    ArrayJSon.Remove(TMDE);
                    String output = Newtonsoft.Json.JsonConvert.SerializeObject(DeleteTM, Newtonsoft.Json.Formatting.Indented);
                    File.WriteAllText(jsonfile, output);
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(null);
        }
Example #23
0
        private static JToken GetGameData()
        {
            string datFilePath = GetDatFile();

            if (!string.IsNullOrEmpty(datFilePath) && File.Exists(datFilePath))
            {
                string jsonData = File.ReadAllText(datFilePath);
                if (AssetsUtility.IsValidJson(jsonData))
                {
                    JToken games = JsonConvert.DeserializeObject <JToken>(jsonData);
                    if (games != null)
                    {
                        JArray installationListArray = games["InstallationList"].Value <JArray>();
                        if (installationListArray != null)
                        {
                            return(installationListArray.FirstOrDefault(game => string.Equals(game["AppName"].Value <string>(), "Fortnite")));
                        }

                        DebugHelper.WriteLine("Fortnite not found in .dat file");
                    }
                }
            }

            return(null);
        }
Example #24
0
        private static void MergeSortedPartialsWithDefaultConfig(int sorterPageId, string sorterPropertyAlias, string documentTypeAlias, HashSet <string> partials)
        {
            JObject config = Config.GetConfiguration(sorterPageId, sorterPropertyAlias);

            if (config != null)
            {
                JArray docTypes = config[Constants.Json.DocTypes] as JArray;

                if (docTypes != null)
                {
                    JToken docType = docTypes.FirstOrDefault(d => (string)d[Constants.Json.Alias] == documentTypeAlias);

                    if (docType != null)
                    {
                        JArray defaultPartials = docType[Constants.Json.Partials] as JArray;

                        if (defaultPartials != null)
                        {
                            foreach (JToken partial in defaultPartials)
                            {
                                string partialName = (string)partial[Constants.Json.Alias];

                                if (!partials.Contains(partialName))
                                {
                                    partials.Add(partialName);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #25
0
        public static Place GetPlaceById(string idTrip, string idPlace)
        {
            var result = new Place();

            string jsonFilePath = "./Data/trips.json";
            var    json         = File.ReadAllText(jsonFilePath);

            try
            {
                JArray trips       = JArray.Parse(json);
                var    tripDetail  = trips.FirstOrDefault(obj => obj["Id"].Value <String>() == idTrip);
                JArray placesArray = (JArray)tripDetail["Places"];

                var placeToGet = placesArray.FirstOrDefault(obj => obj["Id"].Value <string>() == idPlace);
                result.Id          = placeToGet["Id"].ToString();
                result.Name        = placeToGet["Name"].ToString();
                result.Avatar      = placeToGet["Avatar"].ToString();
                result.Address     = placeToGet["Address"].ToString();
                result.Description = placeToGet["Description"].ToString();
                result.Start       = placeToGet["Start"].ToString();
                result.End         = placeToGet["End"].ToString();
            }
            catch (Exception)
            {
                throw;
            }

            return(result);
        }
Example #26
0
        public IActionResult SaveResource([FromBody] dynamic jsonData, string id, string org, string app)
        {
            JObject json = jsonData;

            // Sort resource texts by id
            JArray resources = json["resources"] as JArray;
            JArray sorted    = new JArray(resources.OrderBy(obj => obj["id"]));

            json["resources"].Replace(sorted);

            // updating application metadata with appTitle.
            JToken appTitleToken = resources.FirstOrDefault(x => x.Value <string>("id") == "ServiceName");

            if (!(appTitleToken == null))
            {
                string appTitle = appTitleToken.Value <string>("value");
                _repository.UpdateAppTitle(org, app, id, appTitle);
            }

            _repository.SaveResource(org, app, id, json.ToString());

            return(Json(new
            {
                Success = true,
                Message = "Språk lagret",
            }));
        }
Example #27
0
        public static bool RemoveExpense(string idTrip, string idExpense)
        {
            var result = true;

            string jsonFilePath = "./Data/trips.json";
            var    json         = File.ReadAllText(jsonFilePath);

            try
            {
                JArray trips         = JArray.Parse(json);
                var    tripDetail    = trips.FirstOrDefault(obj => obj["Id"].Value <String>() == idTrip);
                JArray expensesArray = (JArray)tripDetail["Expenses"];

                var expenseToDelete = expensesArray.FirstOrDefault(obj => obj["Id"].Value <string>() == idExpense);
                expensesArray.Remove(expenseToDelete);

                string newJsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(trips,
                                                                                   Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(jsonFilePath, newJsonResult);
            }
            catch (Exception)
            {
                throw;
            }

            return(result);
        }
Example #28
0
        /// <summary>
        /// 坐标转换
        /// </summary>
        /// <param name="longitude">原始经度</param>
        /// <param name="latitude">原始纬度</param>
        /// <param name="xlongitude">转化经度</param>
        /// <param name="xlatitude">转化纬度</param>
        /// <returns></returns>
        public void ConvertCoord(decimal longitude, decimal latitude, out decimal xlongitude, out decimal xlatitude)
        {
            xlongitude = 0;
            xlatitude  = 0;
            string coord  = longitude + "," + latitude;
            string url    = string.Format("{0}?&coords={1}&ak={2}&from={3}&to={4}&output={5}", _url, coord, _ak, _from, _to, "json");
            string result = RequestUtil.Get(url);

            if (!string.IsNullOrEmpty(result))
            {
                dynamic resdata = JsonConvert.DeserializeObject <dynamic>(result);
                if (resdata != null)
                {
                    int status = resdata.status ?? -1;
                    if (status == 0)
                    {
                        JArray jarray = JArray.FromObject(resdata.result) ?? new JArray();
                        if (jarray.Count > 0)
                        {
                            dynamic jitem = jarray.FirstOrDefault();
                            if (jitem != null)
                            {
                                xlongitude = jitem.x ?? 0;
                                xlatitude  = jitem.y ?? 0;
                            }
                        }
                    }
                }
            }
        }
Example #29
0
        public static bool InsertImage(string idTrip, ImageTrip imageEntered)
        {
            var    result       = true;
            string jsonFilePath = "./Data/trips.json";
            var    json         = File.ReadAllText(jsonFilePath);

            try
            {
                JArray trips        = JArray.Parse(json);
                var    tripDetail   = trips.FirstOrDefault(obj => obj["Id"].Value <String>() == idTrip);
                JArray imagesArrary = (JArray)tripDetail["Images"];

                var newImageString  = Newtonsoft.Json.JsonConvert.SerializeObject(imageEntered);
                var newImageJObject = JObject.Parse(newImageString);
                imagesArrary.Add(newImageJObject);

                string newJsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(trips,
                                                                                   Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(jsonFilePath, newJsonResult);
            }
            catch (Exception)
            {
                throw;
            }

            return(result);
        }
Example #30
0
        //deletar empresa
        public void DeletarEmpresa(string arquivoJson)
        {
            var json = File.ReadAllText(arquivoJson);

            try
            {
                var    jObject           = JObject.Parse(json);
                JArray arrayExperiencias = (JArray)jObject["experiencias"];
                Write("Informe o ID da Empresa a deletar : ");
                var empresaId = Convert.ToInt32(Console.ReadLine());

                if (empresaId > 0)
                {
                    var nomeEmpresa     = string.Empty;
                    var empresaADeletar = arrayExperiencias.FirstOrDefault(obj => obj["empresaid"].Value <int>() == empresaId);

                    arrayExperiencias.Remove(empresaADeletar);

                    string saida = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
                    File.WriteAllText(arquivoJson, saida);
                }
                else
                {
                    Write("O ID da empresa é inválido, tente novamente!");
                    AtualizarEmpresa(arquivoJson);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }