Error "Unexpected character encountered while parsing value" - c#

while I am trying to make a http request with httpClient I keep getting this error but I do not know why.
Unexpected character encountered while parsing value: c. Path '',
line 0, position 0."]},"title":"One or more validation errors
occurred.","status":400,
here is my code, and I am using console application to make the request:
class Program {
static void Main (string[] args) {
Data _dt = new Data();
_dt.IP = "192.156.25";
_dt.LogText = "test from http";
_dt.LogType = 1;
_dt.StoreId = 14;
_dt.StoreName = "testino";
_dt.UserId = 2;
NewAddStoreLog(_dt);
}
static void NewAddStoreLog (Data dt) {
HttpClient http = new HttpClient ();
var content = new StringContent (dt.ToString (), Encoding.UTF8, "application/json");
var result = http.PostAsync ("http://192.168.8.180:88/Logs/RecordLogs", content).Result;
string strResult = System.Text.Encoding.UTF8.GetString (result.Content.ReadAsByteArrayAsync ().Result);
System.Console.WriteLine(strResult);
}
}
public class Data {
public int StoreId { get; set; }
public int UserId { get; set; }
public string IP { get; set; }
public int LogType { get; set; } //Enum
public string LogText { get; set; }
public string StoreName { get; set; }
}

Related

Error while reading data from azure table storage

