In.net Framework 4.5 using RestSharp version 105.2.3 getting System.MissingMethodException when I try to use request.AddJsonBody() method - restsharp

I am using RestSharp version 105.2.3 in .Net MVC framework 4.5 project to integrate external API, when I use request.AddJsonBody(obj) I get the runtime exception as System.MissingMethodException
Following are the code I used to call API
```
public string CheckCMSUser(RequestObjectModel requestObject)
{
RestClient client = new RestClient(requestObject.BaseURL + "CheckCMSUser");
RestRequest request = new RestRequest();
var payload = new RequestObjectCMSModel()
{
CompanyNumber = requestObject.CompanyNumber,
UserAccountEmail = requestObject.UserAccountEmail,
IncludeAllSubs = requestObject.IncludeAllSubs
};
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(payload);
request.AddHeader("WebAPI-Version", requestObject.WebAPIVersion);
request.AddHeader("Authorization", requestObject.Token);
var response = client.get(request);
return response.Content;
}
public void CheckCMSUser()
{
requestObj.CompanyNumber = "9999";
requestObj.UserAccountEmail = "user#example.com";
requestObj.IncludeAllSubs = "N";
requestObj.Token = _workContext.Token;
ValidUserResponseModel response = JsonConvert.DeserializeObject<ValidUserResponseModel>(_externalApiService.CheckCMSUser(requestObj));
}
```
Please help me to solve this
Thanks in Advance

Related

Why is the API call not working in ASP.NET Core 6 MVC, but the same API is working fine in ASP.NET MVC 5?

One of my code is perfectly working in ASP.NET MVC 5, but when I am using almost same logic to call the API from ASP.NET Core 6 MVC, then the API always returns an error.
Same parameters and same address is being used in both technologies but the old approach is working.
Please see my old and new Logic to call this API, and guide me how to fix it.
The API Url is :
https://pcls1.craftyclicks.co.uk/json/rapidaddress?key=mykey&include_geocode=true&&postcode=DD68AB&response=data_formatted
ASP.NET MVC 5 - working fine:
using (var client = new HttpClient())
{
string addressUri = WebConfigurationManager.AppSettings["addressUri"];
var uri = addressUri + postcode.Replace(" ","") + "&response=data_formatted";
var response = await client.GetAsync(uri);
string textResult = await response.Content.ReadAsStringAsync();
lObjApiRes = JsonConvert.DeserializeObject<AddressLookupViewModel>(textResult);
}
ASP.NET Core 6 MVC - results in error:
using (HttpClient client = new HttpClient())
{
string addressUri = Configuration["CustomSettings:AddressUri"];
string uri = addressUri + postcode.Replace(" ", "") + "&response=data_formatted";
string textResult = "";
HttpRequestMessage request = new HttpRequestMessage()
{
RequestUri = new Uri(uri),
Method = HttpMethod.Get,
};
HttpResponseMessage response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
textResult = await response.Content.ReadAsStringAsync();
}
}
The steps are simple to reproduce the case. Just create an ASP.NET Core 6 MVC project and try my code.
Please guide me to resolve the issue in a better way.
Why I am always getting this error:
{ "error_code":"0001",
"error_msg": "No data was found for the requested postcode." }

HttpClient not sending post data to NancyFX endpoint

