public static T GetSettings <T>(string fileLocation) { T _result = default(T); string stringified = ""; var json = new JSONProcessor(); try { stringified = FileReader.ReadFileIntoString(fileLocation); } catch (Exception ex) { Console.WriteLine(ex); } try { _result = json.ConvertJsonToType <T>(stringified); } catch (Exception ex) { Console.WriteLine(json.ErrorMessages[0], " [FilePath: " + fileLocation + "]"); Console.WriteLine(ex); } return(_result); }
public string[] GetOCR(string jsonStrokes, string url, string key, string language) { var configuration = new ConfigurationBuilder().AddJsonFile("config.json").Build(); if (configuration != null) { string endpoint = configuration["endpoint"]; string subscriptionKey = key; //configuration["key"]; string lang = language; //configuration["language"]; jsonStrokes = jsonStrokes.Replace("\"language\": \"en-US\"", "\"language\": \"" + lang + "\""); string requestData = jsonStrokes; string apiAddress = url; using (HttpClient client = new HttpClient { BaseAddress = new Uri(apiAddress) }) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey); var content = new StringContent(requestData, Encoding.UTF8, "application/json"); var res = client.PutAsync(endpoint, content).Result; if (res.IsSuccessStatusCode) { string result = res.Content.ReadAsStringAsync().Result; InkRecognitionRoot root = JSONProcessor.ParseInkRecognizerResponse(result); if (root != null) { List <InkLine> lstLines = root.GetLines().ToList(); string tekst = string.Empty; foreach (InkLine line in lstLines) { tekst += tekst + line.RecognizedText; } string[] words = lstLines.Select(q => q.RecognizedText).ToArray(); return(words); } else { throw new Exception("Can't parse response"); } } else { throw new Exception($"ErrorCode: {res.StatusCode}"); } } } else { throw new Exception("Can't parse config file"); } }
static void Main(string[] args) { // CSV Processor Test CSVProcessor csvProcessor = new CSVProcessor(TestCSVFilePath); List <List <string> > stringTable = csvProcessor.GetStringTable(); List <Credential> credentials = csvProcessor.ParseCredentialsFromFile(CSVProcessor.CSVFileFormat.KeePass, stringTable).ToList(); // JSON Processor Test JSONProcessor jsonProcessor = new JSONProcessor(TestJSONFilePath); List <Credential> credentials1 = jsonProcessor.ParseCredentialsFromFile().ToList(); }
private void CheckFavorite() { if (JSONProcessor.CheckFavorite(movieInfo)) { setBtnFavToDelete(); } else { setBtnFavToAdd(); } }
public async Task <HttpResponseMessage> PutAsync(string jsonRequest) { var httpContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json"); var httpResponse = await httpClient.PutAsync(destinationUrl, httpContent); // Throw exception for malformed/unauthorized http requests if (httpResponse.StatusCode == HttpStatusCode.BadRequest || httpResponse.StatusCode == HttpStatusCode.NotFound || httpResponse.StatusCode == HttpStatusCode.Unauthorized) { var errorJson = await httpResponse.Content.ReadAsStringAsync(); var errDetail = JSONProcessor.ParseInkRecognitionError(errorJson); ThrowExceptionForHttpError(errDetail); } return(httpResponse); }
private void buttonImportFile_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.InitialDirectory = "C:\\"; openFileDialog.Filter = "Dashlane-Files (*.json)|*.json|KeePass-Files (*.csv)|*.csv"; openFileDialog.FilterIndex = 1; if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; List <Credential> userPasswords = new List <Credential>(); switch (openFileDialog.FilterIndex) { case 1: JSONProcessor jsonProcessor = new JSONProcessor(filePath); userPasswords = jsonProcessor.ParseCredentialsFromFile().ToList(); break; case 2: CSVProcessor csvProcessor = new CSVProcessor(filePath); userPasswords = csvProcessor. ParseCredentialsFromFile(CSVProcessor.CSVFileFormat.KeePass, csvProcessor.GetStringTable()).ToList(); break; } if (userPasswords.Count == 0) { return; } foreach (Credential credential in userPasswords) { credentialQueue.Enqueue(credential); } byte[] command = { (byte)SerialCommandLimiter.COMM_BEGIN, (byte)SerialCommand.COMM_GET_UNIQUE_ID, (byte)SerialCommandLimiter.COMM_END }; SerialSafeWrite(command, 3); } } }
public Person GetPerson(string id) { string resp = ""; if (client.Connected) { try { resp = SendRequest(new CommandObject("getPerson", id)); } catch (Exception) { throw; } } return(JSONProcessor.ParsePerson(resp)); }
static void Main(string[] args) { XMLProcessor xmlProc; JSONProcessor jsonProc; List <Horse> horses = new List <Horse>(); //Get list of all files in the path. (FeedData directory) string feedPath = Path.Combine(@"C:\Users\Manes\Desktop\BetEasy-Coding-Challenge\code-challenge\dotnet-code-challenge\FeedData"); string[] fileList = Directory.GetFiles(feedPath); foreach (string path in fileList) { //Fire the XML processor if (Path.GetExtension(path).Equals(".xml")) { xmlProc = new XMLProcessor(path); horses.AddRange(xmlProc.Process()); } //Fire the JSON processor if (Path.GetExtension(path).Equals(".json")) { jsonProc = new JSONProcessor(); horses.AddRange(jsonProc.Process(Path.GetFileName(path))); } } if (horses.Count > 0) { Console.WriteLine("********** HORSE LIST **********"); foreach (Horse horse in horses) { Console.WriteLine(horse.Name + " - " + horse.Price); } Console.WriteLine("********************************"); } else { Console.WriteLine("No horses found!"); } }
public async Task <HttpStatusCode> RecognizeAsync() { try { var requestJson = JSONProcessor.CreateInkRecognitionRequest(strokes.AsReadOnly()); var response = await httpManager.PutAsync(requestJson); var statusCode = response.StatusCode; if (statusCode == HttpStatusCode.OK) { var responseJson = await response.Content.ReadAsStringAsync(); root = JSONProcessor.ParseInkRecognizerResponse(responseJson); } return(statusCode); } catch (Exception e) { throw; } }
T IREST <T> .GetDataAsync(T payload) { //must meet minimum parts of an rec if ( !string.IsNullOrEmpty(payload.Address) && !string.IsNullOrEmpty(payload.City) && !string.IsNullOrEmpty(payload.Region) ) { string _strAddress = StringifyPayload(payload); var _requestUri = new UriBuilder(); _requestUri.Scheme = restProtocol; _requestUri.Host = restLink; _requestUri.Path = _strAddress.Replace(" ", "+"); var query = !string.IsNullOrEmpty(_strAddress) ? string.Concat("o=", responseFormat) : ""; query = !string.IsNullOrEmpty(restKey) ? query + string.Concat("&key=", restKey) : ""; _requestUri.Query = query; var _jsonText = CallProvider(_requestUri.ToString()); var json = new JSONProcessor(); json.PrepJSONSafely(_jsonText); if (json.IsJSONValid) { dynamic obj = json.ConvertJsonToType <dynamic>(_jsonText); if (obj.status == "OK") { if (obj["resourceSets"][0]["resources"][0]["entityType"].ToString() == "Address" || obj["resourceSets"][0]["resources"][0]["confidence"].ToString() == "High" || obj["resourceSets"][0]["resources"][0]["confidence"].ToString() == "Medium" ) { //update model payload.Latitude = Single.Parse(obj["resourceSets"][0]["resources"][0]["geocodePoints"][0]["coordinates"][0].ToString()); payload.Longitude = Single.Parse(obj["resourceSets"][0]["resources"][0]["geocodePoints"][0]["coordinates"][1].ToString()); payload.LocationType = obj["resourceSets"][0]["resources"][0]["entityType"].ToString(); payload.ServiceAPIEndPointUID = restUID; } else { //TODO: add bad match code // payload.LocationType = "no_good_match"; //TODO: a retry operation should be added (but lower priority than changed RecordSet) } //} //else //if not OK //{ // //payload.LocationType = obj.status; //} //else if (obj.status == "ZERO_RESULTS") //{ //non-existant rec //} //else if (obj.status == "OVER_QUERY_LIMIT") //{ // //} //else if (obj.status == "REQUEST_DENIED") //{ // //} //else if (obj.status == "INVALID_REQUEST") //{ // //} //else if (obj.status == "UNKNOWN_ERROR") //{ // } } } return(payload); }
private void AddFav_Click(object sender, RoutedEventArgs e) { JSONProcessor.AddToFavorites(movieInfo); setBtnFavToDelete(); }
private void DeleteFav(object sender, RoutedEventArgs e) { JSONProcessor.DeleteFromFavorites(movieInfo); setBtnFavToAdd(); }
T IREST <T> .GetDataAsync(T payload) { //must meet minimum parts of an rec if ( !string.IsNullOrEmpty(payload.Address) && !string.IsNullOrEmpty(payload.City) && !string.IsNullOrEmpty(payload.Region) ) { string _strAddress = StringifyPayload(payload); var _requestUri = new UriBuilder(); _requestUri.Scheme = restProtocol; _requestUri.Host = restLink; _requestUri.Path = responseFormat; var query = !string.IsNullOrEmpty(_strAddress) ? string.Concat("address=", _strAddress) : ""; query = !string.IsNullOrEmpty(restKey) ? query + string.Concat("&key=", restKey) : ""; _requestUri.Query = query; var _jsonText = CallProvider(_requestUri.ToString()); var json = new JSONProcessor(); json.PrepJSONSafely(_jsonText); if (json.IsJSONValid) { dynamic obj = json.ConvertJsonToType <dynamic>(_jsonText); if (obj.status == "OK") { if (!json.IsPropertyInJSON(_jsonText, "PropertyName", "partial_match") || obj.results[0].geometry.location_type == "ROOFTOP" || obj.results[0].geometry.location_type == "RANGE_INTERPOLATED" //center of street block ) { //update model payload.Latitude = obj.results[0].geometry.location.lat; payload.Longitude = obj.results[0].geometry.location.lng; payload.LocationType = obj.results[0].geometry.location_type; payload.ServiceAPIEndPointUID = restUID; } else { //TODO: add bad match code payload.LocationType = "no_good_match"; //TODO: a retry operation should be added (but lower priority than changed RecordSet) } } else //if not OK { //payload.LocationType = obj.status; } //else if (obj.status == "ZERO_RESULTS") //{ //non-existant rec //} //else if (obj.status == "OVER_QUERY_LIMIT") //{ // //} //else if (obj.status == "REQUEST_DENIED") //{ // //} //else if (obj.status == "INVALID_REQUEST") //{ // //} //else if (obj.status == "UNKNOWN_ERROR") //{ // //} } } return(payload); }
public favorites() { InitializeComponent(); lb_movies.ItemsSource = JSONProcessor.GetFavorites(); }