How can I upload a file to rackspace using RESTSharp and .net 4.0? - .net-4.0

Here is what i have so far and it's not working:
private void _send1(string file)
{
var client = new RestClient("https://identity.api.rackspacecloud.com/v2.0");
var request = new RestRequest("tokens", Method.POST);
request.RequestFormat = DataFormat.Json;
string test = "{\"auth\":{\"RAX-KSKEY:apiKeyCredentials\"{\"username\":\"";
test += UserName;
test += "\",\"apiKey\":\"";
test += MyToken;
test += "\"}}}";
request.AddBody(serText);
request.AddParameter("application/json", test, ParameterType.RequestBody);
RestResponse response = (RestResponse)client.Execute(request);
// Content = "{\"badRequest\":{\"code\":400,\"message\":\"java.lang.String cannot be cast to org.json.simple.JSONObject\"}}"
}
note: UserName and apiKey are valid RackSpace credentials :-)
Thanks
In advance
Try 2: ( found this on the web ) and it gives me a token... now what do I do with it?
private void _send2(string file)
{
Dictionary<string, object> dictAuth = new Dictionary<string, object>();
dictAuth.Add("RAX-KSKEY:apiKeyCredentials", new { username = UserName, apiKey = MyToken });
var auth = new
{
auth = dictAuth
};
RestClient client = new RestClient("https://identity.api.rackspacecloud.com");
RestSharp.RestRequest r = new RestRequest("/v2.0/tokens", Method.POST);
r.AddHeader("Content-Type", "application/json");
r.RequestFormat = DataFormat.Json;
r.AddBody(auth);
RestResponse response = (RestResponse)client.Execute(r);
// Content = "{\"access\":{\"token\":{\"id\":\"AACCvxjTOXA\",\"expires\":\"2016-04-09T21:12:10.316Z\",\"tenant\":{\"id\":\"572045\",\"name\...
}
moving just a bit further:
I have create a class that parses out the URL, tenantID and token from Step 2 above
This data is passed to the PostFile call:
private void PostFile(string url, string tenantID, string token, string file)
{
string fName = Path.GetFileName(file);
RestClient client = new RestClient(url);
string baseURL = string.Format("v1/{0}/Support/{1}", tenantID, fName);
RestRequest r = new RestRequest(baseURL, Method.POST);
r.AddHeader("Content-Type", "text/plain");
r.AddParameter("X-Auth-Token", token);
r.AddFile(fName, file);
RestResponse response = (RestResponse)client.Execute(r);
if( response.StatusCode == System.Net.HttpStatusCode.OK)
{
int x = 0;
}
}
Here is what finally worked:
bool bRetval = false;
string fName = Path.GetFileName(file);
RestClient client = new RestClient(url);
string baseURL = string.Format("/Support/{0}", fName);
RestRequest r = new RestRequest(baseURL, Method.PUT);
r.AddHeader("Content-Type", "text/plain");
r.AddHeader("X-Auth-Token", token);
r.AddFile(fName, file);
RestResponse response = (RestResponse)client.Execute(r);

See the above post for the supporting functions that lead up to this one
private bool PostFile(string url, string token, string file)
{
bool bRetval = false;
string fName = Path.GetFileName(file);
RestClient client = new RestClient(url);
string baseURL = string.Format("/Support/{0}", fName);
RestRequest r = new RestRequest(baseURL, Method.PUT);
r.AddHeader("Content-Type", "text/plain");
r.AddHeader("X-Auth-Token", token);
r.AddFile(fName, file);
RestResponse response = (RestResponse)client.Execute(r);
if ( response.StatusCode == System.Net.HttpStatusCode.Created)
{
bRetval = true;
}
return bRetval;
}

Related

Google API Calendar OAUTH2 The remote server returned an error: (404) Not Found