I'm writing a code to read values from a table storage. The code is similar to printing nodes in a tree level by level.
eg:
root
Level1child1 -> Level1child2 -> Level1child3
string tablename = "<table-name">;
string storageAccountName = "<storage-account-name";
var baseurl = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var sastoken = getAccountSASToken();
string filter = #"&$filter=PartitionKey%20eq%20'123'%20and%20RowKey%20eq%20'abc'";
baseurl = $"{baseurl}{sastoken}{filter}";
var data = HttpHelper.GetForOData(baseurl);
var responseData = data.Data.Replace(".", "_");
var odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Queue<int> strQ = new Queue<int>();
Console.WriteLine(odata.value[0].Email);
strQ.Enqueue(odata.value[0].TreeNodeID);
while (strQ.Any())
{
var url = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var token = _tableStorageRepository.GetAccountSASToken();
filter = #"&$filter=ParentNodeId%20eq%20" + strQ.Peek();
url = $"{url}{token}{filter}";
data = HttpHelper.GetForOData(url);
responseData = data.Data.Replace(".", "_");
odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
foreach (var m in odata?.value)
{
Console.WriteLine(m.Email);
strQ.Enqueue(m.TreeNodeID);
}
strQ.Dequeue();
}
public class ODataResponse
{
public string odata_metadata { get; set; }
public List<ODatavalue> value { get; set; }
}
public class ODatavalue
{
public string odata_type { get; set; }
public string odata_id { get; set; }
public string odata_etag { get; set; }
public string odata_editLink { get; set; }
public string RowKey { get; set; }
public string Email { get; set; }
public int ParentNodeID { get; set; }
public int TreeNodeID { get; set; }
}
Code for HttpHelper class: https://github.com/xyz92/httphelper/blob/master/HttpHelper.cs
The first time when I ran this code, it only printed root node.
The second time when I ran this code, it printed root node and Level1child1 node.
For the next runs, it printed root node, Level1child1 node & Level1child2 node.
The last node Level1child3 node is getting printed very rarely on some runs.
What am I missing in this code?
UPDATE:
Sample responseData:
{
"odata_metadata": "https://<storage-account-name>_table_core_windows_net/$metadata#<table-name>",
"value": [{
"odata_type": "<storage-account-name>_<table-name>",
"odata_id": "https://<storage-account-name>_table_core_windows_net/<table-name>(PartitionKey='123',RowKey='abc')",
"odata_etag": "W/\"datetime'2020-09-01T16%3A34%3A21_3342187Z'\"",
"odata_editLink": "<table-name>(PartitionKey='123',RowKey='abc')",
"PartitionKey": "123",
"RowKey": "abc",
"Timestamp#odata_type": "Edm_DateTime",
"Timestamp": "2020-09-01T16:34:21_3342187Z",
"Email": "email",
"ParentNodeID": 1,
"TreeNodeID": 2
}
]
}
Table columns:
Sample data in Table:
Sample outputs while running code:
According to my test, I cannot reproduce your issue in my environment. My test is as below
Table columns:
Sample data in table
Code I use your HttpHelper class to send request
class Program
{
static async Task Main(string[] args)
{
string storageAccountName = "andyprivate" ;
string tableName = "test";
var baseurl = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var sastoken = "";
string filter = #"&$filter=PartitionKey%20eq%20'123'%20and%20RowKey%20eq%20'abc'";
baseurl = $"{baseurl}{sastoken}{filter}";
var data = HttpHelper.GetForOData(baseurl);
var responseData = data.Data.Replace(".", "_");
var odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Queue<int> strQ = new Queue<int>();
Console.WriteLine("----root----");
Console.WriteLine(odata.value[0].Email);
strQ.Enqueue(odata.value[0].TreeNodeID);
while (strQ.Any())
{
int i = 0;
var url = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var token = "";
filter = #$"&$filter=ParentNodeID eq {strQ.Peek()}";
url = $"{ url}{token}{filter}";
data = HttpHelper.GetForOData(url);
responseData = data.Data.Replace(".", "_");
odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Console.WriteLine($"----TreeNode{strQ.Peek()}----");
foreach (var m in odata?.value)
{
if (i == 0) {
strQ.Enqueue(m.TreeNodeID);
i = 1;
}
Console.WriteLine(m.Email);
}
strQ.Dequeue();
}
Console.ReadLine();
}
}
public class ODataResponse
{
public string odata_metadata { get; set; }
public List<ODatavalue> value { get; set; }
}
public class ODatavalue
{
public string odata_type { get; set; }
public string odata_id { get; set; }
public string odata_etag { get; set; }
public string odata_editLink { get; set; }
public string RowKey { get; set; }
public string Email { get; set; }
public int ParentNodeID { get; set; }
public int TreeNodeID { get; set; }
}
Update
My test code
Rest API (I use your HttpHelper class to send request)
class Program
{
static async Task Main(string[] args)
{
string storageAccountName = "andyprivate" ;
string tableName = "test";
var baseurl = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var sastoken = "";
string filter = #"&$filter=PartitionKey%20eq%20'123'%20and%20RowKey%20eq%20'abc'";
baseurl = $"{baseurl}{sastoken}{filter}";
var data = HttpHelper.GetForOData(baseurl);
var responseData = data.Data.Replace(".", "_");
var odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Queue<int> strQ = new Queue<int>();
Console.WriteLine("----root----");
Console.WriteLine(odata.value[0].Email);
strQ.Enqueue(odata.value[0].TreeNodeID);
while (strQ.Any())
{
int i = 0;
var url = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var token = "";
filter = #$"&$filter=ParentNodeID eq {strQ.Peek()}";
url = $"{ url}{token}{filter}";
data = HttpHelper.GetForOData(url);
responseData = data.Data.Replace(".", "_");
odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Console.WriteLine($"----TreeNode{strQ.Peek()}----");
foreach (var m in odata?.value)
{
if (i == 0) {
strQ.Enqueue(m.TreeNodeID);
i = 1;
}
Console.WriteLine(m.Email);
}
strQ.Dequeue();
}
Console.ReadLine();
}
}
public class ODataResponse
{
public string odata_metadata { get; set; }
public List<ODatavalue> value { get; set; }
}
public class ODatavalue
{
public string odata_type { get; set; }
public string odata_id { get; set; }
public string odata_etag { get; set; }
public string odata_editLink { get; set; }
public string RowKey { get; set; }
public string Email { get; set; }
public int ParentNodeID { get; set; }
public int TreeNodeID { get; set; }
}
SDK. I use the package Microsoft.Azure.Cosmos.Table
string storageAccountName = "andyprivate";
string accountKey ="";
string tableName = "test";
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(storageAccountName, accountKey), true);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
CloudTable table = tableClient.GetTableReference(tableName);
TableOperation retrieveOperation = TableOperation.Retrieve<CustomEntity>("123", "abc");
TableResult result = await table.ExecuteAsync(retrieveOperation);
CustomEntity entity = result.Result as CustomEntity;
Queue<int> strQ = new Queue<int>();
Console.WriteLine("----root----");
Console.WriteLine(entity.Email);
strQ.Enqueue(entity.TreeNodeID);
while (strQ.Any()) {
int i = 0;
TableQuery<CustomEntity> query = new TableQuery<CustomEntity>()
.Where(
TableQuery.GenerateFilterConditionForInt("ParentNodeID", QueryComparisons.Equal,strQ.Peek())
);
Console.WriteLine($"----TreeNode{strQ.Peek()}----");
foreach (CustomEntity m in table.ExecuteQuery(query) ) {
Console.WriteLine(m.Email);
if (i == 0) {
strQ.Enqueue(m.TreeNodeID);
i = 1;
}
}
strQ.Dequeue();
}

