How to perform a get request with RestSharp? - windows-phone-7

I'm having trouble figuring out how to make a GET request using RestSharp on Windows Phone 7. All of the examples show making a POST request, but I just need GET. How do I do this?

GET is the default method used by RestSharp, so if you don't specify a method, it will use GET:
var client = new RestClient("http://example.com");
var request = new RestRequest("api");
client.ExecuteAsync(request, response => {
// do something with the response
});
This code will make a GET request to http://example.com/api. If you need to add URL parameters you can do this:
var client = new RestClient("http://example.com");
var request = new RestRequest("api");
request.AddParameter("foo", "bar");
Which translates to http://example.com/api?foo=bar

What you're looking for is located here.
The code snippet that covers your scenario is below (request.Method should be set to Method.GET):
public void GetLabelFeed(string label, Action<Model.Feed> success, Action<string> failure)
{
string resource = "reader/api/0/stream/contents/user/-/label/" + label;
var request = GetBaseRequest();
request.Resource = resource;
request.Method = Method.GET;
request.AddParameter("n", 20); //number to return
_client.ExecuteAsync<Model.Feed>(request, (response) =>
{
if (response.ResponseStatus == ResponseStatus.Error)
{
failure(response.ErrorMessage);
}
else
{
success(response.Data);
}
});
}

Related

Firebase OAuth Bearer token validation in a .NET WebApi eventually fails after running fine for a while

I'm having an issue where the token validation fails after some time (exactly when varies I think but usually counted in days). Restarting the app resolves the issue, so I think it's something wrong with how I initialize things.
I'm using Firebase and below is the bootstrapping code that runs at app startup.
I read in a comment on this old post https://stackoverflow.com/a/29779351/611441 that Google rotates certs, so now I'm thinking that might be the issue? I'm only fetching the certs once for the lifetime of the application. If that's the case, how would I be able to refresh these every now and then since this only runs at startup?
public void ConfigureAuthentication(IAppBuilder app)
{
var issuerSigningKeys = GetIssuerSigningKeys();
var firebaseAdminProjectId = ConfigurationManager.AppSettings.Get("FirebaseAdminProjectId");
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions()
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { firebaseAdminProjectId },
Provider = new OAuthBearerAuthenticationProvider
{
OnValidateIdentity = context =>
{
context.OwinContext.Set<bool>("OnValidateIdentity", true);
return Task.FromResult(0);
}
},
TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKeys = issuerSigningKeys,
ValidAudience = firebaseAdminProjectId,
ValidIssuer = ConfigurationManager.AppSettings.Get("FirebaseAdminValidIssuer"),
IssuerSigningKeyResolver = (arbitrarily, declaring, these, parameters) => issuerSigningKeys
}
});
}
private static List<X509SecurityKey> GetIssuerSigningKeys()
{
HttpClient client = new HttpClient();
var task = client.GetStringAsync("https://www.googleapis.com/robot/v1/metadata/x509/securetoken#system.gserviceaccount.com"));
task.Wait();
string jsonResult = task.Result;
//Extract X509SecurityKeys from JSON result
List<X509SecurityKey> x509IssuerSigningKeys = JObject.Parse(jsonResult)
.Children()
.Cast<JProperty>()
.Select(i => BuildSecurityKey(i.Value.ToString())).ToList();
return x509IssuerSigningKeys;
}
private static X509SecurityKey BuildSecurityKey(string certificate)
{
//Removing "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" lines
var lines = certificate.Split('\n');
var selectedLines = lines.Skip(1).Take(lines.Length - 3);
var key = string.Join(Environment.NewLine, selectedLines);
return new X509SecurityKey(new X509Certificate2(Convert.FromBase64String(key)));
}
I think I've finally figured this out.
First of all, the signing keys seems to be rotated every 5 days because they have a validity property set with a date. This makes sense with the pattern I see...
However, I think the issue is in my code. The TokenValidationParameters' property IssuerSigningKeyResolver expects a delegate. But I'm getting the keys and assigning them to a variable which in turn is assigned to the property. So the "resolver" always resolves the initial keys returned. They'll never refresh. The fix is to simply assign the GetIssuerSigningKeys() method to the property instead:
IssuerSigningKeyResolver = (arbitrarily, declaring, these, parameters) => GetIssuerSigningKeys()