async void GetEvent(string access_token) {
String serviceURL = "https://www.googleapis.com/calendar/v3/calendars/{email}/events";
String url = string.Format(serviceURL + "&key={0}&scope={1}", clientSecret, "https://www.googleapis.com/auth/calendar.events.readonly");
// sends the request
HttpWebRequest userinfoRequest = (HttpWebRequest)WebRequest.Create(url);
userinfoRequest.Method = "GET";
userinfoRequest.Headers.Add(string.Format("Authorization: Bearer {0}", access_token));
userinfoRequest.ContentType = "application/json";
userinfoRequest.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
userinfoRequest.UseDefaultCredentials = true;
userinfoRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
// gets the response
WebResponse userinfoResponse = await userinfoRequest.GetResponseAsync();
using (StreamReader userinfoResponseReader = new StreamReader(userinfoResponse.GetResponseStream())) {
// reads response body
string userinfoResponseText = await userinfoResponseReader.ReadToEndAsync();
output(userinfoResponseText);
}
}

Report Viewer and Web Api

In MVC I could generate .xsl or .pdf file with no issues with File(), but with the web Api nothing is happening when the action is fired! This is what I have tried so far.
I have tried a couple of solutions in here including this one Web API and report viewer
but nothing has worked for me.
public HttpResponseMessage Export(ExportVolunteerSearchFilter searchModel)
{
if (searchModel.Equals(null))
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
var volunteers = _volunteersService.ExportAllVolunteersData(searchModel);
ReportViewer ReportViewer1 = new ReportViewer();
ReportViewer1.SizeToReportContent = true;
ReportViewer1.LocalReport.ReportPath =
System.Web.HttpContext.Current.Server.MapPath("~/Reports/VolunteersReport.rdlc");
ReportViewer1.LocalReport.EnableExternalImages = true;
ReportViewer1.LocalReport.DataSources.Clear();
ReportDataSource _rsource = new ReportDataSource("DataSet1", volunteers);
ReportViewer1.LocalReport.DataSources.Add(_rsource);
ReportViewer1.LocalReport.Refresh();
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string fileName = "reportVolunteer";
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/Reports/VolunteersReport.rdlc"), FileMode.Open);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xls");
return response;
}
I have done it as:-
response.Content = new PushStreamContent(
async (outstream) =>
{
await getDataMethod(outstream)
},
new MediaTypeHeadrerValue(mediaType:"application/xls"));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = $"test.xls"
};
return response;

How to solve this circular dependency problem?

I have two interfaces for components that each requires functionality from the other one. One that generates Oauth tokens, and another one that gets secrets from a secret provider (Azure Key Vault).
The problem is that the Token Provider needs to obtain a secret value (a password) to make its HTTP call, and the Secret Provider class needs to get a Token in order to call Azure. Chicken and Egg problem.
From the other questions I've read, one suggestion is to create a third class/interface on which the original 2 depend, but I'm not sure how that would work here.
Any help and suggestions would be appreciated. Code for all relevant classes/interfaces is shown below.
public interface ISecretProvider
{
string GetSecret(string secretName);
}
public interface ITokenProvider
{
string GetKeyVaultToken();
}
public class OktaTokenProvider : ITokenProvider
{
ISecretProvider _secretProvider;
public string GetKeyVaultToken()
{
var tokenUrl = ConfigurationManager.AppSettings["KeyVault.Token.Url"];
var clientId = ConfigurationManager.AppSettings["KeyVault.Token.ClientId"];
var clientSecret = _secretProvider.GetSecret("ClientSecret");
var scope = ConfigurationManager.AppSettings["KeyVault.Scope"];
var token = GetToken(tokenUrl, clientId, clientSecret, scope);
return token;
}
private string GetToken(string tokenUrl, string clientId, string clientSecret, string scope)
{
var clientCredentials = $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"))}";
string responseFromServer = string.Empty;
bool success = false;
int retryCount = 0;
while (!success)
{
try
{
var tokenWebRequest = (HttpWebRequest)WebRequest.Create(tokenUrl);
tokenWebRequest.Method = "POST";
tokenWebRequest.Headers.Add($"Authorization:{clientCredentials}");
tokenWebRequest.Headers.Add("Cache-control:no-cache");
tokenWebRequest.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(tokenWebRequest.GetRequestStream()))
{
streamWriter.Write($"grant_type=client_credentials&scope={scope}");
streamWriter.Flush();
streamWriter.Close();
}
using (WebResponse response = tokenWebRequest.GetResponse())
{
using (var dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
reader.Close();
}
dataStream.Close();
}
response.Close();
response.Dispose();
}
success = true;
}
catch (Exception)
{
if (retryCount > 3)
{
throw;
}
else
{
retryCount++;
}
}
}
JToken token = JObject.Parse(responseFromServer);
var accessToken = $"Bearer {token.SelectToken("access_token").ToString()}";
return accessToken;
}
}
public class KeyVaultSecretProvider : ISecretProvider
{
ITokenProvider _tokenProvider;
public KeyVaultSecretProvider(ITokenProvider tokenProvider)
{
_tokenProvider = tokenProvider;
}
public string GetSecret(string secretName)
{
var KeyVaultUrl = ConfigurationManager.AppSettings[Constants.KEYVAULT_ENDPOINT];
var subscriptionKey = ConfigurationManager.AppSettings[Constants.KEYVAULT_SUBSCRIPTION_KEY];
string responseFromServer = "";
var requestedSecretUrl = $"{KeyVaultUrl}{secretName}";
var secretWebRequest = (HttpWebRequest)WebRequest.Create(requestedSecretUrl);
var accessToken = _tokenProvider.GetKeyVaultToken();
secretWebRequest.Method = "GET";
secretWebRequest.Headers.Add("authorization:" + accessToken);
secretWebRequest.Headers.Add("cache-control:no-cache");
secretWebRequest.Headers.Add("Ocp-Apim-Subscription-Key:" + subscriptionKey);
using (WebResponse response = secretWebRequest.GetResponse())
{
using (var dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
reader.Close();
}
dataStream.Close();
}
response.Close();
response.Dispose();
}
JToken secret = JObject.Parse(responseFromServer);
var secretValue = secret.SelectToken("Secret").ToString();
return secretValue;
}
}
Have a single class implement both interfaces. The two responsibilities are inter-dependent, so put them together in one class. There is nothing wrong with this.

