How do I change the "NativeHost" string on Windows Phone 7 webclient requests - windows-phone-7

I use WebClient for most of my requests from my WP7 app.
According to Google App Engine logs, the UserAgent is "NativeHost".
I would like to use appname, appversion + phone instead.
Is it possible to change this string when using a WebClient, or a GZip WebClient?

Okay, current working solution:
var headers = new WebHeaderCollection();
// http://dotnetbyexample.blogspot.fi/2011/03/easy-access-to-wmappmanifestxml-app.html
var am = new Util.AppManifest(); // gets appmanifest as per link above
var maker = Microsoft.Phone.Info.DeviceStatus.DeviceManufacturer;
var model = Microsoft.Phone.Info.DeviceStatus.DeviceName;
headers["user-agent"] = string.Format("{0} {1} {2} AppVersion {3}",
maker, model, "WP7.5", am.Version);
WebClient c = new WebClient();
c.Headers = headers;
Now, let's see how much info I can get on what make of phone the app is running on...

Yes, you will have to manually specify the UserAgent string on the WebClient class.
WebClient client = new WebClient ();
client.Headers.Add ("user-agent", "My App; V=2.1, PhoneType");
Obviously you will need to specify/derive the values you want to use in the UserAgent (AppName, Version and Phone).

Related

Cloud AutoML API has not been used in project 618104708054 before or it is disabled

I am trying to build a .NET small app to predict images using my model that was trianed on AutoML.
But I am getting this error:
Cloud AutoML API has not been used in project 618104708054 before or
it is disabled. Enable it by visiting
https://console.developers.google.com/apis/api/automl.googleapis.com/overview?project=618104708054
then retry. If you enabled this API recently, wait a few minutes for
the action to propagate to our systems and retry
First - this is not the project I am using.
Second - If I go to the link with my real project id - it says to me that the api is working well.
My code look like these:
public static string SendPOST(string url, string json)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "Bearer GOOGLE_CLOUD_TOKEN");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
//var res = new JavaScriptSerializer().Deserialize<Response>(result);
//return res;
return result;
}
}
I will appriciate your help,
Thanks.
I finally succeded to make it, the only issue is that I needed to create a service account using the web console:
https://console.cloud.google.com/projectselector/iam-admin/serviceaccounts?supportedpurview=project&project=&folder=&organizationId=
And then to download the json key and push it via the gcloud command from my PC -
gcloud auth activate-service-account --key-file="[/PATH/TO/KEY/FILE.json]
I found the solution in this post:
"(403) Forbidden" when trying to send an image to my custom AutoML model via the REST API

Upload photos to Google Photos API - Error 500

I'm getting the error below while trying to upload media to Google Photos API, following the docs
This is how i retrieve my bytes array:
And this is how i make the request:
I've tried a lot of things and none of it work...
Note: I'm consuming other Google Photos API endpoints, such as Get Albums, Create Albums, Get Media and everything work as expected. The upload media is the only one i'm having trouble with.
Note 2: The token is being sent correctly.
Note 3: All the origin endpoints were configured in the google console (localhost included) so much so that other endpoints are working correctly.
Anyone can give me a light?
I am writing something similar in C# and was able to work with the photo api. My best advice is to double check headers. I hope this helps, additionally I added a postman screenshot of a successful call to the api:
public async Task<GoogleApiResponse> UploadPhoto(StorageFile photo)
{
var userInfo = UserInfoVault.GetUserInfo();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userInfo.AccessToken);
client.DefaultRequestHeaders.Add("X-Goog-Upload-File-Name", photo.DisplayName);
var fileStream = await photo.OpenAsync(FileAccessMode.Read);
var reader = new DataReader(fileStream.GetInputStreamAt(0));
await reader.LoadAsync((uint)fileStream.Size);
byte[] pixels = new byte[fileStream.Size];
reader.ReadBytes(pixels);
var httpContent = new ByteArrayContent(pixels);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
HttpResponseMessage photoResponse = client.PostAsync(ApiEdnpoints.UploadPhoto, httpContent).Result;
string strResponse = await photoResponse.Content.ReadAsStringAsync();
return null;
}
Postman screenshot of successful call to upload a photo