I am doing some integration testing of my web API that uses NancyFX end points. I have the xUnit test create a test server for the integration test
private readonly TestServer _server;
private readonly HttpClient _client;
public EventsModule_Int_Tester()
{
//Server setup
_server = new TestServer(new WebHostBuilder()
.UseStartup<Startup>());
_server.AllowSynchronousIO = true;//Needs to be overriden in net core 3.1
_client = _server.CreateClient();
}
Inside a Test Method I tried the following
[Fact]
public async Task EventTest()
{
// Arrange
HttpResponseMessage expectedRespone = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
var data = _server.Services.GetService(typeof(GenijalnoContext)) as GenijalnoContext;
//Get come random data from the DBcontext
Random r = new Random();
List<Resident> residents = data.Residents.ToList();
Resident random_residnet = residents[r.Next(residents.Count)];
List<Apartment> apartments = data.Apartments.ToList();
Apartment random_Apartment = apartments[r.Next(apartments.Count)];
EventModel model = new EventModel()
{
ResidentId = random_residnet.Id,
ApartmentNumber = random_Apartment.Id
};
//Doesnt work
IList<KeyValuePair<string, string>> nameValueCollection = new List<KeyValuePair<string, string>> {
{ new KeyValuePair<string, string>("ResidentId", model.ResidentId.ToString()) },
{ new KeyValuePair<string, string>("ApartmentNumber", model.ApartmentNumber.ToString())}
};
var result = await _client.PostAsync("/Events/ResidentEnter", new FormUrlEncodedContent(nameValueCollection));
//Also Doesnt work
string json = JsonConvert.SerializeObject(model, Formatting.Indented);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _client.PostAsync("/Events/ResidentEnter", httpContent);
//PostAsJsonAsync also doesnt work
// Assert
Assert.Equal(response.StatusCode, expectedRespone.StatusCode);
}
The NancyFX module does trigger the endpoint and receives the request but without the body
What am I doing wrong? Note that the NancyFX endpoint has no issue transforming a Postman call into a valid model.
The NancyFX endpoint
Alright I fixed it, for those curious the issue was that the NancyFX body reader sometimes does not properly start reading the request body. That is that the stream reading position isn't 0 (the start) all the time.
To fix this you need to create a CustomBoostrapper and then override the ApplicationStartup function so you can set up a before request pipeline that sets the body position at 0
Code below
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
base.ApplicationStartup(container, pipelines);
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx =>
{
ctx.Request.Body.Position = 0;
return null;
});
}

IIS Express crashing asp.net 3.1 utf8 encoding

I used this function all the time in asp.net mvc to fetch data from an API but in asp.net core it's crashing out. I believe it may be an issue to do with the utf8 in .net core has anyone else had issues with this I just get an iis express error of -1 and the code bombs out
public async Task<List<Stock>> GetStockFromApi()
{
List<Stock> _result = new List<Stock>();
var uri = new Uri(string.Format(Constants.GetALlStock, string.Empty));
var response = await _httpClient.GetAsync(uri);
if (response.IsSuccessStatusCode) {
var byteArray = await response.Content.ReadAsByteArrayAsync();
var content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
_result = JsonConvert.DeserializeObject<List<Stock>>(content);
}
return _result.ToList();
}
Make sure your api result (byteArray) in your case is correct.
It works well when I use your code in a brand new asp.net core 3.1 mvc project:
1.Add Microsoft.AspNetCore.Mvc.NewtonsoftJson package to project from PMC
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson -Version 3.1.0
2.Register it in startup.cs
services.AddControllersWithViews().AddNewtonsoftJson();
3. Test Action:
public async Task<List<Stock>> GetStockFromApi()
{
List<Stock> _result = new List<Stock>();
var uri = new Uri("https://localhost:44321/home/GetAllStock");
using (var client = new HttpClient())
{
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var byteArray = await response.Content.ReadAsByteArrayAsync();
var content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
_result = JsonConvert.DeserializeObject<List<Stock>>(content);
}
return _result.ToList();
}
}
public ActionResult<List<Stock>> GetAllStock()
{
var list = new List<Stock>()
{
new Stock()
{
Id = 1,
Name="hello"
},
new Stock()
{
Id = 2,
Name="wrold"
},
};
return Ok(list);
}

How to use the continuationtoken in TFS 2015 Object Model: GetBuildsAsync?

