Custom string from TextBox in webrequest - c#

i am trying to send a HttpWebRequest with the following body :
string body = "{\"prompt\": \"MyText\",\"n\": 2,\"size\": \"256x256\",\"response_format\":\"b64_json\"}";
the request works perfectly with this body, but everytime i try to change "MyText" with a text from textbox, i get an error 400 from server.
i tried this (return error 400):
string body = "{\"prompt\":" +textBox1.Text+",\"n\": 2,\"size\": \"256x256\",\"response_format\":\"b64_json\"}";
any ideas ?

It is not recommended to build your JSON manually as you will highly expose to syntax errors due to missing/extra quotes, braces, etc especially when dealing with complex objects/arrays.
Using the libraries such as System.Text.Json or Newtonsoft.Json for the JSON serialization. This is safer and easier compared to building it manually.
using System.Text.Json;
var obj = new
{
prompt = textBox1.Text,
n = 2,
size = "256x256",
response_format = "b64_json"
};
string body = JsonSerializer.Serialize(obj);
using Newtonsoft.Json;
string body = JsonConvert.SerializeObject(obj);

Related

RestRequest no longer contains AddJsonBody

I have been using restsharp to make this simple request to a webservice:
string sParmDb = Newtonsoft.Json.JsonConvert.SerializeObject(parmsDb);// parmsDb is some object too large to be passed as a query parameter
sParmDb = System.Web.HttpUtility.UrlEncode(sParmDb);
RestSharp.RestRequest;
RestSharp.RestClient cl = new RestSharp.RestClient();
RestSharp.RestResponse rsp;
string sQueryStr = "http://myWebService";
restCall = new RestSharp.RestRequest(sQueryStr, RestSharp.Method.POST);
restCall.AddJsonBody(sParmDb);
rsp = (RestSharp.RestResponse)cl.Execute(restCall);
this works fine on NuGet version 106.9.0 but when I updated the package to 108.0.1 it doesn't compile.
RestSharp.Method doesn't contain POST, though it does have a Post, so perhaps that's a simple change.
The main problem is that RestRequest no longer contains AddJsonBody.
What would be the simplest, quickest code change that will fix this?
Thanks for your help.
UPDATE 26/7/2022
----------------
I realized that the reason that restCall.AddJsonBody was not available was that I needed to include the RestSharp.Extensions as a using directive.
Now this code compiles under version 108, the current version:
RestSharp.RestClient cl = new RestSharp.RestClient();
RestSharp.RestRequest restCall = new RestSharp.RestRequest("http://localhost:60484/api/db", RestSharp.Method.POST);
restCall.AddJsonBody("abcdefg");
RestSharp.RestResponse rsp = (RestSharp.RestResponse)cl.Execute(restCall);
This reaches the web service method, which I am running in debug mode on localhost, but the string value parameter is null.
Do I need another line(s) of code in the calling client to make it work as it does under version 106?
The web service looks like this:
public string Post([FromBody] string value)
{
//do something with value and return some string
}
string sQueryStr = "http://myWebService";
RestSharp.RestClient cl = new RestSharp.RestClient(sQueryStr);
var restCall = new RestRequest() { Method= Method.Post};
...
restCall.AddStringBody(sParmDb, RestSharp.ContentType.Json);
article https://restsharp.dev/usage.html#request-body

Problem With Cyrillic Characters as URL Parameter

I'm trying to translate some text by sending a GET request to https://translate.googleapis.com/ from a C# application.
The request should be formatted as following:
"/translate_a/single?client=gtx&sl=BG&tl=EN&dt=t&q=Здравей Свят!"
where sl= is the source language, tl= is the target language and q= is the text to be translated.
The response is a JSON array with the translated text and other details.
The problem is that when I try to translate from bulgarian to english the result gets broken like: "Р-РґСЂР ° РІРμР№ РЎРІСЏС,!"
There is no problem when I'm translating from english to bulgarian (no cyrillic in the URL) so my gues is that the problem is in the request.
Also whenever I'm sending the request directly from the browser the result is properly translated text.
How I'm doing it:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Web;
class Program
{
static void Main(string[] args)
{
string ApiUrl = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}";
string targetLang = "en";
string sourceLang = "bg";
string text = "Здравей Свят!";
text = HttpUtility.UrlPathEncode(text);
string url = string.Format(ApiUrl, sourceLang, targetLang, text);
using (var client = new HttpClient())
{
var result = client.GetStringAsync(url).Result;
var jRes = (JArray)JsonConvert.DeserializeObject(result);
var translatedText = jRes[0][0][0].ToString();
var originalText = jRes[0][0][1].ToString();
var sourceLanguage = jRes[2].ToString();
}
}
}
Any suggestion will be appreciated.
Thanks to this comment I have managed to recieve a properly formatted response.
The thing is that I'm not using two important parameters in the URL:
ie=UTF-8
oe=UTF-8
The URL should look like this:
https://translate.googleapis.com/translate_a/single?client=gtx&sl=BG&tl=EN&dt=t&q=Здравей%20Свят!&ie=UTF-8&oe=UTF-8

