I have an endpoint with functionname (( CallTrafficEndPoint )) this request was developed by RestSharp Methdology
And I call this endpoint from other place in code but the retrieved type was (RequestData)
so How can I retrive a bool value from this request?
namespace Business.TrafficIntegration
{
public static class Calling_API
{
public static RequestData CallTrafficEndPoint(RequestData TrafficModel, CrmDAL crmDal)
{
RequestData IsLicenseValid;
Utility.Utility utility = new Utility.Utility(crmDal);
string serviceURL = utility.GetAdminConfigurationValue("valid-licence");
var client = new RestClient(serviceURL);
var request = new RestRequest();
var body = new RequestData();
body = TrafficModel;
request.AddJsonBody(body);
using (MemoryStream DeSerializememoryStream = new MemoryStream())
{
//Json String that we get from web api
var response = client.Post(request);
//initialize DataContractJsonSerializer object and pass Student class type to it
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RequestData));
//user stream writer to write JSON string data to memory stream
StreamWriter writer = new StreamWriter(DeSerializememoryStream);
writer.Write(response);
writer.Flush();
DeSerializememoryStream.Position = 0;
//get the Desrialized data
RequestData SerializedObject = (RequestData)serializer.ReadObject(DeSerializememoryStream);
IsLicenseValid = SerializedObject;
// throw new InvalidPluginExecutionException("The retrieved value " + IsLicenseValid);
return IsLicenseValid;
}
}
}
}
I'm trying to build a simple twitter HttpClient and MySQL application using .Net Core 3.1, but I'm seeing an issue where result object becomes null before I'm done handling it. What should be the correct way to handle this?
Sample code:
using (HttpClient httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
var requestUri = "https://api.twitter.com/2/tweets/search/stream";
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");
var stream = httpClient.GetStreamAsync(requestUri).Result;
using (var reader = new StreamReader(stream))
{
//while (!reader.EndOfStream)
while (reader.Peek() >= 0)
{
//We are ready to read the stream
var ResultObject = JsonConvert.DeserializeObject<Tweet>(reader.ReadLine());
Console.WriteLine(ResultObject);
if (ResultObject != null) // <== ResultObject disappears after this :: NullReferenceException
{
Console.WriteLine(ResultObject);
string sQuery = $"INSERT INTO MySQLTable (tweet_id,text) VALUES ({ResultObject.data.id},\"{ResultObject.data.text}\");";
Client.NonQuery(sQuery);
Console.WriteLine(Client.Query("SELECT * FROM MySQLTable;"));
};
}
}
}
public class Tweet
{
public TweetData data;
}
public class TweetData
{
public string id;
public string text;
}
(This issue did not appear in .Net 5.0)
Problem was in string sQuery.
I was trying to .Select() on a null member. Works perfectly fine when there is validation present for null members.
I am using RestSharp to post an object to asp.net Web API action. For JSON format, my client side codes work OK with server side
that provides Web API post action. For XML format, my other client side codes do not work; debugging on server side Web API action,
the object binding is always null; the input paramenter "analyticsLogs" is recevied as null for XML format (see codes below). Please help.
The following is my asp.net web API POST action on server side:
[HttpPost]
public HttpResponseMessage PostAnalyticsLogs([FromBody] AnalyticsLogs analyticsLogs)
{
_logger.Info(analyticsLogs);
bool status = _analyticService.CreateAnalyticsLogs(analyticsLogs);
HttpResponseMessage response = new HttpResponseMessage();
if(status)
{
response = Request.CreateResponse<AnalyticsLogs>(HttpStatusCode.OK, analyticsLogs);
}
else
{
response = Request.CreateResponse<AnalyticsLogs>(HttpStatusCode.InternalServerError, analyticsLogs);
}
return response;
}
The client codes for JSON format works OK:
private void buttonPostAnalyticsLogsDTO_Click(object sender, EventArgs e)
{
try
{
string pingMessage = string.Empty;
clearDataGridViewLinqToExcel();
if (!isWebAPISiteRunning(out pingMessage))
{
MessageBox.Show(pingMessage);
_logger.Error(pingMessage);
return;
}
// POST
AnalyticsLogs analyticsLogs = new AnalyticsLogs();
Analytics analytics = new Analytics();
analytics.Action = "Action test JSON";
analytics.Category = "Category test JSON";
analytics.Label = "Label test";
analytics.Value = 2147483647;
analytics.Timestamp = DateTime.Now;
analyticsLogs.Add(analytics);
// REST SHARP
var client = new RestClient(_webApiBaseUrl);
var request = new RestRequest();
request.Method = Method.POST;
request.RequestFormat = DataFormat.Json; // JSON ***************
request.Resource = "Analytic";
request.AddBody(analyticsLogs);
var response = client.Execute<AnalyticsLogs>(request);
if (response.ResponseStatus == ResponseStatus.Error)
{
_logger.Error(response.ErrorMessage);
MessageBox.Show(response.ErrorMessage);
return;
}
dataGridViewLocalDMSWebAPIForDataAggregator.DataSource = response.Data;
}
catch(Exception ex)
{
_logger.Error(ex);
MessageBox.Show(ex.Message);
}
}
The client codes for XMLformat do not work:
private void buttonPostAnalyticsLogsDTO_XML_Click(object sender, EventArgs e)
{
try
{
string pingMessage = string.Empty;
clearDataGridViewLinqToExcel();
if (!isWebAPISiteRunning(out pingMessage))
{
MessageBox.Show(pingMessage);
_logger.Error(pingMessage);
return;
}
// POST
AnalyticsLogs analyticsLogs = new AnalyticsLogs();
Analytics analytics = new Analytics();
analytics.Action = "Action test XML";
analytics.Category = "Category test XML";
analytics.Label = "Label test";
analytics.Value = 47950494;
analytics.Timestamp = DateTime.Now;
analyticsLogs.Add(analytics);
// REST SHARP
var client = new RestClient(_webApiBaseUrl);
var request = new RestRequest();
request.Method = Method.POST;
request.RequestFormat = DataFormat.Xml; // XML *****************
request.Resource = "Analytic";
request.AddBody(analyticsLogs);
var response = client.Execute<AnalyticsLogs>(request);
if (response.ResponseStatus == ResponseStatus.Error)
{
_logger.Error(response.ErrorMessage);
MessageBox.Show(response.ErrorMessage);
return;
}
dataGridViewLocalDMSWebAPIForDataAggregator.DataSource = response.Data;
}
catch (Exception ex)
{
_logger.Error(ex);
MessageBox.Show(ex.Message);
}
}
My custom DTO classes:
public class Analytics
{
public DateTime Timestamp { get; set; }
public long UserExpId { get; set; }
public string UserExpStatus { get; set; }
public string Category { get; set; }
public string Action { get; set; }
public string Label { get; set; }
public int Value { get; set; }
}
public class AnalyticsLogs : List<Analytics>
{
}
Debugging the problem with XML client codes gives me some information:
(new System.Collections.Generic.Mscorlib_CollectionDebugView<RestSharp.Parameter>(request.Parameters)).Items[0] :RequestBody
+ [0] {text/xml=<AnalyticsLogs>
<Analytics>
<Timestamp>9/9/2014 9:15:58 AM</Timestamp>
<UserExpId>0</UserExpId>
<Category>Category test XML</Category>
<Action>Action test XML</Action>
<Label>Label test</Label>
<Value>47950494</Value>
</Analytics>
</AnalyticsLogs>} RestSharp.Parameter
request.RootElement : null
I've found the problem. The RestSharp Serializer is not comaptible with the DataContractSerializer or XmlSerializer. Both are used from Web API (Default: DataContractSerializer).
RestSharp produces clean XML but the DataContractSerializer need some extra information (aka xmlns:i and xmlns attributes).
You can reproduce your problem within an console application with this code:
(It will throw an detailed exception within the deserialization process)
AnalyticsLogs analyticsLogs = new AnalyticsLogs();
Analytics analytics = new Analytics();
analytics.Action = "Action test XML";
analytics.Category = "Category test XML";
analytics.Label = "Label test";
analytics.Value = 47950494;
analytics.Timestamp = DateTime.Now;
analyticsLogs.Add(analytics);
var serializer = new RestSharp.Serializers.XmlSerializer();
var xml = serializer.Serialize(analyticsLogs);
var obj = Deserialize<AnalyticsLogs>(xml);
static string Serialize<T>(T value) {
XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();
// formatter.UseXmlSerializer = true;
// Create a dummy HTTP Content.
Stream stream = new MemoryStream();
var content = new StreamContent(stream);
/// Serialize the object.
formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait();
// Read the serialized string.
stream.Position = 0;
return content.ReadAsStringAsync().Result;
}
static T Deserialize<T>(string str) where T : class {
XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();
// formatter.UseXmlSerializer = true;
// Write the serialized string to a memory stream.
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(str);
writer.Flush();
stream.Position = 0;
// Deserialize to an object of type T
return formatter.ReadFromStreamAsync(typeof(T), stream, null, null).Result as T;
}
The Methods are from Web API Tutorial and you have to install Web API in your console app.
I've found no solution to get them both work together - sry :(
In our programming environment at work we have both Java and C# developers. I have a web service I created In C# that the Java developers are trying to consume. I have been writing the Java to consume this web service and while I am getting a json result, it is in the wrong format.
Here is what I have on the c# side:
[WebMethod]
public static LinkedList<string> GetInfo(string InfoID, string Username, string Password)
{
LinkedList<string> Result = new LinkedList<string>();
try
{
// Do some stuff I can't show you to get the information...
foreach (Result from data operations)
{
Result.AddLast(sample1);
Result.AddLast(sample2);
Result.AddLast(sample3);
Result.AddLast(BD));
Result.AddLast(CN);
Result.AddLast(Name);
Result.AddLast("###");
}
}catch(Exception exc)
{
Result.AddLast(exc.ToString());
return Result;
}
return Result;
}
Then this is the Java Side:
try {
String uri = "http://example.com/service.asmx/GetInfo";
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Setup Connection Properties
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setChunkedStreamingMode(0);
connection.connect();
// Create the JSON Going out
byte[] parameters = "{'InfoID':'123456789','Username':'usernametoken','Password':'passwordtoken'}".getBytes("UTF-8");
// Start doing stuff
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
os.write(parameters);
os.close();
InputStream response;
// Check for error , if none store response
if(connection.getResponseCode() == 200){response = connection.getInputStream();}
else{response = connection.getErrorStream();}
InputStreamReader isr = new InputStreamReader(response);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(isr);
String read = br.readLine();
while(read != null){
sb.append(read);
read = br.readLine();
}
// Print the String
System.out.println(sb.toString());
// Creat JSON off of String
JSONObject token = new JSONObject(sb.toString());
// print JSON
System.out.println("Tokener: " + token.toString());
response.close();
} catch(IOException exc) {
System.out.println("There was an error creating the HTTP Call: " + exc.toString());
}
And the response I get is in this form...
{"d":["Sample1","Sample2","Sample3","BD","CN","Name","###","Sample1","Sample2","Sample3","BD","CN","Name","###","Sample1","Sample2","Sample3","BD","CN","Name","###"]}
I was wondering if there was a better way to send the response such that the JSON would look like this:
{"1":["Sample1","Sample2","Sample3","BD","CN","Name","###"],"2":["Sample1","Sample2","Sample3","BD","CN","Name","###"],"3":["Sample1","Sample2","Sample3","BD","CN","Name","###"],"4":["Sample1","Sample2","Sample3","BD","CN","Name","###"]}
Ok I think I see your problem here. You want your data to be serialized as
{"1":["Sample1","Sample2","Sample3","BD","CN","Name","###"],"2":["Sample1","Sample2","Sample3","BD","CN","Name","###"],"3":["Sample1","Sample2","Sample3","BD","CN","Name","###"] ... etc
Yet the data structure you are serializing is a single linked list, which is why it is serialized as a single long list. What you need to do is change the data structure. A Dictionary would be perfect, since it is easily serializable as JSON.
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public static Dictionary<int,LinkedList<string>> GetInfo(string InfoID, string Username, string Password)
{
var Result = new Dictionary<int,LinkedList<string>>();
try
{
// Do some stuff I can't show you to get the information...
foreach (Result from data operations)
{
var newList = new LinkedList<string>();
newList.AddLast(sample1);
newList.AddLast(sample2);
newList.AddLast(sample3);
newList.AddLast(BD));
newList.AddLast(CN);
newList.AddLast(Name);
newList.AddLast("###");
int number = something //the number before the list
Result.add( number, newList);
}
}catch(Exception exc)
{
.
.
.
}
return Result;
}
I would like to ask if anyone know how to extract out the "name" and "query" and maybe store it in a arraylist.
Source file: https://api.twitter.com/1/trends/daily.json
You can use JObject , something like: -
string response = requestData("https://api.twitter.com/1/trends/daily.json");
JObject jsonResponse = new JObject();
var name = string.Empty;
var query = string.Empty;
try
{
jsonResponse = JObject.Parse(response);
name = (string)jsonResponse["name"];
query = (string)jsonRespone["query"];
}
catch
{
return "";
}
public string requestData(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string results = sr.ReadToEnd();
sr.Close();
return results;
}
Based on this question: Parse JSON in C#
Make a class that represents the JSON you're extracting, and extract the class from the JSON using the code in the JSONHelper class from the linked question:
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
ms.Close();
return obj;
}
}