When I try to call , it throws me this error: System.NullReferenceException Message=Object reference not set to an instance of an object. Is there something wrong with the code? Need Help!
public Command RegisterUser
{
get
{
return new Command(async () =>
{
UserInfo user = new UserInfo();
//try
//{
user.UserId = 99;
user.LoginId = "aaaa";
user.FirstName = "aaa";
user.SecondName = "ddd";
user.ThirdName = "dd";
user.DOB = DateTime.Now.Date;
user.PhoneNo = "332323";
user.Email = "aa.aa.com";
user.Password = "aaaa";
string jsonData = JsonConvert.SerializeObject(user);
string url = "http://192.168.18.22:44368/api/User";
HttpClient client1 = new HttpClient();
client1.MaxResponseContentBufferSize = int.MaxValue;
StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response1 = await client1.PostAsync(url, content);
string result = "";
if (response1 != null)
result = await response1.Content.ReadAsStringAsync();
//}
//catch (Exception ex)
//{
// string eee = "";
//}
});
}
}
You maybe should check content on null as well as response1, seems like here is the problem. More info about stack trace can help also
if (response1 != null) result = await response1.Content?.ReadAsStringAsync();
Related
I am learning about making requests to an api using my backend and when i make this i receive a response with some informations i want to use but i don't know how to use this.
Let me clarify this for you.
I HAVE THIS CODE TO MAKE THE REQUEST
try
{
//Set Basic Auth
var userPagarme = test_key;
var password = "";
var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userPagarme}:{password}"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var clienteToAdd = new PagarmeCliente()
{
Name = registerUser.Name,
Code = registerUser.Code,
Document = registerUser.Document,
Type = registerUser.Type,
Document_Type = registerUser.Document_Type,
Birthdate = registerUser.Birthdate,
Email = registerUser.Email,
Gender = registerUser.Gender,
Address = new PagarmeClienteEndereco()
{
city = registerUser.City,
country = registerUser.Country,
line_1 = registerUser.Line_1,
line_2 = registerUser.Line_2,
state = registerUser.State,
zip_code = registerUser.Zip_Code
},
Phones = new PagarmeClienteTelefone()
{
mobile_phone = new PagarmeClienteTelefoneMobile()
{
area_code = registerUser.Mobile_phone_area_code,
country_code = registerUser.Mobile_phone_country_code,
number = registerUser.Mobile_phone_number
},
}
};
var jsonString = JsonConvert.SerializeObject(clienteToAdd);
HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
this.responseBodyJSON = JsonConvert.DeserializeObject(responseBody); // I have created this prop as an OBJ to receive the obj that was sent. I don't know if it is correct
}
catch (HttpRequestException e)
{
return BadRequest("\nException Caught - Message :{0} " + e.Message);
}
That is what i have in this responseBodyJSON and i want to use this property ID to insert on my database but if i make something like this below it doesn't work:
string idThatIWant = responseBodyJSON.id... or something like that.
var jsonString = JsonConvert.SerializeObject(clienteToAdd);
HttpResponseMessage response = await client.PostAsJsonAsync(urlPagarme + "customers", clienteToAdd);
You converted your model to JSON but you didn't use that jsonString. This could be the cause of the problem.
var respBody = JsonConvert.DeserializeObject<PagarmeCliente>(responseBody);
respBody.ID should be available if the class PagarmeCliente has the ID field you wanted populated.
I'm trying to achieve update contact with Xero api: I'm trying to update AccountNumber value is null.
This is the code for update method. I'm passing value with ContactId and AccountNumber.
var xContact = new XeroContact
{
AccountNumber = null,
ContactId = CustomerGUID
};
var request = new XeroContactRequest { AuthToken = _authHelper.AccessToken, Search = "", TenantId = _authHelper.TenantId, CustomerGUID = CustomerGUID, Contact = xContact };
var xeroCustomerResult = _xeroContactBusiness.UpdateContact(request);
update function:
public IResult<XeroContact> UpdateContact(XeroContactRequest data)
{
var result = new Result<XeroContact>();
try
{
if (data == null || string.IsNullOrEmpty(data.AuthToken) || string.IsNullOrEmpty(data.TenantId)) throw new ArgumentNullException("data is required");
var client = new RestClient(BaseUrl);
var method = string.Format("/{0}/{1}", _apiMethod, data.CustomerGUID);
var request = new RestRequest(method, Method.POST);
request.AddHeader("Authorization", string.Format("Bearer {0}", data.AuthToken));
request.AddHeader("Accept", "application/json");
request.AddHeader("Xero-tenant-id", data.TenantId);
var postData = JsonConvert.SerializeObject(data.Contact);
request.AddJsonBody(postData);
var response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception(ParseError(response.Content));
}
}
catch (Exception ex)
{
result.HasData = false;
result.Data = null;
result.Error = ex;
}
return result;
}
Can you please help me understand what I'm doing wrong? How can i update AccountNumber by ContactId. Thanks !
I have resolved this issue below way, Just need to send ContactId and those parameter that's need to be updated. Here "AccountNumber" field need to be updated. Thanks !
var body = new
{
ContactId = data.CustomerGUID,
AccountNumber=""
};
var postData = JsonConvert.SerializeObject(body);
request.AddJsonBody(postData);
I am using PushSharp 4.0.10.0 library to send the notification on iOS devices but it's not working. I have debugged it and found there is some ApnsConfiguration connection problem.
I am using this code to send the notificaiton:
public IHttpActionResult Notify()
{
HttpResponseMessage response = new HttpResponseMessage();
HttpContent requestContent = Request.Content;
string errorMessage = "Some error occured.please try again later";
HttpStatusCode responseCode = HttpStatusCode.Unauthorized;
string requestParameter = requestContent.ReadAsStringAsync().Result;
string tokan = "";
var r = Request;
var header = r.Headers;
try
{
if (requestParameter != null)
{
PushNotificationModel complaintModel = JsonConvert.DeserializeObject<PushNotificationModel>(requestParameter);
JsonConvert.DeserializeObject<PushNotificationModel>(requestParameter);
var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/User/xyz.pem"));
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,
appleCert, "xyz");
// Create a new broker
var push = new ApnsServiceBroker(config);
int DeviceType = 1;
string deviceId = Convert.ToString(complaintModel.deviceToken);
string message = "New notification!!";
Guid complaintId = complaintModel.ComplaintId;
string detail = complaintModel.detail;
try
{
//System.Web.Hosting.HostingEnvironment.MapPath("~/Images/User/")
// var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/User/CTPwd.pem"));
push.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
message = ex.Message;
}
else
{
message = "Not an APNSException";
}
// Mark it as handled
return true;
});
};
try
{
push.OnNotificationSucceeded += (notification) =>
{
message = "New Notification";
};
push.Start();
string appleJsonFormat = "{\"aps\": {\"alert\":" + '"' + message + '"' + ",\"sound\": \"default\"}}";
//string appleJsonFormat = "{\"aps\": {\"alert\": " + "Hello World" + ",\"sound\": \"default\"}}";
push.QueueNotification(new ApnsNotification
{
DeviceToken = deviceId,
Payload = JObject.Parse(appleJsonFormat)
});
push.Stop();
}
catch(Exception ex)
{
}
I have searched on google, but did not find any relevant answer. Is there any syntax problem ?
Thanks in advance.
Please use .P12 file format for push notification happy coding:)
I am working on bot technology, in one of my projet i wrote below lines of code
private async void DeliveryProgressReport(IDialogContext context, Activity message)
{
MessagesController.progressdetails = SQLDatabaseService.getinprogressdetails();
var progress = MessagesController.progressdetails;
if (progress.Count > 0)
{
try
{
Activity replyToConversation = message.CreateReply("**In Progress Report Details**");
replyToConversation.Recipient = message.From;
replyToConversation.Type = "message";
replyToConversation.Attachments = new List<Attachment>();
Dictionary<string, string> progresslist = new Dictionary<string, string>();
foreach (var progressreport in progress)
{
//Invoke the machine learning model for predicting the delivery status of delivery person
//var deliveryStatus= await InvokeRequestResponseServiceOfDeliveryPersonPredictionExp1();
//await Task.Delay(TimeSpan.FromSeconds(5));
var deliveryStatus = await InvokeRequestResponseServiceOfDeliveryPersonPredictionExp(progress[0].Name, progress[0].Mobile_Number);
progresslist.Add(progressreport.Name, progressreport.Mobile_Number);
List<CardImage> cardImages = new List<CardImage>();
cardImages.Add(new CardImage(url: progressreport.Photo_Url));
ThumbnailCard tlcard = new ThumbnailCard()
{
Title = "Name:" + progressreport.Name,
Subtitle = "Call:" + progressreport.Mobile_Number,
Images = cardImages,
Text = "Staus by Using Machine Learning Prediction:" + deliveryStatus
};
Attachment plAttachment = tlcard.ToAttachment();
replyToConversation.Attachments.Add(plAttachment);
}
replyToConversation.AttachmentLayout = AttachmentLayoutTypes.List;
await context.PostAsync(replyToConversation);
} catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
else
{
Activity replyToConversation = message.CreateReply("**There are no in progress deliveries are found**");
await context.PostAsync(replyToConversation);
}
}
private async Task<string> InvokeRequestResponseServiceOfDeliveryPersonPredictionExp(string name, string mobile_Number)
{
string status = "";
//Func<Stream, Task> copyStreamAsync = async stream =>
//{
//await Task.Factory.StartNew(async () =>
//{
//using (stream)
//using (var sourceStream = await sourceContent.Content.ReadAsStreamAsync())
//{
// await sourceStream.CopyToAsync(stream);
//}
//var client = new HttpClient();
using (var client = new HttpClient())
{
var scoreRequest = new
{
Inputs = new Dictionary<string, StringTable>() {
{
"input1",
new StringTable()
{
ColumnNames = new string[] {"Id", "Name", "Mobile_Number", "CourierCompany_Name", "Status", "EmailId"},
Values = new string[,] { { "", name, mobile_Number, "", "","" }, { "", name, mobile_Number, "", "", "" }, }
}
},
},
GlobalParameters = new Dictionary<string, string>()
{
}
};
const string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx=="; // Replace this with the API key for the web service
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
client.BaseAddress = new Uri("My Request URL");
// WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application.
// One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context.
// For instance, replace code such as:
// result = await DoSomeTask()
// with the following:
// result = await DoSomeTask().ConfigureAwait(false)
//var status = await PostRequest(scoreRequest,client).ConfigureAwait(false);
HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);//.ConfigureAwait(false);
string correctLocation = "";
string wrongLocation = "";
string notReached = "";
string personMismatch = "";
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
var results = JsonConvert.DeserializeObject<RootObject>(result);
foreach (var value in results.Results.output1.value.Values)
{
status = value[8].ToString();
correctLocation = value[4].ToString();
notReached = value[5].ToString();
personMismatch = value[6].ToString();
wrongLocation = value[7].ToString();
}
Debug.WriteLine("Result: {0}", result);
return status;
}
else
{
Debug.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));
// Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
Debug.WriteLine(response.Headers.ToString());
string responseContent = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseContent);
return status;
}
};
// return status;
}
After executing this below line I got the exception like asynchronous module or handler completed while an asynchronous operation was still pending
await context.PostAsync(replyToConversation);
Before posting this question I had followed through this below links, but I didn't resolve it.
Async Void, ASP.Net, and Count of Outstanding Operations
Web Api + HttpClient: An asynchronous module or handler completed while an asynchronous operation was still pending
Please tell how to resolve this exception.
-Pradeep
Finally, I resolved the above exception when I am return Task instead of void in DeliveryProgressReport method. and also where ever I was called the await DeliveryProgressReport() method there also I return Task instead of void.
-Pradeep
I am trying to access the Jira rest API via C#. For that I am using the Windows.Web.Http.HttpClient. But all I get as a return value is HTML.
I am calling the following URL: https://jira.atlassian.com/rest/api/latest/field/
Little Edit
When I call the url from a browser it works fine, just the call from the HttpClient doesn't work.
Here is my code:
public async Task<IRestResponse> Execute(RestRequest request) {
var restResponse = new RestResponse();
var client = new HttpClient();
var req = new HttpRequestMessage(request.Method, new Uri(BaseUrl, UriKind.RelativeOrAbsolute));
foreach (var item in request.headers) {
req.Headers[item.Key] = item.Value;
}
req.Headers.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
if (this.Authenticator != null)
req.Headers["Authorization"] = this.Authenticator.GetHeader();
var res = await client.SendRequestAsync(req);
restResponse.Content = await res.Content.ReadAsStringAsync();
restResponse.StatusCode = res.StatusCode;
restResponse.StatusDescription = res.ReasonPhrase;
if (!res.IsSuccessStatusCode) {
restResponse.ErrorMessage = restResponse.Content;
restResponse.ResponseStatus = ResponseStatus.Error;
} else if (res.StatusCode == HttpStatusCode.RequestTimeout) {
restResponse.ResponseStatus = ResponseStatus.TimedOut;
} else if (res.StatusCode == HttpStatusCode.None) {
restResponse.ResponseStatus = ResponseStatus.None;
} else {
restResponse.ResponseStatus = ResponseStatus.Completed;
}
return restResponse;
}
I just found my problem, I don't add the relative path anywhere. It just calls the BaseUrl meaning https://jira.atlassian.com/ that explains why I get the HTML page.