Reading and writting on appsettings.json - c#

I am trying to read and write a value on appsettings.json.It is called Refreshed_Token. I have found something on internet and it was very well explained as an example but i get only one error. Can you please guys help me thank you very much.
Worker.cs
public async Task request_refresh_token()
{
var client = new RestClient("https://accounts.zoho.eu/oauth/v2/token?grant_type=authorization_code&client_id=" +_config.Value.Zoho_Client_Id+ "&client_secret=" +_config.Value.Zoho_Client_Secret+ "&code=" +_config.Value.Zoho_Code);
var request = new RestRequest();
request.AddHeader("Cookie", "xxx; xxx; iamcsr=xxx");
RestResponse response = await client.PostAsync(request);
var result = JObject.Parse(response.Content);
var refresh_token = result["refresh_token"].Value<string>();
update_appsettings_json(refresh_token);
}
public void update_appsettings_json(string refresh_token)
{
var appSettingsPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
var json = File.ReadAllText(appSettingsPath);
var jsonSettings = new JsonSerializerSettings();
jsonSettings.Converters.Add(new ExpandoObjectConverter());
jsonSettings.Converters.Add(new StringEnumConverter());
dynamic config = JsonConvert.DeserializeObject<System.Dynamic.ExpandoObject>(json, jsonSettings);
config.Config.Zoho_Code = Zoho_Refreshed_Token.refresh_token;
var newJson = JsonConvert.SerializeObject(config, Formatting.Indented, jsonSettings);
File.WriteAllText(appSettingsPath, newJson);
}
appsetting.json file :
{
"Config": {
"LeadCustomerId": "4096",
"URL": "example.com",
"Token": "xxx",
"Contact_Custom_Id": "11249",
"Opportunity_Custom_Id": "11261",
"Account_Custom_Id": "13397",
"Task_Custom_Id": "16876",
"Call_Custom_Id": "17033",
"Meeting_Custom_Id": "17098",
"Zoho_Client_Id": "xxx",
"Zoho_Client_Secret": "xxx",
"Zoho_Code": "xxx",
"Zoho_Refreshed_Token": ""
}
}
Config.cd file is:
public class Config
{
public string LeadCustomerId { get; set; }
public string WeclappURL { get; set; }
public string Weclapp_Token { get; set; }
public string Contact_Custom_Id { get; set; }
public string Opportunity_Custom_Id { get; set; }
public string Account_Custom_Id { get; set; }
public string Task_Custom_Id { get; set; }
public string Call_Custom_Id { get; set; }
public string Meeting_Custom_Id { get; set; }
public string Zoho_Client_Id { get; set; }
public string Zoho_Client_Secret { get; set; }
public string Zoho_Code { get; set; }
public string Zoho_Refreshed_Token { get; set; }
}
The error i get is this: The Zoho_Refreshed_Token does not exist in the current context
Thank you for your time!

Related

Getting Http Error Code 411 : Length Required

