public void CanParseIntoJObjectThrowsWithNonJSON() { JSONModel model = new JSONModel(); string testString = "[NotJSON"; model.LoadJSONFromString(testString); }
private JSONModel PrepareModel() { JSONModel model = new JSONModel(); model.LoadJSONFromURL(testURL); return(model); }
public IList <BetEasyModel> Transform(FileInfo file) { IList <BetEasyModel> modelList = new List <BetEasyModel>(); using (StreamReader r = new StreamReader(file.FullName)) { var json = r.ReadToEnd(); JSONModel jsonModel = JsonConvert.DeserializeObject <JSONModel>(json); if (jsonModel != null && jsonModel.RawData != null && jsonModel.RawData.Markets != null) { List <Market> markets = jsonModel.RawData.Markets; foreach (var market in markets) { var selections = market.Selections.Select(t => new { t.Price, t.Tags.name, t.Id }).ToList(); foreach (var selection in selections) { BetEasyModel model = new BetEasyModel(); model.HorseName = selection.name; model.Price = selection.Price; model.Id = selection.Id; modelList.Add(model); } } } } return(modelList); }
public void CanLoadStringFromURL() { JSONModel model = new JSONModel(); string expected = LoadTestStringFromURL(); string result = JSONModel.LoadStringFromURL(testURL); Assert.AreEqual(expected, result); }
/// <summary> /// Action to reset App's State /// </summary> private void AppResetCommand() { jsonModel.Dispose(); jsonModel = new JSONModel(); SomeText = "Start over!"; ButText = "Push me!"; ProgressVal = 0; }
public void CanParseIntoJObject() { JSONModel model = new JSONModel(); string testString = LoadTestStringFromURL(); model.LoadJSONFromString(testString); Assert.IsNotNull(model.LoadedJSON); string expected = LoadTestStringFromFile("../../full_json.json"); Assert.AreEqual(expected, model.ToString()); }
static void Main(string[] args) { XMLProcess xMLProcess = new XMLProcess(Directory.GetCurrentDirectory() + "\\XML\\New Text Document.XML"); JSONModel jSON = xMLProcess.XMLReader(); var options = new JsonSerializerOptions { WriteIndented = true }; string jsonString = JsonSerializer.Serialize <JSONModel>(jSON, options); Console.WriteLine(jsonString); Console.ReadLine(); }
public void CanFindViewsByClassNameWillNotFindMismatches() { JSONModel model = PrepareModel(); IEnumerable <JToken> tokens = model.SearchJSON("NotPresent"); int count = 0; foreach (JToken token in tokens) { count++; } Assert.AreEqual(0, count); }
public ActionResult GenerateChordSheet([FromBody] JSONModel data) { try { var chordList = new List <string>(JsonConvert.DeserializeObject <List <string> >(data.Json)); var logic = new Logic(); string svgXml; svgXml = logic.GeneratePianoChartSvgXml(chordList); return(Json(svgXml)); } catch { //return Json("Something went wrong generating chord chart. Please try again."); return(Json("Failed")); } }
public ActionResult Create([FromBody] JSONModel data) { try { CreditCardModel c = JsonConvert.DeserializeObject <CreditCardModel>(data.Json); var businessData = new CreditCardDebtBL(); businessData.SaveData(c); return(RedirectToAction(nameof(Index))); } catch (Exception e) { string err = e.ToString(); return(View()); } }
// GET: Admin/JSONGallery public string GetJsonGallery(int?PageNumber, int?NumberOfItems) { //Set the page number and number of items from the request var _pageNumber = PageNumber; var _numberOfItems = NumberOfItems; var _numberOfPages = 0; //Retrieve gallery images and populate the gallery model var model = GalleryBLL.GetImageGallery((int)_pageNumber, (int)_numberOfItems, out _numberOfPages); var JsonString = new JSONModel(); JsonString.NumberOfPages = _numberOfPages; JsonString.Gallery = model; //Send JSON response to calling object return(JsonConvert.SerializeObject(JsonString)); }
public JsonResult Json() { GeekopolyContext _context = new GeekopolyContext(); List <Field> fields = _context.Fields.ToList(); List <Property> properties = _context.Properties.ToList(); properties = _context.Properties.ToList(); List <Category> categories = _context.Categories.ToList(); List <Player> players = _context.Players.ToList(); categories = _context.Categories.ToList(); fields = _context.Fields.ToList(); players = _context.Players.ToList(); JSONModel jsonmodel = new JSONModel(); jsonmodel.category_list = categories; jsonmodel.field_list = fields; jsonmodel.property_list = properties; jsonmodel.player_list = players; return(Json(jsonmodel)); }
public void CanFindViewsByClassName() { JSONModel model = PrepareModel(); IEnumerable <JToken> tokens = model.SearchJSON("Input"); int count = 0; JToken first = null; foreach (JToken token in tokens) { if (count == 0) { first = token; } count++; } Assert.AreEqual(26, count); string expectedString = LoadTestStringFromFile("../../first_class_input.json"); Assert.AreEqual(expectedString, first.ToString()); }
public void CanFindViewsByIdentifier() { JSONModel model = PrepareModel(); IEnumerable <JToken> tokens = model.SearchJSON("Button#apply"); int count = 0; JToken first = null; foreach (JToken token in tokens) { if (count == 0) { first = token; } count++; } Assert.AreEqual(1, count); string expectedString = LoadTestStringFromFile("../../button_apply.json"); Assert.AreEqual(expectedString, first.ToString()); }
static void Main(string[] args) { string server, projectId, username, password; if (args == null || args.Length < 4) { Console.WriteLine("Missing arguments."); return; } else { server = args[0]; projectId = args[1]; username = args[2]; password = args[3]; } Console.WriteLine("----------------------NR CSV to API----------------------"); Console.WriteLine("Authenticating..."); DataAPIClient apiClient = new DataAPIClient(new System.Net.Http.HttpClient(), true) { BaseUri = new Uri(server) }; apiClient.HttpClient.Timeout = Timeout.InfiniteTimeSpan; //authorize TokenResponse tokenResponse = AccountExtensions.GetToken(apiClient.Account, new TokenRequest(username, password)); apiClient.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.AccessToken); if (tokenResponse.AccessToken == null || tokenResponse.AccessToken == "") { Console.WriteLine("AUTHENTICATION FAILED"); return; } else { Console.WriteLine("Authentication COMPLETED!"); } Console.WriteLine("Mapping data from CSV..."); string filelocation = Path.Combine(Environment.CurrentDirectory + "\\..\\..\\Data\\csv\\test.csv"); //Mapping CSV data into C# object List <CSVData> csvData = DataMapper.getMappedDataFromCSV(filelocation); JSONModel uploadData = new JSONModel(); //Mapping MetaData for JSONModel DataMapper.getMetadataForImport().ForEach(uploadData.MetaData.Add); //Mapping CaseData for JSONModel DataMapper.getCasedataForImport(csvData).ForEach(uploadData.CaseData.Add); //Serializing JSONModel C# Object to JSON Object var json = new JavaScriptSerializer().Serialize(uploadData); Console.WriteLine("Mapping COMPLETED!"); //Import API of JSON Object data Console.WriteLine("Importing data to the server"); dynamic importInput = json; Response importResponse = ImportExtensions.PostImport(apiClient.Import, importInput, projectId); if (importResponse.Data == null || tokenResponse.AccessToken == "") { Console.WriteLine("DATA IMPORT FAILED"); return; } else { Console.WriteLine("Import COMPLETED!"); } //GET Import Batches API PagedInputOfBatchFilterInput batchFilterInput = new PagedInputOfBatchFilterInput() { Paging = new PagingInput() { PageNumber = 1, PageSize = 10 } }; Response batches = ImportExtensions.Batches(apiClient.Import, batchFilterInput, projectId); //Isolating ImportId for activation from batches.Data string var Ids = batches.Data.ToString(); Ids = Ids.Substring(Ids.IndexOf("ImportID") + 11, Ids.Length - (Ids.IndexOf("ImportID") + 11)); Ids = Ids.Substring(0, Ids.IndexOf("\r") - 1); string[] parsedIds = Ids.Split(','); List <long?> IdsToActivates = new List <long?>(); foreach (string s in parsedIds) { if (Int32.TryParse(s, out int result)) { IdsToActivates.Add(result); } } Console.WriteLine("Activating data on the server..."); //Activate Import Batches API ActivateInput activateInput = new ActivateInput() { IdsToActivate = IdsToActivates, IdsToDeactivate = new List <long?>() }; ActivationExtensions.Activate(apiClient.Activation, activateInput, projectId); //GET Activation History API PagedInputOfActivationHistoryFilterInput historyFilterInput = new PagedInputOfActivationHistoryFilterInput() { Paging = new PagingInput() { PageNumber = 1, PageSize = 10 } , Sorting = new SortingInput() { OrderBy = "ActivationTime", Ascending = false } }; Response activationHistory = ActivationExtensions.History(apiClient.Activation, historyFilterInput, projectId); //Isolating last history record for valdiation var history = activationHistory.Data.ToString(); history = history.Substring(history.IndexOf("ActivationTime") + 18, history.Length - (history.IndexOf("ActivationTime") + 18)); history = history.Substring(0, history.IndexOf("\r") - 3); if (DateTime.TryParse(history, out DateTime lastHistory)) { if (lastHistory > DateTime.Now.AddMinutes(-60)) { Console.WriteLine("Data activation COMPLETED!"); } else { Console.WriteLine("DATA ACTIVATION FAILED"); return; } } else { Console.WriteLine("DATA ACTIVATION FAILED"); return; } }
public UrlProcessor(Controller aController, JSONModel aModel) { controller = aController; model = aModel; }
public MainMenuProcessor(Controller aController, JSONModel aModel) { model = aModel; controller = aController; }
public Publisher() { // we prepare an instance of Data Model to provide some data jsonModel = new JSONModel(); }
public void LoadStringThrowsWithBadURL() { JSONModel model = new JSONModel(); string result = JSONModel.LoadStringFromURL("bad"); }
public JSONModel XMLReader() { int cdsCount = 0; double pricesSum = 0; List <string> countries = new List <string>(); int minYear = 0; int maxYear = 0; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(PathToXML); XmlElement catalogeElement = xmlDocument.DocumentElement; foreach (XmlNode cds in catalogeElement) { cdsCount++; foreach (XmlNode chiledCdNode in cds.ChildNodes) { if (chiledCdNode.Name == "COUNTRY") { if (!countries.Contains(chiledCdNode.InnerText)) { countries.Add(chiledCdNode.InnerText); } } if (chiledCdNode.Name == "PRICE") { if (double.TryParse(chiledCdNode.InnerText, out double price)) { pricesSum += price; } } if (chiledCdNode.Name == "YEAR") { if (int.TryParse(chiledCdNode.InnerText, out int year)) { if (minYear == 0 || year <= minYear) { minYear = year; } else if (maxYear == 0 || year >= maxYear) { maxYear = year; } } } } } JSONModel model = new JSONModel { CdsCount = cdsCount, PricesSum = String.Format("{0:C2}", pricesSum), Countries = countries.ToArray(), MinYear = minYear.ToString(), MaxYear = maxYear.ToString() }; return(model); }
static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); //Congifure appsettings for reading json var configuration = builder.Build(); string SampleJson = configuration["SampleJson"];//Read Json from Config string MaskedJson = configuration["MaskedJson"]; Console.WriteLine(MaskedJson); Console.WriteLine(MaskedJson); try { var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true }; var jsonString = File.ReadAllText(SampleJson); //Read the json and Deserialize var jsonElement = System.Text.Json.JsonSerializer.Deserialize <JSONModel>(jsonString); JToken token = JToken.Parse(jsonString); var jsonPaths = File.ReadAllText(MaskedJson); JSONModel model = JsonConvert.DeserializeObject <JSONModel>(jsonString); MaskedJson maskedDataElements = JsonConvert.DeserializeObject <MaskedJson>(jsonString); MaskedJson maskedJson = new MaskedJson(); //Console.WriteLine(model); //Console.WriteLine(jsonElement); var data = jsonElement.repositoryLog.moqTransactions[0].returnData.data; //JsonHelper.ObscureMatchingValues(data, jsonPaths); //Compare method ExampleLogger.Log(token.ToString(Formatting.None)); var model2 = JsonConvert.DeserializeObject <JArray>(data); //Loop through Json to compare against Mask Objects foreach (JObject content in model2.Children <JObject>()) { foreach (JProperty prop in content.Properties()) { foreach (string arr in prop.Last) { if (prop.Last.Equals(maskedDataElements)) { prop.Value = "xxx"; //Todo - Change the logic to mask Console.WriteLine(prop.Name + " - " + prop.Value); } //Console.WriteLine(prop.Name); } Console.WriteLine(prop.Name + " - " + prop.Value); Console.ReadLine(); //JsonHelper.ObscureMatchingValues(prop.Name, jsonPaths); } } } catch (Exception ex) { //Log Exception or write to Console } }