I am using the following code
BuildHttpClient service = new BuildHttpClient(tfsCollectionUri,
new Microsoft.VisualStudio.Services.Common.VssCredentials(true));
var asyncResult = service.GetBuildsAsync(project: tfsTeamProject);
var queryResult = asyncResult.Result;
This returns only the first 199 builds.
Looks like in need to use the continuationtoken but am not sure how to do this. The docs say that the REST API will return the token. I am using the Object Model, and am looking for how to retrieve the token!
I am using Microsoft.TeamFoundationServer.Client v 14.102.0; Microsoft.TeamFoundationServer.ExtendedClient v 14.102.0, Microsoft.VisualStudio.Service.Client v 14.102.0 and Microsoft.VisualStudio.Services.InteractiveClient v 14.102.0
Question
How do I use the continuation token **when using the TFS Object model?
The continuationToken is in the response header after the first call to the API:
x-ms-continuationtoken: xxxx
It can not be retrieved from .net client library. You have to use the rest api to retrieve the header information. Here is an example for your reference:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace GetBuilds
{
class Program
{
public static void Main()
{
Task t = GetBuilds();
Task.WaitAll(new Task[] { t });
}
private static async Task GetBuilds()
{
try
{
var username = "xxxxx";
var password = "******";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
using (HttpResponseMessage response = client.GetAsync(
"http://tfs2015:8080/tfs/DefaultCollection/teamproject/_apis/build/builds?api-version=2.2").Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
You have to use 'GetBuildsAsync2', which returns an IPagedList. You can retrieve the ContinuationToken from the IPagedList:
// Iterate to get the full set of builds
string continuationToken = null;
List<Build> builds = new List<Build>();
do
{
IPagedList<Build> buildsPage = service.GetBuildsAsync2(tfsTeamProject, continuationToken: continuationToken).Result;
//add the builds
builds.AddRange(buildsPage);
//get the continuationToken for the next loop
continuationToken = buildsPage.ContinuationToken;
}
while (continuationToken != null);

Twitter API upgrade for Windows Phone

I have tweet poster in my application which uses oAuth 1.0 which will retire soon and will be non functional. I have to upgrade my API to 1.1. Twitter development center says that, If oAuth is used by your application, you can easily transaction to 1.1 by only updating your API endpoint. What exactly is API endpoint?
Here I'm having hard understanding about API endpoint. I think my asyncronous post call URL must be upgraded.
Here is the relevant codes which I think that might include the answer;
private void btnPostTweet_Click(object sender, RoutedEventArgs e)
{
namebocx.Text = userScreenName;
if (txtBoxNewTweet.Text.Trim().Length == 0) { return; }
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = TwitterSettings.consumerKey,
ConsumerSecret = TwitterSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
};
var restClient = new RestClient
{
Authority = TwitterSettings.StatusUpdateUrl,
HasElevatedPermissions = true,
Credentials = credentials,
Method = WebMethod.Post
};
restClient.AddHeader("Content-Type", "application/x-www-form-urlencoded");
// Create a Rest Request and fire it
var restRequest = new RestRequest
{
Path = "1/statuses/update.xml?status=" + txtBoxNewTweet.Text //Here must be endpoint of Api??
};
var ByteData = Encoding.UTF8.GetBytes(txtBoxNewTweet.Text);
restRequest.AddPostContent(ByteData);
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
}
}
and also here is the authentication settings:
public class TwitterSettings
{
public static string RequestTokenUri = "https://api.twitter.com/oauth/request_token";
public static string AuthorizeUri = "https://api.twitter.com/oauth/authorize";
public static string AccessTokenUri = "https://api.twitter.com/oauth/access_token";
public static string CallbackUri = "http://www.google.com";
public static string StatusUpdateUrl { get { return "http://api.twitter.com"; } }
public static string consumerKey = "myconsumerkeyhere";
public static string consumerKeySecret = "myconsumersecrethere";
public static string oAuthVersion = "1.0a";
}
Here what twitter says me to replace with this instead of written in my code;
https://api.twitter.com/1.1/statuses/update.json
and some parameters told here -->> https://dev.twitter.com/docs/api/1.1/post/statuses/update
How should I update my API endpoint, what kind of changes do I have to do?
If you can help me, I really appreciate
You can change this:
Path = "1/statuses/update.xml?status=" + txtBoxNewTweet.Text
//Here must be endpoint of Api??
to this:
Path = "1.1/statuses/update.json?status=" + txtBoxNewTweet.Text
//Here must be endpoint of Api??