When I am trying to upload a file using following code I am receiving Length Required error. Please note that if I am uploading a TEXT file then I don't see any issues. But when I upload WORD or PDF I am seeing the error. FYI, I am able to see to Content-Length in my request header in both occasions. Any help would be much appreciated.
internal static class CreateFile
{
private static string _Server = "MyServer.com";
private static string _Database = "ACTIVE";
internal static async Task<string> CreateFileInFolder(string _AuthToken, string _FolderId, string _FileLocation)
{
// Force TLS 1.2 instead of the default value.
ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//folder creation URI
string _FileCreateUri = $"https://{_Server}/api/v2/customers/1/libraries/{_Database}/folders/{_FolderId}/documents";
FileInfo _FileDetails = new (_FileLocation);
string _Result = "";
FileRoot _FileRoot = new()
{
doc_profile = new FileProfile()
{
author = "ADMIN",
comment = "New Import",
default_security = "private",
name = _FileDetails.Name,
custom1 = "Test",
custom2 = "Test",
custom17 = "12345",
access = "full_access",
database = _Database,
size = _FileDetails.Length,
#class = "DOC",
type = "ACROBAT",
type_description = "",
wstype = "document"
},
audit = new FileAudit()
{
comments = "Test Import"
},
keep_locked = false,
warnings_for_required_and_disabled_fields = true
};
byte[] _FileBytes = File.ReadAllBytes(_FileDetails.FullName);
string _Boundary = $"----------{DateTime.Now.Ticks:x}";
MultipartFormDataContent _MultipartFormDataContent = new(_Boundary)
{
{
JsonContent.Create(_FileRoot), "profile"
},
{
new StreamContent(new MemoryStream(_FileBytes), _FileBytes.Length), "file"
}
};
_MultipartFormDataContent.Headers.Remove("Content-Type");
_MultipartFormDataContent.Headers.TryAddWithoutValidation("Content-Type", $"multipart/form-data; boundary={_Boundary}");
using (HttpClient _HttpClient = new())
{
//include authentication token in request header
_HttpClient.DefaultRequestHeaders.Add("X-Auth-Token", _AuthToken);
using (HttpResponseMessage _HttpResMsg = await _HttpClient.PostAsync(_FileCreateUri, _MultipartFormDataContent))
{
if (_HttpResMsg.StatusCode == HttpStatusCode.Created)
{
_Result = _HttpResMsg.Content.ReadAsStringAsync().Result;
}
}
}
//MessageBox.Show($"Json profile newly created folder: {_HttpResMsg.Content.ReadAsStringAsync().Result}", "New Folder Profile", MessageBoxButton.OK);
return _Result;
}
public class FileAudit
{
public string comments { get; set; }
}
public class FileProfile
{
public string author { get; set; }
public string access { get; set; }
public string comment { get; set; }
public string #class { get; set; }
public string database { get; set; }
public string default_security { get; set; }
public string name { get; set; }
public long size { get; set; }
public string type { get; set; }
public string type_description { get; set; }
public string wstype { get; set; }
public string custom1 { get; set; }
public string custom2 { get; set; }
public string custom17 { get; set; }
}
public class FileRoot
{
public FileProfile doc_profile { get; set; }
public FileAudit audit { get; set; }
public bool keep_locked { get; set; }
public bool warnings_for_required_and_disabled_fields { get; set; }
}
}
Tried to use HttpRequestMessage by setting Content-Length but again able to upload TEXT files but not WORD or PDF files.

Deserialization not filling my variables/response.data shows null

