RestSharp package update causing RestRequest problem with Method.POST - asp.net-mvc

I need to update RestSharp to newest version in one project and once the newest version is installed and referenced, an existing RestRequest call causes error.
Uri uri = new Uri(url);
var client = new RestClient(uri.Scheme + "://" + uri.DnsSafeHost);
client.Authenticator = new HttpBasicAuthenticator(username, password);
var RSrequest = new RestRequest(uri.AbsolutePath, Method.POST);
What Visual Studio complains about is "Method.POST" instead of "Method.Post". Once updated to "Method.Post", project builds fine but the RestRequest call does not seem work as intended. When I look into RestRequest definition with RestSharp updated to newest version, it looks different than the old version, as it defaults to Method.Get:
public RestRequest(string? resource, Method method = Method.Get)
How can this be fixed? Obviously, I do not have much RestSharp knowledge, neighter I am the author of the code I am about to update.

Related

Azure DevOps Client Library - Download Earlier Repository Files

I am trying to download earlier repository versions (.csproj files) from the commit records that I am obtaining from the Azure DevOps NuGet client library. I want to do this so I can access the Assembly Version information in the .csproj file. The GetFile() function I am using to get the current version of the file works fine but I want to download the older versions of the file from the commit records.
This is the GetFile function.
public string GetFile(string projectName, string repoName, string fileName)
{
try
{
var items = ListItems(projectName, repoName);
var projectPath = items.FirstOrDefault(i => i.Path.Contains(fileName))?.Path ?? "";
GitHttpClient gitClient = GetGitHttpClient();
GitRepository repo = GetRepositoryAsync(projectName, repoName);
var stream = gitClient.GetItemTextAsync(repo.Id, projectPath).Result;
var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
catch (Exception e)
{
return "";
}
}
And this function gets the commits.
public async Task<List<GitCommitRef>> GetCommitsAsync(string projectName, string repoName)
{
var client = GetGitHttpClient();
var repo = GetRepositoryAsync(projectName, repoName);
var gitQueryCommitsCriteria = new GitQueryCommitsCriteria();
return await client.GetCommitsAsync(repo.Id, gitQueryCommitsCriteria);
}
Now I want to download each version of the .csproj that relates to each of these commits.
Any help anyone can give me with this would be greatly appreciated.
Kind regards, Stuart
The GetFile() function I am using to get the current version of the
file works fine but I want to download the older versions of the file
from the commit records.
I think you're in the right direction. I once used Azure Devops Rest Api Items-Get to get content of one specific version of file successfully with the help of versionDescriptor parameter.
https://dev.azure.com/MyOrgName/MyProjectName/_apis/git/repositories/MyReposName/Items?path=/README.md&versionDescriptor%5BversionOptions%5D=0&versionDescriptor%5BversionType%5D=2&versionDescriptor%5Bversion%5D={Commit ID}&download=true&resolveLfs=true&%24format=octetStream&api-version=5.0-preview.1
Since functions available in client library are corresponding to that in Rest Api, so client library must have corresponding parameters to do that.
And here's what I found:
Most of the overloads of gitClient.GetItemTextAsync() functions have GitVersionDescriptor versionDescriptor = null as input, and I think this is what you need.
Hope it makes some help.

Unable to find DiscoveryClient for IdentityServer4

Trying to access discovery client for acceising other endpoints anf following with,
http://docs.identityserver.io/en/aspnetcore1/endpoints/discovery.html
Installed IdentityModel nuget package in .Net 7.5 MVC application. But unable to find the DiscoveryClient.
var discoveryClient = new DiscoveryClient("https://demo.identityserver.io");
var doc = await discoveryClient.GetAsync();
Is there something change in Identitymodel for IdentityServer4
Also, unable to find parameter for "Tokenclient".
Able to figure out, change in IdentityModel, its all extension of HttpClient.
https://identitymodel.readthedocs.io/en/latest/client/discovery.html
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://demo.identityserver.io");
Yes, you are correct. There are lot of changes in the IdentityModel NuGet package.
Below code will help you:
HttpClient httpClient = new HttpClient();
//Below code will give you discovery document response previously we were creating using DiscoveryClient()
// They have created `.GetDiscoveryDocumentAsync()` extension method to get discovery document.
DiscoveryDocumentResponse discoveryDocument = await httpClient.GetDiscoveryDocumentAsync();
// To create a token you can use one of the following methods, which totally depends upon which grant type you are using for token generation.
Task<TokenResponse> RequestAuthorizationCodeTokenAsync(AuthorizationCodeTokenRequest)
Task<TokenResponse> RequestClientCredentialsTokenAsync(ClientCredentialsTokenRequest)
Task<TokenResponse> RequestDeviceTokenAsync(DeviceTokenRequest)
Task<TokenResponse> RequestPasswordTokenAsync(PasswordTokenRequest)
Task<TokenResponse> RequestRefreshTokenAsync(RefreshTokenRequest)
Task<TokenResponse> RequestTokenAsync(TokenRequest)
For example if you want to create a token for password grant type then use below code:
PasswordTokenRequest passwordTokenRequest = new PasswordTokenRequest()
{
Address = discoveryDocument.TokenEndpoint,
ClientId = ClientName,
ClientSecret = ClientSecret,
GrantType = GrantTypes.ResourceOwnerPassword,
Scope = scope,
UserName = userName,
Password = password
};
httpClient.RequestPasswordTokenAsync(passwordTokenRequest);
I hope this will help you!
If you used some sample code and the other answers aren't working, because HttpClient doesn't have GetDiscoveryDocumentAsync
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001");
Update your IdentityModel package, in Visual Studio:
Right click Dependencies -> Manage Nuget Packages -> Updates (select "All" in top right corner)

Could not load type 'RestSharp.Authenticators.HttpBasicAuthenticator' from assembly 'RestSharp, Version=105.1.0.0

I have used a MVC web application running on the ASP.NET Framework version 4.5.1.
I have made nopcommercePlugin. I am upgrading version 3.4 to 3.5
After the update, I am getting the following error:
System.TypeLoadException: Could not load type
'RestSharp.HttpBasicAuthenticator' from assembly 'RestSharp,
Version=105.2.1.0, Culture=neutral, PublicKeyToken=null'.
I am using Twilio to send an SMS message:
using Twilio;
public bool MethodName(string FromNumber, string ToNumber, string URL, string code = "")
{
if (code == "")
{
//URL = URL.Replace(" ", "%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20");
URL = URL.Replace(" ", "%20");
}
else
{
URL = URL + code + " we repeat your code is : " + code;
URL = URL.Replace(" ", "%20");
}
string AccountSid = _SMSProviderSettings.SMSGatewayTwillioAccountSID;
string AuthToken = _SMSProviderSettings.SMSGatewayTwillioAccountAuthToken;
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var options = new CallOptions();
var twimal = new Twilio.TwiML.TwilioResponse();
twimal.Pause(5);
options.To = ToNumber;
options.Url = URL;
options.From = FromNumber;
options.Method = "GET";
var call = twilio.InitiateOutboundCall(options);
if (call != null)
{
if (call.RestException == null)
return true;
}
//error log entry in system log
_logger.InsertLog(LogLevel.Error, call.RestException.Message, call.RestException.Message + " For more detail click here " + call.RestException.MoreInfo);
return false;
}
The Installed version are :
Twilio.4.0.5
Twilio.TwiML.3.3.6
Twilio.Mvc.3.1.15
RestSharp.105.1.0
I have seen a similar question posted back in 18th August 2015 (8 days ago) and there is also some discussion on the Twilio Nuget page discussing an Alpha Version that is reported.
If I used RestShrap 105.2.2 version then These errors are generate
Can anyone tell me what version options should be used?
Twilio developer evangelist here.
RestSharp has been updated last week to version 105.2.2. that caused the Twilio library to start failing since HttpBasicAuthenticator has been moved around to a different namespace.
The Twilio Library has then been updated to version 4.0.5 which now works with RestSharp version 105.2.2. The packages file has also been updated to use that version.
So in short, all you should need to do is update your RestSharp to version 105.2.2 via Nuget Package Manager or via Package Manager Console by running:
Install-Package RestSharp
When install Package for RestSharp through Package Manager Console, In RestSharp Folder there are multipal folder choose net452-client and install RestSharp dll.
After that my error has been solved.

How to perform a request to a REST API in ASP.net 5.0 (MVC6)

I am writing an ASP.Net 5, MVC 6 application (also referred to as 'ASP.net vNext') with Visual Studio 2015 RC.
How do I perform a simple GET request to a REST API? In .net 4.5 I would have used HttpClient but that no longer seems to be available.
I have tried adding both the 'System.Net.Http' and 'Microsoft.Net.Http' packages as advised by Visual Studio, however I still get "The type or namespace name 'HttpClient' could not be found" which leads me to believe that HttpClient is not the right way to do this in ASP.net 5?
Can anyone advise on the correct way to make HTTP GET requests in ASP.net 5?
Update: My question is not a duplicate of 'HttpClient in ASP.NET 5.0 not found?' bercause the answer given is out of date and not applicable to the latest version of ASP.net 5.0
Here is a solution for you, I just tried it out on the ASP.Net 5 Web site project template. Add the following method to HomeController
static async Task<string> DownloadPageAsync()
{
string page = "http://en.wikipedia.org/";
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
return result.Substring(0, 50);
}
}
Then in the HomeControllers Index method
string test = DownloadPageAsync().Result;
And in project.json I added the following reference at dependencies
"Microsoft.Net.Http": "2.2.22"
I found an answer which was in part from a post called '
HttpClient in ASP.NET 5.0 not found?', but there were some missing gaps because the technology has moved on a bit now. I have blogged the full solution here: http://blogs.msdn.com/b/martinkearn/archive/2015/06/17/using-httpclient-with-asp-net-5-0.aspx

