I am trying to upload photos form Windows phone (mango) to facebook with BackgroundTransferRequest object. This is because I want to upload photos even if the app is not running.
I am using facebook C# SDK to get access token etc and which works great but to upload using this, we need to keep the APP active.
I can use fiddler and create a Post request with access token and upload the image to facebook to a album.
https://graph.facebook.com/178040612256938/Photos/?access_token=AAACEdEose0cBAA4p0Ozqj0H39RP2tGyxdq0LAxoADyBZCPgjgrXMwU93VAOVkulemC3ZC5lVZCTiJ3rYeFXtM67tYNEZBvPQmasbT9AvX
Now, here is my code that I took off of sample here - http://msdn.microsoft.com/en-us/library/hh202959(v=vs.92).aspx
I am not sure how to add headers that fiddler adds OR how to use this for uploading photos to FB. getting 400 as response. Currently the following code can upload photo to my WCF service.
also looked at - BackgroundTransferRequest WP7
IsolatedStorageFileExtensions.SavePicture(Path.Combine(TransfersFiles, picture.FileName), picture.Data);
string fbURL = #"https://graph.facebook.com/106216062727932/Photos/?access_token=AAACEdEose0cBAA4p0Ozqj0H39RP2tGyxdq0LAxoADyBZCPgjgrXMwU93VAOVkulemC3ZC5lVZCTiJ3rYeFXtM67tYNEZBvPQmasbT9AvD";
var transferRequest = new BackgroundTransferRequest(new Uri(fbURL, UriKind.Absolute));
if (!_wifiOnly)
{
transferRequest.TransferPreferences = TransferPreferences.AllowCellular;
}
if (!_externalPowerOnly)
{
transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
}
if (!_wifiOnly && !_externalPowerOnly)
{
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
}
//this is the place to upload to Facebook
transferRequest.Method = "POST";
//_OLD transferRequest.UploadLocation = new Uri(TransfersFiles + #"\" + picture.FileName, UriKind.Relative);
transferRequest.UploadLocation = new Uri(TransfersFiles + #"\" + picture.FileName, UriKind.Relative);
string boundary = DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
//---
transferRequest.TransferStatusChanged += OnTransferStatusChanged;
transferRequest.TransferProgressChanged += OnTransferProgressChanged;
BackgroundTransferService.Add(transferRequest);
Related
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
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
I am using Web Client to download yammer attachments i tried to use all different URL's available by yammer API / browser :
-download URL
-large preview URL
-right click and copy image URL
file is downloaded with 0 bytes
any suggestion ?
to download Yammer attachments you need both Download URl and Access token as below
string Path = #"C:\SocialMediaDownloads\Yammer\Attachments\"+MessageId;
bool isExists = System.IO.Directory.Exists(Path);
if (!isExists)
System.IO.Directory.CreateDirectory(Path);
WebClient client = new WebClient();
client.BaseAddress = "https://www.yammer.com";
client.Headers["Authorization"] = "Bearer " + accessToken;
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadFileAsync(new Uri(URL),Path+#"\"+FileName);
return Path;
}
We are trying to upload image to Twitter via silverlight code in WP7. We are able to post the message but not the image.
We tried all including download of their library but not getting the hint.
In following link,
https://dev.twitter.com/docs/api/1/post/statuses/update_with_media
there is one point which we are not able to set.
"Unlike POST statuses/update, this method expects raw multipart data. Your POST request's Content-Type should be set to multipart/form-data with the media[] parameter "
I am not getting it how to put it.
Can anyone please guide me or provide sample for image upload?
If your photo is called LoadedPhoto, you could create a memory stream from it
MemoryStream ms = new MemoryStream();
LoadedPhoto.SaveJpeg(ms, LoadedPhoto.PixelWidth, LoadedPhoto.PixelHeight, 0, 100);
Create OAuthCredentials object according to the authentication details you have acquired
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = Common.TwitterSettings.ConsumerKey,
ConsumerSecret = Common.TwitterSettings.ConsumerKeySecret,
Token = file.AccessToken,
TokenSecret = file.AccessTokenSecret,
Version = "1.0"
};
Create a RestClient and a RestRequest
var restClient = new RestClient
{
Authority = "https://upload.twitter.com"
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = "/1/statuses/update_with_media.xml",
Method = Hammock.Web.WebMethod.Post
};
Set the stream position to 0
ms.Position = 0;
Add fields to RestRequest
restRequest.AddField("status", message);
restRequest.AddFile("media[]", "ScreenShot.png", ms, "image/jpeg");
And then begin request
restClient.BeginRequest(restRequest, callback);
callback is a callback method for the request.
Taken from my blog post, see there for more details if you're interested.
I have a WP7 app using facebook SDK 5.4.1. I try to upload a photo to Facebook, but always get an error message "(OAuthException) (#1) An unknown error occurred".
Here is my code:
var app = new Facebook.FacebookApp(AuthKey);
var parameters = new Dictionary<string, object>
{
{"message","test"},
{"description","test2"}
};
FacebookMediaObject media = new FacebookMediaObject
{
FileName = "1",
ContentType = "image/jpeg"
};
WriteableBitmap wb = new WriteableBitmap(0, 0).FromResource("/Images/thumbnails/Color.png");
media.SetValue(wb.ToByteArray());
parameters.Add("source", media);
app.PostAsync("me/photos", parameters, new FacebookAsyncCallback(postResult));
I can post a message on FB wall using my app, but not for uploading photos(I tried to upload different sizes of photo). What can be wrong? Thanks
You can't use wb.toByteArray() - you need to encode the image to JPEG before uploading it.
Extensions.SaveJpeg() is what you are looking for (here)