MethodNotAllowedHttpException in compiled.php line 8518

Im sending request from salesforce to laravel then laravel return the result and display them on visual force page
Error Detail
Apex Method
public List<SelectOption> getItems()
{
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint('http://clozer.3spire.net/public/goclozer/country');
req.setMethod('GET');
req.setCompressed(false);
req.setBody('key1=value1&key2=value2');
req.setHeader('Content-Type', 'application/json');
try {
res = http.send(req);
} catch(System.CalloutException e) {
system.debug('Callout error: '+ e);
}
getAllCountry = (Map<String, String>)JSON.deserialize(res.getBody(),Map<String, String>.class);
List<SelectOption> option = new List<SelectOption>();
option.add(new SelectOption('0','--None--'));
for(String c : getAllCountry.values())
{
option.add(new SelectOption(c,c));
}
return option;
}
Expected Result
{"0":"Aruba","1":"Antigua and Barbuda","2":"United Arab Emirates","3":"Afghanistan","4":"Algeria","5":"Azerbaijan","6":"Albania","7":"Armenia","8":"Andorra","9":"Angola","10":"American Samoa","11":"Argentina","12":"Australia","13":"Ashmore and Cartier Islands"}
Laravel 5 Route
Route::get('/goclozer/country','GoClozerController#getCountry');
Laravel 5 Method
public function getCountry()
{
$country = \App\Country::all();
$names = array();
foreach($country as $c)
{
$names[] = $c->name;
}
echo json_encode($names,JSON_FORCE_OBJECT);
}
How can i get ride of this error
Thanks in advance
MethodNotAllowedHttpException means that you're using wrong HTTP verb ( Get, Post, Put, Delete ...). You've route defined for GET, but you may be posting data
The modification (as I assume you just want to retrieve the country names only) can be achieved by
$countries = Country::all(['name']);
this will only retrieve the names of the countries from the table, you can add more fields if you want to.
Controller gets a request, returns a response. You're not returning any response. just echoing the result. You can do the following,
return $countries;
This will simply return the JSON with country names.
You don't have to put an explicit slash at the front of route declaration. you can even write like the following and that will work too.
Route::get('goclozer/country','GoClozerController#getCountry');

Uploading images with redactor to MVC

This might be a bit too specific for here and I may need to contact redactor support but i've seen other questions about redactor here so i figured i'd give it a shot ...
Ok ...
So i'm trying to get get image uploading to work following the example here ...
http://imperavi.com/redactor/docs/images/
My client side code ...
$("textarea").redactor({
focus: true,
imageUpload: '/MyController/UploadImage'
});
My MVC controller action looks like this ...
public JsonResult UploadImage(object image)
{
// Do something with whatever that was i got from redactor
var result = new { filelink = "" };
return Json(result);
}
The problem is ... what did redactor actually give me?
Was it the whole file? a chunk? i can't seem to tell because the object has no type information at all and the raw post information seems way too little to actually be a whole image file.
Has anyone had any experience with this / actually done it before?
I don't really want to setup php on my server for this 1 function.
EDIT:
Ok a bit more digging reveals that if i pull the underlying Request object it has a files property which apparently contains my posted image file.
I think i might be able to figure it out from here.
Where I get a code block in place i'll post it as an answer.
You are receiving a HttpPostedFileBase object. Here is my implementation:
jQuery:
$('#blog-post').redactor(
{
imageUpload: '/blog/images/',
imageGetJson: '/images/locations/blogs/'
});
Then in the controller:
public ActionResult Images(HttpPostedFileBase file)
{
// Verify that the user selected a file
if( file != null && file.ContentLength > 0 )
{
// extract only the fielname
var fileName = Path.GetFileName( file.FileName );
// store the file
var path = Path.Combine( ImageLocation.BlogPicturePath, fileName );
file.SaveAs( path );
}
return Json( new { filelink = ImageLocation.BlogPictureUrl + "/" + file.FileName } );
}
ok um ... i think im there ...
This needs a bit of cleaning up and I don't expect you guys to understand what goes on under the bonnet of my custom DMS code but just assume it takes the stream and returns a FileInfo object and in theory this should work for you too ...
public ActionResult Upload()
{
// this object is specific to my system but all it does is
// stream the file to a path on the server (code not needed for this Q)
var dmsService = _kernel.Get<IDMSFileSystemService>();
List<FileInfo> savedFiles = new List<FileInfo>();
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
using (file.InputStream)
{
savedFiles.Add(dmsService.AddFromStream(file.InputStream, file.FileName);
}
}
var result = savedFiles.Select(f => new { filelink = f.Path}).ToArray();
return Json(result);
}
Suprisingly simple right ... :)