Authenticating on TFS 2010

I'm having trouble authenticating as a specific user on MS Team Foundation Server. In older versions it would look like:
teamFoundationCredential = new System.Net.NetworkCredential("<USERNAME>", "<PASSWORD>", "<DOMAIN>");
TeamFoundationServer tfs = new TeamFoundationServer("http://mars:8080/", teamFoundationCredential);
Can some one tell me the equivilent for the 2010 version. So far I have:
ICredentialsProvider cred = null;
tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://asebeast.cpsc.ucalgar.ca:8080/tfs/DefualtCollection"));
tfs.EnsureAuthenticated();
Thanks
For TFS 2010, use the following:
TfsTeamProjectCollection collection = new TfsTeamProjectCollection(
new Uri("http://asebeast.cpsc.ucalgar.ca:8080/tfs/DefaultCollection",
new System.Net.NetworkCredential("domain_name\\user_name", "pwd"));
collection.EnsureAuthenticated();
I've been having the same problem. The above solution doesn't work for me and really can't figure out why. I keep getting a cast exception.
Spent a day trying to figure this out - so thought I'd share my current workaround to the problem.
I've created my own internal class that implements ICredentialsProvider - as below:
private class MyCredentials : ICredentialsProvider
{
private NetworkCredential credentials;
#region ICredentialsProvider Members
public MyCredentials(string user, string domain, string password)
{
credentials = new NetworkCredential(user, password, domain);
}
public ICredentials GetCredentials(Uri uri, ICredentials failedCredentials)
{
return credentials;
}
public void NotifyCredentialsAuthenticated(Uri uri)
{
throw new NotImplementedException();
}
#endregion
}
I then instantiate this and pass it in as below:
MyCredentials credentials = new MyCredentials(UserName, Password, Domain);
TfsTeamProjectCollection configurationServer =
TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
new Uri(tfsUri), credentials);
Note that I haven't implemented the NotifyCredentialsAuthenticated - not sure what this actually does, so left the NotImplementedException in there so I could catch when its called, which so far hasn't happened. Now successfully connected to TFS.
I've had some problems connecting to our old TFS 2008 server using this method as well, but the thing that solved my case was really simple:
First I defined the TFS Url to be:
private const string Tfs2008Url = #"http://servername:8080/tfs/";
static readonly Uri Tfs2008Uri = new Uri(Tfs2008Url);
The path used in the URL is the one we use when connecting via VisualStudio, so I thought this had to be the same in API calls, but when I tried to use this with the following authentication, I got a TF31002 / 404 error:
var collection = new TfsTeamProjectCollection(Tfs2008Uri,new NetworkCredential("AdminUser","password","domain_name"));
collection.EnsureAuthenticated();
But when I changed the Url to the TFS root, it authenticated OK!
private const string Tfs2008Url = #"http://servername:8080/";
static readonly Uri Tfs2008Uri = new Uri(Tfs2008Url);
Don't know if that helped anyone, but it sure did the trick for me!
This has worked pretty good for me:
_tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsUri);
_tfs.ClientCredentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential("myUserName", "qwerty_pwd", "myDomainName")));
_tfs.EnsureAuthenticated();

Resources