Set a Json Serialized Object into session. not able to parse it from the View

Just the Brief Code which is enough to explain my problem i guess.
Here is my c# code:
List<MaZone> ListZoneValues = new List<MaZone>();
ListZoneValues.Add(new MaZone()
{
ZoneIc = int.Parse(DataReader["ZoneIC"].ToString()),
ZoneName = DataReader["ZoneName"].ToString()
});
HttpContext.Session.SetString("ZoneDetails",JsonConvert.SerializeObject(ListZoneValues));
Here is my javascript code.
var ZoneDetailsVB = '#HttpContextAccessor.HttpContext.Session.GetString("ZoneDetails")';
JSON.parse(ZoneDetailsVB);
But the error im face is while Parsing the Json.
The Error was:
Uncaught SyntaxError: Unexpected token & in JSON at position 2
at JSON.parse (<anonymous>)
Json string Recieved:
[{"ZoneIc":1,"ZoneName":"Zone1"},{"ZoneIc":2,"ZoneName":"Zone1 & 2"},{"ZoneIc":3,"ZoneName":"Zone2"},{"ZoneIc":4,"ZoneName":"Zone4"},{"ZoneIc":5,"ZoneName":"Zone5"},{"ZoneIc":6,"ZoneName":"Zone 6"},{"ZoneIc":7,"ZoneName":"Zone Num 7"}]
Thanks in Advance.
If you are using jQuery, you could do something like this
function htmlDecode(value) {
return $("<textarea/>").html(value).text();
}
var ZoneDetailsVB = '#HttpContextAccessor.HttpContext.Session.GetString("ZoneDetails")';
JSON.parse(htmlDecode(ZoneDetailsVB));
You can also use he library https://github.com/mathiasbynens/he
Third solution is to use
Html.Raw
var ZoneDetailsVB = '#(Html.Raw(HttpContextAccessor.HttpContext.Session.GetString("ZoneDetails").ToString()))'

Parsing a generic variable from a Json text

I'm trying to parse the info from a json object obtained via api, but in this request, I'm trying to get just one variable. I just want to get the summonerLevel variable.
{
"test": {
"id":107537,
"name":"test",
"profileIconId":785,
"summonerLevel":30,
"revisionDate":1440089189000
}
}
I've been trying to it with this code and I know that if I write
p.summonerLevel = (int)(obj.test.summonerLevel)
it will work, but the problem is that test is not a static name, and it will be changing within each request I do. Any good example on how to do it?
Thanks
WebClient c = new WebClient();
string data = c.DownloadString("https://las.api.pvp.net/api/lol/las/v1.4/summoner/by-name/"+summonerName+"?api_key=<api-key>");
dynamic obj = JsonConvert.DeserializeObject(data);
p.summonerLevel = (int)(obj.tempName.summonerLevel);
Something like this?
int summonerLevel= (int)JObject.Parse(data).First.First["summonerLevel"];

C# Extracting data from Json or DataSets - Porting from Python (Json to Dict)

I have the following Python script which I need to port to C#. This gets a JSON response from a URL and then pops it into a dictionary. Then it checks for the data next_page and if there is data (it's not empty) it then returns true. Underneath I'll paste the C# code I have but I'm really struggling to do the final part. I don't know and I certainly don't want to understand the data in the JSON response, I just want to know if the field next_page is there.
# Gets JSON response
response = requests.get(url, auth=(user, pwd))
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
data = response.json()
if(data['next_page']):
return True
else:
return False
So this is the c# code I've got:
using Newtonsoft.Json;
string response = "";
using (WebClient client = new WebClient())
{
client.UseDefaultCredentials = true;
client.Credentials = new NetworkCredential(user, password);
try
{
response = client.DownloadString(url);
} catch (Exception e)
{
throw e;
}
}
XmlDocument xml = JsonConvert.DeserializeXmlNode(json, "RootObject");
XmlReader xr = new XmlNodeReader(xml);
DataSet ds = new DataSet("Json Data");
ds.ReadXml(xr);
From what I've seen on the web DataSets work best when you know what the data inside of it is. I just want to know if there is a field called next_page and if there is, is it empty or does it have data. I'm just struggling to get anything out of the DataSet.
You will want to include the JSON.net nuget package (http://james.newtonking.com/json) this lets you deserialize the JSON response into a dictionary (or preferably a new class) allowing you to access the response.
eg add this into your try catch after including the library
var dict = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
Alternativly you could create a new class that represents the expected JSON and deserialize into that
public class ResponseObject
{
public string next_page { get; set; }
}
var responseResult = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseObject>(response);

Categories