Add Linq statement to a Web API Get with a filter, i'm trying to add $select

I trying to apply some linq statements to all my Get Web api commands. I figured I could do this using an ActionFilterAttribute.
I'm basically adding $select support in web api since its currently not supported. I'm not sure where to get the IQueryable results. I believe I need it before sql execution happens but after Get function has returned the IQueryable result. Any help would be great. I'm trying something similiar to this post, but his idea will not work because HttpResponseMessage response = actionExecutedContext.Result; is no longer in RC.
Thanks
Nick
solution
public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
{
HttpRequestMessage request = actionExecutedContext.Request;
HttpResponseMessage response = actionExecutedContext.Response;
IQueryable obj;
if (response != null && response.TryGetContentValue(out obj) && request.RequestUri.ParseQueryString()["$select"] != null)
{
System.Collections.Specialized.NameValueCollection QueryItems = request.RequestUri.ParseQueryString();
string select = QueryItems["$select"];
if (!string.IsNullOrWhiteSpace(select))
{
obj = obj.Select(string.Format("new ({0})", select));
}
//
//this should be generic not hard coded for Json
//
string json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse();
actionExecutedContext.Response.Content = new StringContent(json);
actionExecutedContext.Response.Content.Headers.Clear();
actionExecutedContext.Response.Content.Headers.Add("Content-Type", "application/json");
actionExecutedContext.Response.StatusCode = System.Net.HttpStatusCode.OK;
}
}
see the original post above. I added the solution to the bottom.

Object XMLHttpRequest to JSON

I am creating an jquery ajax form which calls the method below
public string GetRestaurantInfo(string date, string pageId)
{
Node node = new Node(Convert.ToInt32(pageId));
string day = DateTime.Parse(date).DayOfWeek.ToString();
return JsonConvert.SerializeObject(GetOpeningHours(node, day));
}
private static object GetOpeningHours(Node node, string day)
{
XDocument xmlDoc = XDocument.Parse(node.GetProperty("openingHours").ToString());
var q = from item in xmlDoc.Descendants("scheduleItem")
where item.Element("weekDayLocal").Value == day
select new
{
day = item.Element("weekDayLocal").Value,
startTime = item.Element("firstSet").Element("hourStart").Value,
closingTime = item.Element("firstSet").Element("hourEnd").Value,
hoursOpen = 4
};
return q;
}
I would like the data to be returned in a JSON format, but it is returning the data in the following format
{"d":" [{\"day\":\"Tuesday\",\"startTime\":\"17:00\",\"closingTime\":\"11:00\",\"hoursOpen\":4}]"}
I am not sure how to resolve this? Any ideas?
Thanks in advance for any help
I assume this thread was not answered, and I found this thread when I Google as I faced the same issue too. After a struggle with Firebug, The solution was simple in the end. You just have to parse it twice as in the following code. But I am not sure whether this is the correct solution, or is this an impact in the web service call that I tried to make.
JSON.parse(JSON.parse(result).d)
Anyway just for some one who want to know the web service call,
xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//xhr.responseText; this contains the data
}
}
};
xhr.send(params);
Thanks,
Sabo
Well that is jSon i suppose. Did you try doing below in the callback javascript function.
function callback(rslt,cntxt){
var result = Sys.Serialization.JavaScriptSerializer.deserialize(rslt);
console.dir(result);
}
watch the firebug console and inspect the object that was dumped.

Resources