I want to put the jsonBody I get from the Rest API into this class construction.
Console.WriteLine(response.Data);
Somehow it only returns null.
This my whole code:
RestClient client = new RestClient("https://euterpe.webuntis.com/WebUntis/jsonrpc.do?school=HTL-Perg");
public void login()
{
var request = new RestRequest(Method.POST);
request.AddHeader("Content-type", "application/jason");
request.AddJsonBody(new
{
id = "ID",
method = "authenticate",
#params = new
{
user = "kung",
password = "foo",
client = "CLIENT"
},
jsonrpc = "2.0"
});
var response = this.client.Execute<AuthenticationResponse>(request);
Console.WriteLine(response.Data);
}
The request is working and I get the following return of the Rest API:
{
"jsonrpc":"2.0",
"id":"ID",
"result": {
"sessionId":"A173BECFB75F66123D6B678BE9745A29",
"personType":5,
"personId":1234,
"klasseId":123
}
}
Finally this are the two classes the response should get stored to, but the variables seem to stay empty:
public class AuthenticationResponse
{
[DeserializeAs(Name = "jsonrpc")]
public String Jsonrpc { get; set; }
[DeserializeAs(Name = "id")]
public int id { get; set; }
[DeserializeAs(Name = "result", Content=true)]
AuthenticationResult res { get; set; }
}
public class AuthenticationResult
{
[DeserializeAs(Name = "sessionId")]
string sessionId { get; set; }
[DeserializeAs(Name = "personType")]
int personType { get; set; }
[DeserializeAs(Name = "personId")]
int personId { get; set; }
[DeserializeAs(Name = "klasseId")]
int klasseId { get; set; }
}
Thanks for every advice.
I have taken a look at your code and tried it with WebUntis. Here is a working example as a console app. Especially important is the call to client.AddHandler Hope it helps solving your problem.
using RestSharp;
using RestSharp.Deserializers;
using System;
using System.Text;
namespace ConsoleApp3
{
internal class Program
{
private static RestClient client = new RestClient("https://euterpe.webuntis.com/WebUntis/jsonrpc.do?school=HTL-Perg");
public class AuthenticationResponse
{
[DeserializeAs(Name = "id")]
public string id { get; set; }
[DeserializeAs(Name = "result", Content = true)]
public AuthenticationResult result { get; set; }
}
public class AuthenticationResult
{
[DeserializeAs(Name = "sessionId")]
public string sessionId { get; set; }
[DeserializeAs(Name = "personType")]
public int personType { get; set; }
[DeserializeAs(Name = "personId")]
public int personId { get; set; }
[DeserializeAs(Name = "klasseId")]
public int klasseId { get; set; }
}
private static void Main(string[] args)
{
client.AddHandler(new JsonDeserializer(), "application/json-rpc");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-type", "application/json");
request.AddJsonBody(new
{
id = "ID",
method = "authenticate",
#params = new
{
user = "kung",
password = "foo",
client = "CLIENT"
},
jsonrpc = "2.0"
});
var response = client.Execute<AuthenticationResponse>(request);
var resp = Encoding.UTF8.GetString(response.RawBytes, 0, (int)response.ContentLength);
Console.WriteLine(response.Data);
}
}
}
Greetings,
Rainer.
Your AuthenticationResponse possibly needs to be
public class AuthenticationResponse
{
[DeserializeAs(Name = "id")]
public string id { get; set; }
[DeserializeAs(Name = "result")]
AuthenticationResult res { get; set; }
public string jsonrpc { get; set; } // Can remove if you dont need it.
}
Update
Based on your comment that this didn't work, please try to use Newtonsoft.Json to deserialize your result.
var response = client.Execute(request);
var deserialized = JsonConvert.DeserializeObject<AuthenticationResponse>(response.Content);
You would have to use JsonPropertyAttribute instead of DeserliazeAs in your class definition.
public class AuthenticationResponse
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("result")]
AuthenticationResult res { get; set; }
}
public class AuthenticationResult
{
[JsonProperty("sessionId")]
string sessionId { get; set; }
[JsonProperty("personType")]
int personType { get; set; }
[JsonProperty("personId")]
int personId { get; set; }
[JsonProperty("klasseId")]
int klasseId { get; set; }
}
Additional Option
You could also use RestSharp.Newtonsoft.Json which makes Newtonsoft.Json default serializer for RestSharp (and skipping the intermediate step).
In your Json there is nothing called "res" that is being returned .
This should fix your issue :
public class AuthenticationResponse
{
[DeserializeAs(Name = "jsonrpc")]
public String Jsonrpc {get;set;}
[DeserializeAs(Name = "id")]
public int Id { get; set; }
[DeserializeAs(Name = "result")]
AuthenticationResult Result { get; set; }
}

Read Json data from file