Get "API key is missing" error when querying account details to Mailchimp API 3.0 using RestSharp

When using RestSharp to query account details in your MailChimp account I get a "401: unauthorized" with "API key is missing", even though it clearly isn't!
We're using the same method to create our RestClient with several different methods, and in all requests it is working flawlessly. However, when we're trying to request the account details, meaning the RestRequest URI is empty, we get this weird error and message.
Examples:
private static RestClient CreateApi3Client(string apikey)
{
var client = new RestClient("https://us2.api.mailchimp.com/3.0");
client.Authenticator = new HttpBasicAuthenticator(null, apiKey);
return client;
}
public void TestCases() {
var client = CreateApi3Client(_account.MailChimpApiKey);
var req1 = new RestRequest($"lists/{_account.MailChimpList}/webhooks", Method.GET);
var res1 = client.Execute(req1); // works perfectly
var req2 = new RestRequest($"automations/{account.MailChimpTriggerEmail}/emails", Method.GET);
var res2 = client.Execute(req2); // no problem
var req3 = new RestRequest(Method.GET);
var res3 = client.Execute(req3); // will give 401, api key missing
var req4 = new RestRequest(string.Empty, Method.GET);
var res4 = client.Execute(req4); // same here, 401
}
When trying the api call in Postman all is well. https://us2.api.mailchimp.com/3.0, GET with basic auth gives me all the account information and when debugging in c# all looks identical.
I'm trying to decide whether to point blame to a bug in either RestSharp or MailChimp API. Has anyone had a similar problem?
After several hours we finally found what was causing this..
When RestSharp is making the request to https://us2.api.mailchimp.com/3.0/ it's opting to omit the trailing '/'
(even if you specifically add this in the RestRequest, like: new RestRequest("/", Method.GET))
so the request was made to https://us2.api.mailchimp.com/3.0
This caused a serverside redirect to 'https://us2.api.mailchimp.com/3.0/' (with the trailing '/') and for some reason this redirect scrubbed away the authentication header.
So we tried making a
new RestRequest("/", Method.GET)
with some parameters (req.AddParameter("fields", "email")) to make it not scrub the trailing '/', but this to was failing.
The only way we were able to "fool" RestSharp was to write it a bit less sexy like:
new RestRequest("/?fields=email", Method.GET)

Windows.Web.Http.HttpClient + WEB API Windows Authentication

