How to update AccountNumber value by ContactId in XERO API using C# - 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);

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

How to use an information sent on httpResponse?

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.

Multiple requests (pagination) with RestSharp

I'm new to C# and I need help! I need to send paged data through a client rest. As the data mass is very large, I would like to trigger several requests at the same time, however, only a small part of the data is arriving at the destination. Can you help me with what's wrong?
public void SendResultsByFireForget(string env, string transactionId, int days)
{
var client = new RestClient();
var proxyDefinition = new WebProxy("xxx.xxx.xxx.xxx");
proxyDefinition.UseDefaultCredentials = true;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
client.Proxy = proxyDefinition;
if (String.IsNullOrEmpty(transactionId))
{
throw new ArgumentException("Parameter transactionId is null or empty!");
}
if (String.IsNullOrEmpty(env))
{
throw new ArgumentException("Parameter uri is null or empty!");
}
List<Result> listOfResults = Repository.GetResultsByIntervalPerDay(-31);
if (listOfResults.Count() == 0 || listOfResults == null)
{
throw new Exception("The list of results is empty or null");
}
var tasks = new List<Task>();
foreach (List<Result> page in GetPages(listOfResults, 500))
{
var currentPageCopy = page;
var task = Task.Run(() =>
{
var currentPage = JSonExtensions.ToJSon(currentPageCopy);
var request = new RestRequest(
$"{env.Trim()}/results1/?transaction_id={transactionId.Trim()}",
Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(currentPage);
client.ExecuteAsync(request);
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
}
if u can get total result count on first result you can do like this .
// RestClient is extented restsharp client you can do your own .
List<User> UserList = new();
// inline method
UserList getUser(int startCount,int limit)
{
var Data = RestClient.GetData(Url);
return Data;
}
// another inline for getting total count
int GetOrderCounts()
{
// get total counts
var FData = getUser(0,0);
return FData.TotalRecordCount;
}
var GetTotalCount = GetOrderCounts();
for (int ONumber = 0; ONumber <= GetOrderCount; ONumber += 100)
{
var Return = GetOrders(OrderNumber, 100);
if (Return != null)
UserList.AddRange(Return.Data);
};

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;

How to mock a OWIN Testserver with RestSharp?

I'm using OWIN with WebAPI integration as WebApp. Future plan is to use OWIN self-hosting which is working fine but the OWIN testserver implementation is not working together with RestSharp:
Sample without RestSharp:
https://blogs.msdn.microsoft.com/webdev/2013/11/26/unit-testing-owin-applications-using-testserver/
First attempt is to use a mock class derived from RestClient class:
public class MockRestClient : RestClient
{
public TestServer TestServer { get; set; }
public MockRestClient(TestServer testServer)
{
TestServer = testServer;
}
public override IRestResponse Execute(IRestRequest request)
{
// TODO: Currently the test server is only doing GET requests via RestSharp
var response = TestServer.HttpClient.GetAsync(request.Resource).Result;
var restResponse = ConvertToRestResponse(request, response);
return restResponse;
}
private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponseMessage httpResponse)
{
RestResponse restResponse1 = new RestResponse();
restResponse1.Content = httpResponse.Content.ReadAsStringAsync().Result;
restResponse1.ContentEncoding = httpResponse.Content.Headers.ContentEncoding.FirstOrDefault();
restResponse1.ContentLength = (long)httpResponse.Content.Headers.ContentLength;
restResponse1.ContentType = httpResponse.Content.Headers.ContentType.ToString();
if (httpResponse.IsSuccessStatusCode == false)
{
restResponse1.ErrorException = new HttpRequestException();
restResponse1.ErrorMessage = httpResponse.Content.ToString();
restResponse1.ResponseStatus = ResponseStatus.Error;
}
restResponse1.RawBytes = httpResponse.Content.ReadAsByteArrayAsync().Result;
restResponse1.ResponseUri = httpResponse.Headers.Location;
restResponse1.Server = "http://localhost";
restResponse1.StatusCode = httpResponse.StatusCode;
restResponse1.StatusDescription = httpResponse.ReasonPhrase;
restResponse1.Request = request;
RestResponse restResponse2 = restResponse1;
foreach (var httpHeader in httpResponse.Headers)
restResponse2.Headers.Add(new Parameter()
{
Name = httpHeader.Key,
Value = (object)httpHeader.Value,
Type = ParameterType.HttpHeader
});
//foreach (var httpCookie in httpResponse.Content.)
// restResponse2.Cookies.Add(new RestResponseCookie()
// {
// Comment = httpCookie.Comment,
// CommentUri = httpCookie.CommentUri,
// Discard = httpCookie.Discard,
// Domain = httpCookie.Domain,
// Expired = httpCookie.Expired,
// Expires = httpCookie.Expires,
// HttpOnly = httpCookie.HttpOnly,
// Name = httpCookie.Name,
// Path = httpCookie.Path,
// Port = httpCookie.Port,
// Secure = httpCookie.Secure,
// TimeStamp = httpCookie.TimeStamp,
// Value = httpCookie.Value,
// Version = httpCookie.Version
// });
return restResponse2;
}
Unfortunatly I stuck with Post events, which needs html body from restResponse.
Has anybody done something similar.
BTW: I can also use OWIN unit tests with self-hosting OWIN, but this will not work on Teamcity automatic builds.
I changed the mock rest Client to work with Post/Put/Delete methods too. It is not 100% complete (missing auth, Cookies, files etc.), but in my case it is sufficient:
public class MockRestClient : RestClient
{
public TestServer TestServer { get; set; }
public MockRestClient(TestServer testServer)
{
TestServer = testServer;
}
public override IRestResponse Execute(IRestRequest request)
{
// TODO: Currently the test server is only doing GET requests via RestSharp
HttpResponseMessage response = null;
Parameter body = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
HttpContent content;
if (body != null)
{
object val = body.Value;
byte[] requestBodyBytes;
string requestBody;
if (val is byte[])
{
requestBodyBytes = (byte[]) val;
content = new ByteArrayContent(requestBodyBytes);
}
else
{
requestBody = Convert.ToString(body.Value);
content = new StringContent(requestBody);
}
}
else
content = new StringContent("");
string urladd = "";
IEnumerable<string> #params = from p in request.Parameters
where p.Type == ParameterType.GetOrPost && p.Value != null
select p.Name + "=" + p.Value;
if(!#params.IsNullOrEmpty())
urladd = "?" + String.Join("&", #params);
IEnumerable<HttpHeader> headers = from p in request.Parameters
where p.Type == ParameterType.HttpHeader
select new HttpHeader
{
Name = p.Name,
Value = Convert.ToString(p.Value)
};
foreach (HttpHeader header in headers)
{
content.Headers.Add(header.Name, header.Value);
}
content.Headers.ContentType.MediaType = "application/json";
switch (request.Method)
{
case Method.GET:
response = TestServer.HttpClient.GetAsync(request.Resource + urladd).Result;
break;
case Method.DELETE:
response = TestServer.HttpClient.DeleteAsync(request.Resource + urladd).Result;
break;
case Method.POST:
response = TestServer.HttpClient.PostAsync(request.Resource + urladd, content).Result;
break;
case Method.PUT:
response = TestServer.HttpClient.PutAsync(request.Resource + urladd, content).Result;
break;
default:
return null;
}
var restResponse = ConvertToRestResponse(request, response);
return restResponse;
}
private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponseMessage httpResponse)
{
RestResponse restResponse1 = new RestResponse();
restResponse1.Content = httpResponse.Content.ReadAsStringAsync().Result;
restResponse1.ContentEncoding = httpResponse.Content.Headers.ContentEncoding.FirstOrDefault();
restResponse1.ContentLength = (long)httpResponse.Content.Headers.ContentLength;
restResponse1.ContentType = httpResponse.Content.Headers.ContentType.ToString();
if (httpResponse.IsSuccessStatusCode == false)
{
restResponse1.ErrorException = new HttpRequestException();
restResponse1.ErrorMessage = httpResponse.Content.ToString();
restResponse1.ResponseStatus = ResponseStatus.Error;
}
restResponse1.RawBytes = httpResponse.Content.ReadAsByteArrayAsync().Result;
restResponse1.ResponseUri = httpResponse.Headers.Location;
restResponse1.Server = "http://localhost";
restResponse1.StatusCode = httpResponse.StatusCode;
restResponse1.StatusDescription = httpResponse.ReasonPhrase;
restResponse1.Request = request;
RestResponse restResponse2 = restResponse1;
foreach (var httpHeader in httpResponse.Headers)
restResponse2.Headers.Add(new Parameter()
{
Name = httpHeader.Key,
Value = (object)httpHeader.Value,
Type = ParameterType.HttpHeader
});
//foreach (var httpCookie in httpResponse.Content.)
// restResponse2.Cookies.Add(new RestResponseCookie()
// {
// Comment = httpCookie.Comment,
// CommentUri = httpCookie.CommentUri,
// Discard = httpCookie.Discard,
// Domain = httpCookie.Domain,
// Expired = httpCookie.Expired,
// Expires = httpCookie.Expires,
// HttpOnly = httpCookie.HttpOnly,
// Name = httpCookie.Name,
// Path = httpCookie.Path,
// Port = httpCookie.Port,
// Secure = httpCookie.Secure,
// TimeStamp = httpCookie.TimeStamp,
// Value = httpCookie.Value,
// Version = httpCookie.Version
// });
return restResponse2;
}

Categories