How would you detect the current browser in an Api Controller? - c#

I'm trying to detect the current web browser within one of my Api Controllers in my program using MVC4. Everywhere I look people say to use Request.Browser, however I can't get that to work. Any suggestions or is there something I'm overlooking?

You can use the HttpBrowserCapabilities in System.Web like this
var userAgent = HttpContext.Current.Request.UserAgent;
var userBrowser = new HttpBrowserCapabilities { Capabilities = new Hashtable { { string.Empty, userAgent } } };
var factory = new BrowserCapabilitiesFactory();
factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser);
//Set User browser Properties
BrowserBrand = userBrowser.Browser;
BrowserVersion = userBrowser.Version;
This relies on browscap.ini in Windows/System32/inetsrv/ or Windows/SysWOW64/inetsrv for definitions.
This article may also help - http://stephenwalther.com/archive/2010/03/05/use-asp-net-4-browser-definitions-with-asp-net-3-5

You could do something like following too from within the Web API's action:
System.Net.Http.HttpRequestMessage currentRequest = this.Request;
System.Net.Http.Headers.HttpHeaderValueCollection<System.Net.Http.Headers.ProductInfoHeaderValue> userAgentHeader = currentRequest.Headers.UserAgent;

Related

Issues publishing image to Facebook Page via Graph API SDK .NET

Attempting this on .NET Core 3.1
After several hours of trying to publish a photo to my public facebook page (as in business page) of which I am the admin and have a long-term token for...
I keep getting the following response to my request using the official Facebook SDK for .NET. However, the image itself is never loaded.
{{"id":"786692942226147","post_id":"113260773923227_786692942226147"}}
The request looks like
var imageMedia = new FacebookMediaObject { FileName = file.FileName, ContentType = file.ContentType };
var stream = file.OpenReadStream();
var bytes = await stream.ReadAsByteArrayAsync();
imageMedia.SetValue(bytes);
var fbClient = new FacebookClient(credential.Token)
{
AppId = _config.GetValue<string>("FacebookClientId"),
AppSecret = _config.GetValue<string>("FacebookSecret")
};
dynamic parameters = new ExpandoObject();
parameters.message = request.Message;
parameters.file = imageMedia;
var result = await fbClient.PostTaskAsync($"{credential.PageId}/photos", parameters, token);
I'm sure it has something to do with the parameters I'm passing in, like parameters.file... but the docs for this thing are VERY unclear... as in "literally does not exist"
Anyone with experience getting this working, please point me in the right direction?
The solution is to change parameters.file to parameters.image...

In Google.Apis.Pagespeedonline.v5 how to get all categories in one call?

I am using Google.Apis.Pagespeedonline.v5 (nuget) to perform the analysis on my site.
By performing the analysis directly from the API Explorer site you can perform the test on all five categories.
https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed
However, using the dotnet api, the category parameter only accepts one CategoryEnum, so, I can only get the result in one category per request.
I wonder if it is possible to get all categories in a single request
var initializer = new Initializer()
{
ApiKey = "XXXXXXXXXXXXXXX",
BaseUri = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed",
GZipEnabled = true
};
var service = new PagespeedonlineService(initializer);
var request = new RunpagespeedRequest(service, "https://www.google.com");
request.Category = CategoryEnum.Accessibility;
request.Locale = "pt";
request.Strategy = StrategyEnum.Desktop;
var response = request.Execute();
Well, you can do it this way:
GET https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?category=ACCESSIBILITY&category=PERFORMANCE&locale=pt&strategy=DESKTOP&url=https%3A%2F%2Fwww.google.com%2F&prettyPrint=true&key=[YOUR_API_KEY] HTTP/1.1
But in your situation maybe you can change base URL to look like:
BaseUri = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?category=ACCESSIBILITY&category=PERFORMANCE"
Give it a try this way

Access Moodle API from .Net Console Application

For one of my projects I need to manage some of the attributes of our Moodle, including (but probably not limited to) Creating/Updating users and managing enrolments.
I need to create this interface in a .Net (4.0+) Console application, so information can be processed from other systems.
I have checked NuGet for packages for Moodle but I cant find anything.
Can you advise on how I could achieve this interface?
Thanks in advance.
I don't think there is a wrapper available for this. You will need to enable moodle webservices:
https://docs.moodle.org/dev/Web_services
And create your own. I am using RestSharp for this:
https://www.nuget.org/packages/RestSharp
This code will work for accessing course information
string result = "";
string methodName = "GetCourse";
string apiName = "core_course_get_courses";
string apiCall = moodleUrl + "?wstoken=" + token + "&wsfunction=" + apiName + "&moodlewsrestformat=json";
try
{
using (WebClient client = new WebClient())
{
client.BaseAddress = apiCall;
client.Headers[HttpRequestHeader.Accept] = "application/json";
result = client.DownloadString(apiCall);

Google Custom Site Search Api C# Paging

I am using the Google C# API for the Custom Search and have it working and returning results, however I cannot see a way to make the paging work correctly.
Looking at what I get returned, no where does it tell me how many pages there are in the result? It just has a .Start property? Which is not much good unless I know how many 'pages' of results I have?
Am I missing something stupid here? Here is an example of the code I have so far
var svc = new CustomsearchService(new BaseClientService.Initializer { ApiKey = settings.GoogleCustomSearchApi });
var listRequest = svc.Cse.List(searchTerm);
listRequest.Cx = settings.GoogleCustomSearchEngineId;
listRequest.ImgSize = CseResource.ListRequest.ImgSizeEnum.Medium;
listRequest.Num = 10;
// List to hold everything in
var resultItems = new List<Google.Apis.Customsearch.v1.Data.Result>();
// Result set 1
listRequest.Start = 1;
var search = listRequest.Execute();
resultItems.AddRange(search.Items);
I have resulted at the moment to doing two or three calls one after the other and getting a load of results back. But I would prefer to have this properly paged.
The JSON API response has totlResults field:
https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response.
It should be exposed under search.Queries
Found it, its in
search.SearchInformation.TotalResults

Mock User Agent

I'm writing unit tests in which I need a fake HttpContext. I used the HttpSimulator from Phil Haack (http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx).
But an function in the Sitecore api throws an exception on the following code:
request.Browser.Browser.IndexOf("IE", StringComparison.OrdinalIgnoreCase) > -1;
I debugged my code and the request.Browser.Browser is empty. I tried to fill the property with Moq but I get an exception. I also tried to add it as a header.
My code looks like this:
using (HttpSimulator simulator = new HttpSimulator("/", "localpath"))
{
//NameValueCollection nvc = new NameValueCollection { { "User-Agent", "IE" } };
//simulator.SimulateRequest(new Uri("http://www.foo.bar"), HttpVerb.GET, nvc);
simulator.SimulateRequest();
var browserMock = new Mock<HttpBrowserCapabilities>();
browserMock.SetupAllProperties();
//browserMock.SetupProperty(b => b.Browser, "IE");
HttpContext.Current.Request.Browser = browserMock.Object;
}
Does anyone know how i can mock this property?
Actually this is possible - you can set the Browser property directly on the request:
httpSim.SimulateRequest(new Uri("http://www.test.com"));
HttpContext.Current.Request.Browser = new HttpBrowserCapabilities
{
Capabilities = new Dictionary<string,string>
{
{"majorversion", "8"},
{"browser", "IE"},
{"isMobileDevice","false"}
}
};
This can not be done, you will have to use the HttpContextBase e.d. classes in MVC. Turns out unit testing with web forms is messy(?)

Categories

Resources