How to use an information sent on httpResponse? - c#

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.

Related

NullReferenceException coming while calling PostAsync on xamarin.Forms

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();

SEndGrid not replacing Dynamics Data

My one template is not replacing dynamics data in the email
My Code is given below
public static System.Net.HttpStatusCode SendEmailV2(DynamicsModel dynamicsmodel, string templateId, TraceWriter log)
{
log.Info("Executing SendEmailV2");
var SendGridApiCode = System.Environment.GetEnvironmentVariable("SendGridApiCode", EnvironmentVariableTarget.Process);
var fromEmail = System.Environment.GetEnvironmentVariable("FromEmail", EnvironmentVariableTarget.Process);
var fromName = System.Environment.GetEnvironmentVariable("FromName", EnvironmentVariableTarget.Process);
var dynamicTemplateData = new DynamicData
{
Name = dynamicsmodel.FullName
};
string output = JsonConvert.SerializeObject(dynamicTemplateData);
log.Info("json:" + output);
EmailAddress from = new EmailAddress(fromEmail, "test name");
EmailAddress to = new EmailAddress(dynamicsmodel.Email, dynamicsmodel.FullName);
var sendGridClient = new SendGridClient(SendGridApiCode);
var sendGridMessage = CreateSingleTemplateEmail(from, to, templateId, dynamicTemplateData);
var response = sendGridClient.SendEmailAsync(sendGridMessage).Result;
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
log.Info("Emails Sent from SendGrid");
}
else
{
log.Info("response.StatusCode:" + response.StatusCode.ToString());
}
return response.StatusCode;
}
My JSON which is being passed is given below
{"name":"Test User"}
This happens to one template only. Any help will be much appreciated

How to update AccountNumber value by ContactId in XERO API using C#

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);

The combination of parameters is either not valid or not complete.\r\nParameter name: tagObject VSTS Git API

I try to attach a tag to existing commit using GitHttpClient CreateAnnotatedTagAsync method (Microsoft.TeamFoundation.SourceControl.WebApi). But each time I keep getting error:
The combination of parameters is either not valid or not complete.\r\nParameter name: tagObject
Part of code for adding annotated tag.
GitObject gitObject = new GitObject { ObjectId = commitId, ObjectType = GitObjectType.Commit };
GitAnnotatedTag tagObj = new GitAnnotatedTag
{
Name = tagName.Replace(' ', '_'),
TaggedObject = gitObject,
TaggedBy = new GitUserDate
{
Name = "FirstName LastName",
Email = "someemail#smth.com",
Date = DateTime.Now
},
Message = tagComment
};
GitAnnotatedTag res = gitClient.CreateAnnotatedTagAsync(tagObj, projectName, new Guid(repositoryId)).Result;
Examples of tag objects I tried to send:
Any help would be appreciated.
So I just used API to create tags:
GitAnnotatedTag tag = null;
try
{
var tagObject = new { Name = tagName.Replace(' ', '_'), Message = tagComment, TaggedObjectId = commitId };
StringContent stringContent = new StringContent(JsonConvert.SerializeObject(tagObject),
Encoding.UTF8,
"application/json");
client.DefaultRequestHeaders.Add("Accept", "application/json; charset=utf-8; api-version=3.2-preview.1");
using (HttpResponseMessage response = client.PostAsync(string.Format(createTagUrl, projectId, repositoryId), stringContent).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
tag = JsonConvert.DeserializeObject<GitAnnotatedTag>(responseBody);
}
}
catch (Exception ex)
{
// Add some error handling here
}
return tag;

C# Unit tests - Unable to extract Content from the IHttpActionResult responce