Im using Windows.Web.Http.HttpClient to connect to my WEB API. Application haven't prompted for userid and password, but recently i changed WEB API by moving AuthorizeAttribute filter from Action to Class level. Now my Windows store 8.1 application prompt for user id and password. Please let me know how to set HttpClient to not prompt the login and password. Can any1 suggest me do i need to add header to my httpcleint
using (Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient())
{
// Add a user-agent header
var headers = httpClient.DefaultRequestHeaders;
// The safe way to check a header value from the user is the TryParseAdd method
// Since we know this header is okay, we use ParseAdd with will throw an exception
// with a bad value - http://msdn.microsoft.com/en-us/library/windows/apps/dn440594.aspx
headers.UserAgent.ParseAdd("ie");
headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
using (var response = await httpClient.GetAsync(new Uri(url)))
I dont see a way to send Default credentials.
Disable UI dialogs using HttpBaseProtocolFilter.AllowUI. Try this:
Windows.Web.Http.Filters.HttpBaseProtocolFilter filter =
new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.AllowUI = false;
HttpClient client = new HttpClient(filter);
Uri uri = new Uri("http://localhost/?basic=1");
var response = await client.GetAsync(uri);
System.Diagnostics.Debug.WriteLine(response);
Do you need credentials? Use HttpBaseProtocolFilter.ServerCredential. Try this:
Uri uri = new Uri("http://localhost?ntlm=1");
Windows.Web.Http.Filters.HttpBaseProtocolFilter filter =
new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.AllowUI = false;
// Set credentials that will be sent to the server.
filter.ServerCredential =
new Windows.Security.Credentials.PasswordCredential(
uri.ToString(),
"userName",
"abracadabra");
HttpClient client = new HttpClient(filter);
var response = await client.GetAsync(uri);
System.Diagnostics.Debug.WriteLine(response);
Do you need default Windows credentials (domain credentials)? Simply add the Enterprise Authentication capability to your Package.appxmanifest.
I tried to apply your solution but it doesn't work as expected, or maybe I don't understand what I'm supposed to do.
I need to user the Windows credentials and I have enabled the Enterprise Authentification capability on my UWP app.
I use the code that you suggest:
var filter = new HttpBaseProtocolFilter();
filter.AllowUI = false;
var client = new HttpClient(filter);
HttpResponseMessage response = new HttpResponseMessage();
response = await client.PostAsync(concUri, null);
But the response returns me a 401.3 error...
If I add the login/password to the ServerCredential, this works well:
var filter = new HttpBaseProtocolFilter();
filter.AllowUI = false;
filter.ServerCredential = new Windows.Security.Credentials.PasswordCredential(WebServiceConstants.WebServiceUrl.ToString(), "login", "password");
var client = new HttpClient(filter);
HttpResponseMessage response = new HttpResponseMessage();
response = await client.GetAsync(concUri);
But I don't see what is the role of the Enterprise Authentication capability in this case, if I need to pass the login and the password...

Create Event C# SDK Failes - Getting (OAuthException) (#324) Missing or invalid image file

I am trying to create an event using the C# SDK. I am using the code from the following blog:
http://facebooksdk.blogspot.co.uk/2011/05/facebook-create-event.html
And I am using an image that I copied from an existing event on Facebook.
I am getting however the following error:
(OAuthException) (#324) Missing or invalid image file
Does anyone have an idea how to make it work?
Many thanks!
The code is as follows:
public string CreateEvent()
{
var fb = new FacebookWebClient();
Dictionary<string, object> createEventParameters = new Dictionary<string, object>();
createEventParameters.Add("name", "My birthday party )");
createEventParameters.Add("start_time", DateTime.Now.AddDays(2).ToUniversalTime().ToString(new CultureInfo("en-US")));
createEventParameters.Add("end_time", DateTime.Now.AddDays(2).AddHours(4).ToUniversalTime().ToString(new CultureInfo("en-US")));
createEventParameters.Add("owner", "Balaji Birajdar");
createEventParameters.Add("description", " ( a long description can be used here..)");
//Add the "venue" details for the event
JsonObject venueParameters = new JsonObject();
venueParameters.Add("street", "dggdfgg");
venueParameters.Add("city", "gdfgf");
venueParameters.Add("state", "gfgdfgfg");
venueParameters.Add("zip", "gfdgdfg");
venueParameters.Add("country", "gfdgfg");
venueParameters.Add("latitude", "100.0");
venueParameters.Add("longitude", "100.0");
createEventParameters.Add("venue", venueParameters);
createEventParameters.Add("privacy", "OPEN");
createEventParameters.Add("location", "fhdhdfghgh");
//Add the event logo image
//You can add the event logo too
FacebookMediaObject logo = new FacebookMediaObject()
{
ContentType = "image/jpeg",
FileName = #"C:\DevProjects\O2\o2PriorityFB\o2PriorityFB.Web\Images\logo.jpg"
};
logo.SetValue(System.IO.File.ReadAllBytes(logo.FileName));
createEventParameters["#file.jpg"] = logo;
JsonObject resul = fb.Post("/me/events", createEventParameters) as JsonObject;
return resul["id"].ToString();
}
You need to include a valid access token in the request. Also, I would recommend upgrading to V6 of the Facebook C# SDK. For the version you are using though you need to pass the access token into the constructor of FacebookWebClient as follows:
var fb = new FacebookWebClient("valid_facebook_access_token");

Resources