How to assign Room to an Event for meeting using Microsoft Graph API in a UWP App

I am calling the API for creating a meeting on a fixed date & time. I am using Microsoft Graph API for this. Here is the URL
var url = "https://graph.microsoft.com/v1.0/me/events";
I have taken care of the Authentication part and my code does the following thing to send the JSON response to the API
private async void sendInvites_Click(object sender, RoutedEventArgs e)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
var url = "https://graph.microsoft.com/v1.0/me/events";
CIBC.Models.SendMeetingInvites.RootObject obj = new CIBC.Models.SendMeetingInvites.RootObject();
CIBC.Models.SendMeetingInvites.Location loc = new CIBC.Models.SendMeetingInvites.Location();
loc.displayName = GlobalVariables.MeetingRoomName;
//loc.RoomEmailAddress = GlobalVariables.meetingRoomEmailID.ToString();
obj.subject = "Maths";
CIBC.Models.SendMeetingInvites.Body body = new CIBC.Models.SendMeetingInvites.Body();
body.content = "Its a booking for follow up meeting";
body.contentType = "HTML";
obj.body = body;
List<CIBC.Models.SendMeetingInvites.Attendee> attens = new List<Models.SendMeetingInvites.Attendee>();
for(int i=0;i<GlobalVariables.NumberOfParticipant.Count;i++)
{
CIBC.Models.SendMeetingInvites.EmailAddress email = new CIBC.Models.SendMeetingInvites.EmailAddress();
CIBC.Models.SendMeetingInvites.Attendee atten = new CIBC.Models.SendMeetingInvites.Attendee();
email.address = GlobalVariables.NumberOfParticipant[i].ParticipantADdress;
atten.emailAddress = email;
atten.type = "Required";
attens.Add(atten);
}
CIBC.Models.SendMeetingInvites.Start start = new CIBC.Models.SendMeetingInvites.Start();
start.dateTime = GlobalVariables.sendMeetingInviteStartDate;
start.timeZone = "UTC";
obj.start = start;
CIBC.Models.SendMeetingInvites.End end = new CIBC.Models.SendMeetingInvites.End();
end.dateTime = GlobalVariables.sendMeetingInviteEndTime;
end.timeZone = "UTC";
obj.end = end;
obj.attendees = attens;
obj.location = loc;
string postBody = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
// var postBody1 = "{'Subject':'Testing Organizer - 12','Location':{'DisplayName':'Some place'}," +
//"'Start': {'DateTime': '2016-07-15T15:00:00.0000000', 'TimeZone':'UTC'}," +
//"'End': {'DateTime': '2016-07-15T15:30:00.0000000', 'TimeZone':'UTC'}," +
//"'Body':{'Content': 'This is a test of Grap API.', 'ContentType':'Text'}," +
//"'IsOrganizer':'False','Organizer':{'EmailAddress': " + "{'Address':'organizer#some.com'} }}";
// var requestString = #"{"subject":"My event","start":{"dateTime":"2017-09-25T07:44:27.448Z","timeZone":"UTC"},"end":{"dateTime":"2017-10-02T07:44:27.448Z","timeZone":"UTC"}}"";
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer",GlobalVariables.Token);
request.Content = new StringContent(postBody, UTF8Encoding.UTF8, "application/json");
response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{ }
// return await response.Content.ReadAsStringAsync();
else
{
}
//return "";
}
Here is the class file that I am using to pass to the HTTPResponse Message
namespace CIBC.Models.SendMeetingInvites
{
public class Body
{
public string contentType { get; set; }
public string content { get; set; }
}
public class Start
{
public DateTime dateTime { get; set; }
public string timeZone { get; set; }
}
public class End
{
public DateTime dateTime { get; set; }
public string timeZone { get; set; }
}
public class Location
{
public string displayName { get; set; }
//public string RoomEmailAddress { get; set; }
}
public class EmailAddress
{
public string address { get; set; }
public string name { get; set; }
}
public class Attendee
{
public EmailAddress emailAddress { get; set; }
public string type { get; set; }
}
public class RootObject
{
public string subject { get; set; }
public Body body { get; set; }
public Start start { get; set; }
public End end { get; set; }
public Location location { get; set; }
public List<Attendee> attendees { get; set; }
}
}
My requirement is to send a meeting invite to all the users and also mentioning the Room Details like Name& Email ID of the room.
I tried adding a RoomEmail address in the Request as under The Location class
public string RoomEmailAddress { get; set; }
When I tested this using Microsoft Graph Explorer website , i got the error message
{
"error": {
"code": "RequestBodyRead",
"message": "The property 'RoomEmailAddress' does not exist on type 'Microsoft.OutlookServices.Location'. Make sure to only use
property names that are defined by the type or mark the type as open
type.",
"innerError": {
"request-id": "1883d87d-a5d6-4357-a699-7c112da0e56b",
"date": "2017-09-26T12:03:50"
}
} }
How do I make sure that whenever I create a meeting request , I can assign a room to it?
Currently I am just able to pass DisplayName while sending the Request to the URL.
Once I remove the Email Address property (I added myself ), the code returns Success.
Any workarounds so that I can send the room email address also so that the room also receives a copy of the meeting invite ?
Add the room as an attendee with "type": "Resource". Then add the room's display name in the location property.