I have this controller
[Route("GeocacheAddressObjectList")]
[HttpPost]
public async Task<IHttpActionResult> GeocacheAddressObjectList([FromBody] List<GeocacheAddress> addresses)
{
//check valid addresses
if(addresses == null)
{
return BadRequest("Invalid addresses. The address list object is null!") as IHttpActionResult;
}
ElasticHelper searchHelper = new ElasticHelper(ConfigurationManager.AppSettings["ElasticSearchUri"]);
List<GeocacheAddress> geocodedAddresses = new List<GeocacheAddress>();
// check each address in the addresses list against geocache db
foreach (GeocacheAddress address in addresses)
{
var elasticSearchResult = SearchGeocacheIndex(address);
// found a match
if (elasticSearchResult.Total != 0)
{
SearchProperties standardizedAddressSearch = new SearchProperties();
standardizedAddressSearch.Size = 1;
standardizedAddressSearch.From = 0;
Address elasticSearchResultAddress = elasticSearchResult.Hits.ElementAt(0).Source;
// query the standardized key in geocache db
standardizedAddressSearch.ElasticAddressId = elasticSearchResultAddress.Standardized.ToString();
// the address is already standardized, return the standardized address with its geocode
if (standardizedAddressSearch.ElasticAddressId == "00000000-0000-0000-0000-000000000000")
{
geocodedAddresses.Add(new GeocacheAddress
{
Id = address.Id,
Street = elasticSearchResultAddress.AddressString,
City = elasticSearchResultAddress.City,
State = elasticSearchResultAddress.State,
ZipCode = elasticSearchResultAddress.Zipcode,
Plus4Code = elasticSearchResultAddress.Plus4Code,
Country = elasticSearchResultAddress.Country,
Latitude = elasticSearchResultAddress.Coordinates.Lat,
Longitude = elasticSearchResultAddress.Coordinates.Lon
});
}
else // perform another query using the standardized key
{
Address standardizedAddress = StandardAddressSearch(standardizedAddressSearch).Hits.ElementAt(0).Source;
if (standardizedAddress == null)
{
return BadRequest("No standardized address found in geocache database") as IHttpActionResult;
}
geocodedAddresses.Add(new GeocacheAddress()
{
Id = address.Id,
Street = standardizedAddress.AddressString,
City = standardizedAddress.City,
State = standardizedAddress.State,
ZipCode = standardizedAddress.Zipcode,
Plus4Code = standardizedAddress.Plus4Code,
Country = standardizedAddress.Country,
Latitude = standardizedAddress.Coordinates.Lat,
Longitude = standardizedAddress.Coordinates.Lon
});
}
}
else // not found in geocache db, call SmartStreets API
{
List<Address> address_list = new List<Address>();
using (HttpClient httpClient = new HttpClient())
{
//Send the request and get the response
httpClient.BaseAddress = new System.Uri(ConfigurationManager.AppSettings["GeocodingServiceUri"]);
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
//Lookup object to perform Geocoding service call
var postBody = JsonConvert.SerializeObject(new Lookup()
{
MaxCandidates = 1,
Street = address.Street,
City = address.City,
State = address.State,
ZipCode = address.ZipCode
});
var requestContent = new StringContent(postBody, Encoding.UTF8, "application/json");
// Send the request and get the response
var response = await httpClient.PostAsync("GeocodeAddressObject", requestContent);
if (!response.IsSuccessStatusCode) //error handling
{
geocodedAddresses.Add(new GeocacheAddress()
{
Id = address.Id,
Error = response.ReasonPhrase
});
}
Geocode geocodeFromGeocoder = JsonConvert.DeserializeObject<List<Geocode>>(response.Content.ReadAsStringAsync().Result).ElementAt(0);
GeocacheAddress geocodedAddress = new GeocacheAddress()
{
Id = address.Id,
Street = geocodeFromGeocoder.CorrectedAddress,
City = geocodeFromGeocoder.City,
State = geocodeFromGeocoder.State,
ZipCode = geocodeFromGeocoder.Zipcode,
Plus4Code = geocodeFromGeocoder.Plus4Code,
Country = geocodeFromGeocoder.Country,
Latitude = geocodeFromGeocoder.Latitude,
Longitude = geocodeFromGeocoder.Longitude
};
geocodedAddresses.Add(geocodedAddress);
// check each geocoded address against geocache db
Guid standardized_key;
var geocodedAddressResult = SearchGeocacheIndex(geocodedAddress);
// found a match
if (geocodedAddressResult.Total != 0)
{
Address standardizedAddress = geocodedAddressResult.Hits.ElementAt(0).Source;
standardized_key = standardizedAddress.AddressID;
}
else // not found, insert geocode into geocache db
{
Address new_standardized_address = createStandardizedAddress(geocodeFromGeocoder);
standardized_key = new_standardized_address.AddressID;
address_list.Add(new_standardized_address);
}
// insert non-standardized address into geocache db
Address new_nonstandardized_address = createNonStandardizedAddress(address, standardized_key);
address_list.Add(new_nonstandardized_address);
}
searchHelper.BulkIndex<Address>(address_list, "xxx", "xxx");
}
}
return Json(geocodedAddresses, new Newtonsoft.Json.JsonSerializerSettings()) as IHttpActionResult;
}
I am writing a unit test to test some part of this controller.
I want to compare the response received from the controller with the expected value. When i debug the result, it shows the content for the response but I am unable to use content like (result.Content) in the code.
When i try to use this line, then it returns null response.
var result = await controller.GeocacheAddressObjectList(testGeocacheAddress) as OkNegotiatedContentResult<GeocacheAddress>;
Actual unit test code. I would appreciate any help.
[TestMethod]
public async Task TestMethod1()
{
var controller = new GeocachingController();
var testGeocacheAddress = new List<GeocacheAddress>();
testGeocacheAddress.Add(new GeocacheAddress
{
City = "Renton",
});
var result = await controller.GeocacheAddressObjectList(testGeocacheAddress);
var expected = GetGeocacheAddress();
Assert.AreEqual(result.Content.City, expected[0].City);
}
private List<GeocacheAddress> GetGeocacheAddress()
{
var testGeocacheAddress = new List<GeocacheAddress>();
testGeocacheAddress.Add(new GeocacheAddress
{
Id = Guid.Empty,
Street = "365 Renton Center Way SW",
City = "Renton",
State = "WA",
ZipCode = "98057",
Plus4Code = "2324",
Country = "USA",
Latitude = 47.47753,
Longitude = -122.21851,
Error = null
});
return testGeocacheAddress;
}
In your unit test you need to cast the result to JsonResult<T>, more specifically JsonResult<List<GeocacheAddress>> as that is what you are returning.
var result = await controller.GeocacheAddressObjectList(testGeocacheAddress) as JsonResult<List<GeocacheAddress>>;
If you were to have used return Ok(geocodedAddresses) in your controller return (where you now return the call from Json) then you could have cast to OkNegotiatedContentResult<List<GeocacheAddress>>.
Also in your Controller code you do not need to cast the return to IHttpActionResult because JsonResult<T> already implements that. The cast is redundant.
That's quite simple to achieve, all you have to do is cast the content you're expecting in your unit test method.
Example:
Controller:
public class FooController : ApiController
{
public IHttpActionResult Get()
{
var foo = "foo";
return Ok(foo);
}
}
Unit test:
[TestMethod]
public void Get_Foo_From_Controller()
{
var fooController = new FooController();
var result = fooController.Get();
//Here we are casting the expected type
var values = (OkNegotiatedContentResult<string>)result;
Assert.AreEqual("Foo", values.Content);
}
By the way, i noticed you're using the async keyword in your controller action but i don't see the await keyword.
Using the async keyword without an await will give you a warning and result in a synchronous operation.
Also, you dont have to cast your response as an IHttpActionResult, you could do something like i showed in my example, wrap your content inside an Ok(your content here) and you're good to go.

Categories