how to make a request to my .NET Core App from UWP, with Microsoft Account Authentication

Update
some code on web side
startup.cs
app.UseOAuthAuthentication(new OAuthOptions()
{
AuthenticationScheme = "Microsoft-AccessToken",
DisplayName = "MicrosoftAccount-AccessToken",
ClientId = {CliendID},
ClientSecret = {ClientSecret},
CallbackPath = new PathString("/signin-microsoft-token"),
AuthorizationEndpoint = MicrosoftAccountDefaults.AuthorizationEndpoint,
TokenEndpoint = MicrosoftAccountDefaults.TokenEndpoint,
UserInformationEndpoint = MicrosoftAccountDefaults.UserInformationEndpoint,
Scope = { "https://graph.microsoft.com/user.read" },
SaveTokens = true,
Events = new OAuthEvents()
{
OnCreatingTicket = async context =>
{
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
response.EnsureSuccessStatusCode();
var user = JObject.Parse(await response.Content.ReadAsStringAsync());
var identifier = user.Value<string>("id");
if (!string.IsNullOrEmpty(identifier))
{
context.Identity.AddClaim(new Claim(
ClaimTypes.NameIdentifier, identifier,
ClaimValueTypes.String, context.Options.ClaimsIssuer));
}
var userName = user.Value<string>("displayName");
if (!string.IsNullOrEmpty(userName))
{
context.Identity.AddClaim(new Claim(
ClaimTypes.Name, userName,
ClaimValueTypes.String, context.Options.ClaimsIssuer));
}
var email = user.Value<string>("userPrincipalName");
if (!string.IsNullOrEmpty(email))
{
context.Identity.AddClaim(new Claim(
ClaimTypes.Email, email,
ClaimValueTypes.Email, context.Options.ClaimsIssuer));
}
}
}
});
HomeController.cs
[Authorize]
public string GetInfo()
{
return "Hello world!";
}
I am able to retrieve user's token with code like this
string MicrosoftClientID = {ClientID};
string MicrosoftCallbackURL = "urn:ietf:wg:oauth:2.0:oob";
string scope = WebUtility.UrlEncode("openid offline_access https://graph.microsoft.com/user.read");
string MicrosoftURL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?client_id=" + MicrosoftClientID + "&response_type=code&redirect_uri=" + MicrosoftCallbackURL + "&response_mode=query&scope=" + scope;
Uri StartUri = new Uri(MicrosoftURL);
Uri EndUri = new Uri(MicrosoftCallbackURL);
WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
StartUri,
EndUri);
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
string code = WebAuthenticationResult.ResponseData.Replace("urn:ietf:wg:oauth:2.0:oob?code=", "");
string strContent = "client_id=" + MicrosoftClientID + "&scope=" + scope + "&code=" + code + "&redirect_uri=" + MicrosoftCallbackURL + "&grant_type=authorization_code";
HttpClient httpClient = new HttpClient();
HttpContent httpContent = new StringContent(strContent);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("https://login.microsoftonline.com/consumers/oauth2/v2.0/token", httpContent);
string stringResponse = await httpResponseMessage.Content.ReadAsStringAsync();
}
but how can i use the token to make a request to API of my .NET Core Web application, which is hosted on azure?
I have tried these
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationModel.AccessToken);
string apicontent = await httpClient.GetStringAsync("https://{host}.azurewebsites.net/home/GetInfo");
apicontent.ToString();
all I got is html of login page
Any help please?
This Authorize is as same as an normal web application.
If you don't want to authenticate the user when you call this API, you can remove the attribure [Authorize] for the GetInfo. And if you also have [Authorize] attribure for the controller, you can add [AllowAnonymous] attribute to specify this action is skipped by AuthorizeAttribute during authorization.
You can refer to here about Authentication and Authorization.
Let's start from the Web Api:
Here is my sample method to retrieve friends list from the Api.
Note that there is "Route prefix" attribute - to indicate which resource I would like to retrieve and "Authorize" attribute to demand authentication before calling this method:
[RoutePrefix("api/Friends")]
public class FriendsController : ApiController
{
[Authorize]
[Route("GetConfirmedFriends")]
public IHttpActionResult GetConfirmedFriends()
{
using (DbWrapper dbContext = new DbWrapper())
{
return Ok(dbContext.GetConfirmedFriends());
}
}
}
Now in the UWP application you will call this method like below:
public async Task<ObservableCollection<Friend>> GetConfirmedFriends()
{
//access token eretrieved after MS authentication:
if (_accessToken == null)
throw new NullReferenceException("Access token cannot be empty. Please authenticate first");
try
{
using (HttpClient client = new HttpClient())
{
ObservableCollection<Friend> friends = null;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _accessToken);
var data = await client.GetAsync(string.Concat(https://{host}.azurewebsites.net/, "api/Friends/GetConfirmedFriends"));
var jsonResponse = await data.Content.ReadAsStringAsync();
if (jsonResponse != null)
friends = JsonConvert.DeserializeObject<ObservableCollection<Friend>>(jsonResponse);
return friends;
}
}
catch (WebException exception)
{
throw new WebException("An error has occurred while calling GetConfirmedFriends method: " + exception.Message);
}
}
Please check and let me know.

IAsyncResult in WP7, how to know when an async method will be finished?

public string MyMethod(string param1)
{
var url = string.Format(UrlMask, HttpUtility.UrlEncode(param1), Login, ApiKey);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.BeginGetResponse(result =>
{
var requestInternal = (HttpWebRequest)result.AsyncState;
var response = (HttpWebResponse)requestInternal.EndGetResponse(result);
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
var resultXml = XDocument.Load(response.GetResponseStream());
var x = from r in resultXml.Descendants("node")
select r.Element("element").Value;
}
}, request);
return null;
}
MyMethod should return the string value when a lambda function will be finished. My questions are:
how can I know when the lambda function inside
request.BeginGetResponse will be finished?
how MyMethod will be know about it to return value?
To see when the lambda is finished you could use a ManualResetEvent like this:
public string MyMethod(string param1)
{
const int timeOutInMs = 1000;
using (ManualResetEvent ended = new ManualResetEvent(false))
{
var url = string.Format(UrlMask, HttpUtility.UrlEncode(param1), Login, ApiKey);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.BeginGetResponse(result =>
{
var requestInternal = (HttpWebRequest) result.AsyncState;
var response = (HttpWebResponse) requestInternal.EndGetResponse(result);
using (
StreamReader streamReader =
new StreamReader(response.GetResponseStream()))
{
var resultXml = XDocument.Load(response.GetResponseStream());
var x = from r in resultXml.Descendants("node")
select r.Element("element").Value;
}
ended.Set();
}, request);
if (!ended.WaitHandle.WaitOne(timeOutInMs))
{
throw new TimeoutException("lambda took too long to complete");
}
}
return null;
}