How do I get online predictions in C# for my model on Cloud Machine Learning Engine?

I have successfully deployed on model on Cloud ML Engine and verified it is working with gcloud ml-engine models predict by following the instructions, now I want to send predictions to it from my C# app. How do I do that?
The online prediction API is a REST API, so you can use any library for sending HTTPS requests, although you will need to use Google's OAuth library to get your credentials.
The format of the request is JSON, as described in the docs.
To exemplify, consider the Census example. A client for that might look like:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Newtonsoft.Json;
namespace prediction_client
{
class Person
{
public int age { get; set; }
public String workclass { get; set; }
public String education { get; set; }
public int education_num { get; set; }
public string marital_status { get; set; }
public string occupation { get; set; }
public string relationship { get; set; }
public string race { get; set; }
public string gender { get; set; }
public int capital_gain { get; set; }
public int capital_loss { get; set; }
public int hours_per_week { get; set; }
public string native_country { get; set; }
}
class Prediction
{
public List<Double> probabilities { get; set; }
public List<Double> logits { get; set; }
public Int32 classes { get; set; }
public List<Double> logistic { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
class MainClass
{
static PredictClient client = new PredictClient();
static String project = "MY_PROJECT";
static String model = "census"; // Whatever you deployed your model as
public static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
try
{
Person person = new Person
{
age = 25,
workclass = " Private",
education = " 11th",
education_num = 7,
marital_status = " Never - married",
occupation = " Machine - op - inspct",
relationship = " Own - child",
race = " Black",
gender = " Male",
capital_gain = 0,
capital_loss = 0,
hours_per_week = 40,
native_country = " United - Stats"
};
var instances = new List<Person> { person };
List<Prediction> predictions = await client.Predict<Person, Prediction>(project, model, instances);
Console.WriteLine(String.Join("\n", predictions));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
class PredictClient {
private HttpClient client;
public PredictClient()
{
this.client = new HttpClient();
client.BaseAddress = new Uri("https://ml.googleapis.com/v1/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<List<O>> Predict<I, O>(String project, String model, List<I> instances, String version = null)
{
var version_suffix = version == null ? "" : $"/version/{version}";
var model_uri = $"projects/{project}/models/{model}{version_suffix}";
var predict_uri = $"{model_uri}:predict";
GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();
var bearer_token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer_token);
var request = new { instances = instances };
var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
var responseMessage = await client.PostAsync(predict_uri, content);
responseMessage.EnsureSuccessStatusCode();
var responseBody = await responseMessage.Content.ReadAsStringAsync();
dynamic response = JsonConvert.DeserializeObject(responseBody);
return response.predictions.ToObject<List<O>>();
}
}
}
You may have to run gcloud auth login to initialize your credentials before running locally, if you haven't already.

JSON Deserialize Object HTTPWebResponse

I am trying to take my Web Request JSON output and parse it. Here is the output
{
"kind":"internal",
"name":"SplashPageToggle_dg",
"fullPath":"SplashPageToggle_dg",
"generation":1255326,
"selfLink":"https://link",
"type":"stri ng",
"records":[
{
"name":"enable_app1",
"data":"0"
},
{
"name":"enable_app2",
"da ta":"0"
},
{
"name":"enable_app3",
"data":"0"
},
{
"name":"enable_app4",
"data":"0"
},
{
"name":"enable_app5",
"data":"0"
},
{
"name":"enable_app6",
"data":"1"
},
{
"name":"enable_app7",
"data":"0"
},
{
"name":"enable_app8",
"data":"0"
},
{
"name":"enable_app9",
"data":"0"
},
{
"name":"enable_app10",
"data":"0"
}
]
}
I have created public classes for these results
public class RootObject
{
public string kind { get; set; }
public string name { get; set; }
public string fullPath { get; set; }
public int generation { get; set; }
public string selfLink { get; set; }
public string type { get; set; }
public List<Record> records { get; set; }
}
public class Record
{
public string name { get; set; }
public string data { get; set; }
}
When I try to deserialize the Record class and choose the name, I get the name from the RootObject class. Here is my code
static void Main(string[] args)
{
string url = "URL";
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(url);
getRequest.Method = "GET";
getRequest.Credentials = new NetworkCredential("UN", "PW");
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback
(
delegate { return true; }
);
var getResponse = (HttpWebResponse)getRequest.GetResponse();
Stream newStream = getResponse.GetResponseStream();
StreamReader sr = new StreamReader(newStream);
var result = sr.ReadToEnd();
var splashInfo = JsonConvert.DeserializeObject<Record>(result);
Console.WriteLine(splashInfo.name);
Console.ReadLine();
}
You are trying to deserialize your JSON into the wrong class.
Change this line:
var splashInfo = JsonConvert.DeserializeObject<Record>(result);
to this:
var splashInfo = JsonConvert.DeserializeObject<RootObject>(result);
Fiddle: https://dotnetfiddle.net/2xR7hO

While trying to upload video using daily motion API i got this error "The request was aborted: The request was canceled."

i am using daily motion API for uploading videos from my application but when try to upload more than 2 MB sized video i get this error "The request was aborted: The request was canceled." and this error invoked by this line of code var responseBytes = client.UploadFile(uploadUrl, fileToUpload);
and this is my code which i am using to upload video
public static void Main(MyVideo video)
{
var accessToken = GetAccessToken();
Authorize(accessToken);
var fileToUpload = video.Path;
var uploadUrl = GetFileUploadUrl(accessToken);
var response = GetFileUploadResponse(fileToUpload, accessToken, uploadUrl);
var uploadedResponse = PublishVideo(response, accessToken);
}
public class UploadResponse
{
public string format { get; set; }
public string acodec { get; set; }
public string vcodec { get; set; }
public int duration { get; set; }
public int bitrate { get; set; }
public string dimension { get; set; }
public string name { get; set; }
public int size { get; set; }
public string url { get; set; }
public string hash { get; set; }
public string seal { get; set; }
public override string ToString()
{
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy;
System.Reflection.PropertyInfo[] infos = this.GetType().GetProperties(flags);
StringBuilder sb = new StringBuilder();
string typeName = this.GetType().Name;
sb.AppendLine(typeName);
sb.AppendLine(string.Empty.PadRight(typeName.Length + 5, '='));
foreach (var info in infos)
{
object value = info.GetValue(this, null);
sb.AppendFormat("{0}: {1}{2}", info.Name, value != null ? value : "null", Environment.NewLine);
}
return sb.ToString();
}
}
private static UploadResponse GetFileUploadResponse(string fileToUpload, string accessToken, string uploadUrl)
{
// ServicePointManager.DefaultConnectionLimit = 900000;
//HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uploadUrl);
//wr.KeepAlive = false;
//wr.Timeout = System.Threading.Timeout.Infinite;
//wr.ProtocolVersion = HttpVersion.Version10;
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var responseBytes = client.UploadFile(uploadUrl, fileToUpload);
var responseString = Encoding.UTF8.GetString(responseBytes);
var response = JsonConvert.DeserializeObject<UploadResponse>(responseString);
return response;
}
and i have already tried al the possible solutionsu provided on Stackoverflow earlier also done with http execution time and we client time out but not working please someone help me

Categories