Hello i'm trying to read json data from a text file but it doesn't work.
when i try to get data from a website then it works fine.
Anyone know a solution to fix this problem ?
thanks in advance.
private void Form1_Load(object sender, EventArgs e)
{
string path = #"C:\Users\spacefrog\Documents\Visual Studio 2017\Projects\json_test_solution\json_test\bin\Debug\test.json";
// Stream stream = File.OpenRead(path);
WebClient client = new WebClient();
Stream stream = client.OpenRead("https://www.cryptocompare.com/api/data/coinlist/"); // works perfect
/*
Stream stream = client.OpenRead(path); // doesn't work
Stream stream = File.OpenRead(path); // doesn't work
*/
/* File Data content (same as website)
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
"LTC": {
"Id": "3808",
"Url": "/coins/ltc/overview",
"ImageUrl": "/media/19782/ltc.png",
"Name": "LTC",
"CoinName": "Litecoin",
"FullName": "Litecoin (LTC)",
"Algorithm": "Scrypt",
"ProofType": "PoW",
"SortOrder": "2"
}
...
},
"Type": 100
}
*/
StreamReader reader = new StreamReader(stream);
JObject json = JObject.Parse(reader.ReadLine());
stream.Close();
MessageBox.Show((string)json["Response"]);
}
JObject json = JObject.Parse(reader.ReadLine());
How should the JSON.NET Parser parse the first line? Looking at your comment, the first line seems to be
{
Does not look like a valid JSON object. Take a look at the ReadToEnd method.
By the way, you may want to use the StreamReader within a using scope.
You don't have to use a temp file to parse that json
WebClient webClient = new WebClient();
var json = webClient.DownloadString("https://www.cryptocompare.com/api/data/coinlist/");
var rootObj = JsonConvert.DeserializeObject<SOTest.RootObject>(json);
//OR var jObj = JObject.Parse(json);
if you really want to save to a file you can use
webClient.DownloadFile(url,filename);
or write the json above to a file
File.WriteAllText(filename, json);
or if you want to go the client.OpenRead way
var f = File.Create(filename);
stream.CopyTo(f);
public class SOTest
{
public class DataItem
{
public string Id { get; set; }
public string Url { get; set; }
public string ImageUrl { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
public string CoinName { get; set; }
public string FullName { get; set; }
public string Algorithm { get; set; }
public string ProofType { get; set; }
public string FullyPremined { get; set; }
public string TotalCoinSupply { get; set; }
public string PreMinedValue { get; set; }
public string TotalCoinsFreeFloat { get; set; }
public string SortOrder { get; set; }
}
public class RootObject
{
public string Response { get; set; }
public string Message { get; set; }
public string BaseImageUrl { get; set; }
public string BaseLinkUrl { get; set; }
public Dictionary<string,DataItem> Data { get; set; }
public int Type { get; set; }
}
}

Facing issue while deserializing the http resposne [duplicate]

This question already has an answer here:
Deserializing JSON into an object
(1 answer)
Closed 7 years ago.
I am using JavaScriptserializer to deserialize the HTTP response and convert back to object.
Code to retrieve the response:
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
var myobj = js.Deserialize<List<NPIObj>>(objText);
}
I am getting JSON string as below:
objText:
{
"NPI": [
{
"NPI": "1003000118",
"EntityType": "Organization",
"IsOrgSubpart": "N",
"OrgName": "STEVEN ENGEL PEDIATRICS",
"FirstLineMailingAddress": "1700 NEUSE BLVD",
"MailingAddressCityName": "NEW BERN",
"MailingAddressStateName": "NC",
"MailingAddressPostalCode": "28560-2304",
"MailingAddressCountryCode": "US",
"MailingAddressTelephoneNumber": "252-637-3799",
"MailingAddressFaxNumber": "252-633-0944",
"FirstLinePracticeLocationAddress": "1700 NEUSE BLVD",
"PracticeLocationAddressCityName": "NEW BERN",
"PracticeLocationAddressStateName": "NC",
}
]
}
The issue happens I am able to get JSON response in the objText variable.
But when i try to deserialize the reponse to NPIObj,the count is coming as 0.
var myobj = js.Deserialize<List<NPIObj>>(objText);
myobj variable is having count as 0,even I am receiving the JSON response.
Here is my NPIObj class:
public class NPIObj
{
public string EntityType { get; set; }
public string FirstLineMailingAddress { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MailingAddressCityName { get; set; }
public string MailingAddressCountryCode { get; set; }
public string MailingAddressPostalCode { get; set; }
public string MailingAddressStateName { get; set; }
public string MiddleName { get; set; }
public string NamePrefix { get; set; }
public string NPI { get; set; }
public string OrgName { get; set; }
public string SecondLineMailingAddress { get; set; }
}
Can anyone help me out how can i get the response to NPIObj?
You have a root property in your json: NPI. So you are not deserializing the array but the root object.
Create another class:
public class NPIRoot
{
public List<NPIObj> NPI { get; set; }
}
Then
var myobj = js.Deserialize<NPIRoot>(objText);

Read Json from file and display [duplicate]

This question already has answers here:
Android app Json
(2 answers)
Closed 7 years ago.
I writing android app and have API
Writing API to file like this
Code of writing:
string url2 = "http://new.murakami.ua/?mkapi=getProducts";
JsonValue json = await FetchAsync(url2);
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine(path, "myfile.txt");
using (var streamWriter = new StreamWriter(filename, true))
{
streamWriter.Write(json.ToString());
streamWriter.Close();
}
ParseAndDisplay1(json);
ParseAndDisplay2(json);
ParseAndDisplay3(json);
ParseAndDisplay4(json);
ParseAndDisplay5(json);
ParseAndDisplay6(json);
ParseAndDisplay7(json);
ParseAndDisplay8(json);
}
private async Task<JsonValue> FetchAsync(string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
//dynamic data = JObject.Parse(jsonDoc[15].ToString);
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
// Return the JSON document:
return jsonDoc;
}
}
}
And I need to read some fields from file
I try to do it like this but it didn't work
Code:
private void ParseAndDisplay1(JsonValue json)
{
TextView productname = FindViewById<TextView> (Resource.Id.posttittle);
TextView price = FindViewById<TextView> (Resource.Id.price);
TextView weight = FindViewById<TextView> (Resource.Id.weight);
productname.Click += delegate {
var intent404 = new Intent (this, typeof(SoupesDetailActivity1));
StartActivity (intent404);
};
string path = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine (path, "myfile.txt");
using (var streamReader = new StreamReader (filename, true)) {
JsonValue firstitem = json [81];
productname.Text = firstitem ["post_title"];
price.Text = firstitem ["price"] + " грн";
weight.Text = firstitem ["weight"] + "г";
}
}
Can you help me with this problem?
Here's a simple way to read the JSON and manipulate it using Json.NET that you can install from Xamarin:
var url = "http://new.murakami.ua/?mkapi=getProducts";
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
// Since you're just downloading the json you can use a webclient
using (var wc = new WebClient())
{
// Download the json data
var jsonData = await wc.DownloadStringTaskAsync(new Uri(url));
// Save the json data
File.WriteAllText(Path.Combine(path, "myfile.txt"), jsonData);
// Deserialize the Json into a list of object of the type YourObject
List<YourObject> list = JsonConvert.DeserializeObject<List<YourObject>>(jsonData);
// Do whatever you want to do with the data
foreach (var yourObject in list)
{
// this is just an example
Console.WriteLine(yourObject.post_title);
}
}
And this is the definition of the YourObject class:
// this will hold the deserialized objects and make it easy to use
// You can delete properties you don't need
public class YourObject
{
public int ID { get; set; }
public string post_author { get; set; }
public string post_date { get; set; }
public string post_date_gmt { get; set; }
public string post_content { get; set; }
public string post_title { get; set; }
public string post_excerpt { get; set; }
public string post_status { get; set; }
public string comment_status { get; set; }
public string ping_status { get; set; }
public string post_password { get; set; }
public string post_name { get; set; }
public string to_ping { get; set; }
public string pinged { get; set; }
public string post_modified { get; set; }
public string post_modified_gmt { get; set; }
public string post_content_filtered { get; set; }
public int post_parent { get; set; }
public string guid { get; set; }
public int menu_order { get; set; }
public string post_type { get; set; }
public string post_mime_type { get; set; }
public string comment_count { get; set; }
public string filter { get; set; }
public object img_url { get; set; }
public string visibility { get; set; }
public string price { get; set; }
public string weight { get; set; }
public string energy { get; set; }
public string sku { get; set; }
public int category { get; set; }
}

Categories

Resources