Facebook C# SDK WP7 - Can't upload photo to Facebook - c#

I'm trying to upload a photo to facebook using the Facebook C# SDK with WP7.
Here's my code:
public void PostMessageWithImage(string statusMessage, Stream stream)
{
FacebookClient fb = new FacebookClient(AccessToken);
FacebookMediaStream mediaStream = new FacebookMediaStream
{
FileName = DateTime.Now.ToLocalTime().ToLongDateString(),
ContentType = "image/jpeg",
}.SetValue(stream);
fb.PostCompleted += MessagePostCompleted;
fb.PostAsync(this.id + "/photos", new
{
message = statusMessage, //already tried name and caption
source = mediaStream
});
}
I keep getting this:
(OAuthException - #1) (#1) An unknown error occurred
at Facebook.FacebookClient.ProcessResponse(HttpHelper httpHelper, String responseString, Type resultType, Boolean containsEtag, IList`1 batchEtags)
at Facebook.FacebookClient.<>c__DisplayClass4.<ApiAsync>b__1(Object o, OpenReadCompletedEventArgs e)
This code was working fine four months ago, but now I just can't upload photos to Facebook. It only works when I use a url instead of a file. Could you help me?

i got same error.
that my code :
dynamic argumentContent = new ExpandoObject();
argumentContent.message = imageDesc;
if (!string.IsNullOrEmpty(imageUrl))
argumentContent.url = imageUrl;
else
argumentContent.source = new FacebookMediaObject
{
ContentType = "image/jpeg",
FileName = FormatUploadPictureFileName()
}.SetValue(imageBytes);
FacebookClient fbClient = new FacebookClient(accessToken);
fbClient.PostTaskAsync("me/photos", argumentContent);
fbClient.PostCompleted += (postContent, Ex) =>
{});
soluction:
if this image create with your code and format as stream. so you will got this error.
first you need save it as png/jpeg file to isolate storage .
then read it and format to bytes[] array from local isolate storage .
you will found it's work.

Related

C# app "upload file to google drive" request returning as null

I have a C# desktop app which allows the user to backup its to google drive via the google drive api V3.
I have the following method in a class which is used to load the backups
static string[] Scopes = { DriveService.Scope.DriveFile };
static string ApplicationName = "MyApp";
private static string CreateFile(string pFilePath, string parentFolderId, DriveService service)
{
var fileMetaData = new Google.Apis.Drive.v3.Data.File();
fileMetaData.Name = Path.GetFileName(pFilePath);
fileMetaData.MimeType = "application/vnd.google-apps.file";
fileMetaData.Parents = new List<string> { parentFolderId };
FilesResource.CreateMediaUpload request;
using(var stream = new FileStream(pFilePath, FileMode.Open))
{
request = service.Files.Create(fileMetaData, stream, "application/vnd.google-apps.file");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
return file.Id;
}
Upon reaching request.Upload(), the request doesn't seem to have any issues, but later on after the file declaration, file turns out to be null, so no response body and thus no id either.
Is there something wrong with my request? I tried to see if I could catch an Exception in upload, which the method description claims would be of type IUploadProgress.Exception, but such an interface doesn't actually have an Exception property.
I've already authenticated and I managed to create a folder (which is the ID passed by argument parentFolderId, confirmed to not be null), so I am able to communicate with drive, just that this particular upload isn't working.
This is the code i use How to upload a file to Google Drive with C# .net I use the async method personally
string uploadedFileId;
// Create a new file on Google Drive
await using (var fsSource = new FileStream(UploadFileName, FileMode.Open, FileAccess.Read))
{
// Create a new file, with metadata and stream.
var request = service.Files.Create(fileMetadata, fsSource, "text/plain");
request.Fields = "*";
var results = await request.UploadAsync(CancellationToken.None);
if (results.Status == UploadStatus.Failed)
{
Console.WriteLine($"Error uploading file: {results.Exception.Message}");
}
// the file id of the new file we created
uploadedFileId = request.ResponseBody?.Id;
}
As for your code i think you need execute on the end
request.Upload().Execute;

Google Cloud Platforms Text To Speech API "'Error creating credential from JSON. Unrecognized credential type ."

using (var stream = new FileStream("C:/textToSpeech/client_secret.json", FileMode.Open, FileAccess.Read))
{
var credential = GoogleCredential.FromStream(stream).CreateScoped(LoggingServiceV2Client.DefaultScopes);
var channel = new Grpc.Core.Channel(
LoggingServiceV2Client.DefaultEndpoint.ToString(),
credential.ToChannelCredentials());
var client = await TextToSpeechClient.CreateAsync(channel.ShutdownToken);
//var client = TextToSpeechClient.Create();
var input = new SynthesisInput
{
Text = "This is Demo of the Google Cloud Text-to-Speech API"
};
VoiceSelectionParams voiceSelection = new VoiceSelectionParams
{
LanguageCode = "en-US",
SsmlGender = SsmlVoiceGender.Female,
};
var audioConfig = new AudioConfig
{
AudioEncoding = AudioEncoding.Mp3
};
var response = client.SynthesizeSpeech(input, voiceSelection, audioConfig);
using (var output = File.Create("output.mp3"))
{
response.AudioContent.WriteTo(output);
}
Console.WriteLine("Audio content written to file output.mp3");
}
I want to convert my text to audio text in a form application but I get an error while translating. I signed up for Google Cloud Platform and created my JSON file by doing the necessary actions. I am getting the following error while authorizing the API.You can see the screenshot of the error I got here. I added the necessary things to the environment variables. I tried every solution I found on the internet, but I could not get rid of this error. Error => System.InvalidOperationException: 'Error creating credential from JSON. Unrecognized credential type .'

YouTube API - Video Upload - 401 Unauthorized

This is driving me crazy! I am using the following code below. 90% of the time I get the following error. Every now and then it works with no problem. Please help. I checked the Developer Key, Username and Password.
Error: System.Net.WebException: The remote server returned an error:
(401) Unauthorized. at System.Net.HttpWebRequest.GetResponse()
at
Google.GData.Client.ResumableUpload.ResumableUploader.UploadStreamPart(Int32
partIndex, String httpMethod, Uri sessionUri, Authenticator
authentication, Stream payload, String mediaType, AsyncData data)
at
Google.GData.Client.ResumableUpload.ResumableUploader.UploadStream(String
httpMethod, Uri sessionUri, Authenticator authentication, Stream
payload, String mediaType, AsyncData data) at
Google.GData.Client.ResumableUpload.ResumableUploader.Insert(Authenticator
authentication, AbstractEntry payload, AsyncData data) at
Google.GData.Client.ResumableUpload.ResumableUploader.AsyncInsertWorker(AsyncResumableUploadData
data, AsyncOperation asyncOp, SendOrPostCallback
completionMethodDelegate) Value cannot be null. Parameter name:
inputStream can not be null
**My Code:**
newVideo.Tags.Add(new MediaCategory("Nonprofit", YouTubeNameTable.CategorySchema));
newVideo.Description = DateTime.Now.ToShortDateString();
newVideo.YouTubeEntry.Private = false;
ResumableUploader m_ResumableUploader = null;
Authenticator YouTubeAuthenticator;
m_ResumableUploader = new ResumableUploader(100); //chunksize 1 MB
m_ResumableUploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(m_ResumableUploader_AsyncOperationCompleted);
m_ResumableUploader.AsyncOperationProgress += new AsyncOperationProgressEventHandler(m_ResumableUploader_AsyncOperationProgress);
YouTubeAuthenticator = new ClientLoginAuthenticator(ConfigurationManager.AppSettings["APPLICATION_NAME"].ToString(), ServiceNames.YouTube, ConfigurationManager.AppSettings["LOGIN_USERNAME"].ToString(), ConfigurationManager.AppSettings["LOGIN_PASSWORD"].ToString());
YouTubeAuthenticator.DeveloperKey = ConfigurationManager.AppSettings["DEVELOPER_KEY"].ToString();
string contentType = MediaFileSource.GetContentTypeForFileName(fileName);
newVideo.MediaSource = new MediaFileSource(filePath, contentType);
AtomLink link = new AtomLink("http://uploads.gdata.youtube.com/resumable/feeds/api/users/" + ConfigurationManager.AppSettings["YT_USERNAME"].ToString() + "/uploads");
link.Rel = ResumableUploader.CreateMediaRelation;
newVideo.YouTubeEntry.Links.Add(link);
m_ResumableUploader.InsertAsync(YouTubeAuthenticator, newVideo.YouTubeEntry, new object());
I think I should add.. It breaks on the last line ytr.ParseVideo(e.ResponseStream);
void m_ResumableUploader_AsyncOperationCompleted(object sender, AsyncOperationCompletedEventArgs e)
{
YouTubeRequestSettings ys = new YouTubeRequestSettings(ConfigurationManager.AppSettings["APPLICATION_NAME"].ToString(),
ConfigurationManager.AppSettings["DEVELOPER_KEY"].ToString(), ConfigurationManager.AppSettings["LOGIN_USERNAME"].ToString(),
ConfigurationManager.AppSettings["LOGIN_PASSWORD"].ToString());
YouTubeRequest ytr = new YouTubeRequest(ys);
Video v = ytr.ParseVideo(e.ResponseStream);
}
My guess would be that you're not uploading into the account that corresponds to the stored credentials that you have. In general, you shouldn't do things like ConfigurationManager.AppSettings["YT_USERNAME"].ToString() in your GData API v2 code; instead, you should use the value default as the user portion of a URL, which refers to the currently authenticated user.

How to create google-drive spreadsheet from .csv file?

I`d like to create spreadsheet from .csv file.
Code:
static void Main()
{
String CLIENT_ID = "<MY ID>";
String CLIENT_SECRET = "<MY SECRET>";
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
var service = new DriveService(auth);
File body = new File();
body.Title = "My spread";
body.Description = "A test spread";
body.MimeType = "application/vnd.google-apps.spreadsheet";
byte[] byteArray = System.IO.File.ReadAllBytes("spread.csv");
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
service.Files.Insert(body, stream, "application/vnd.google-apps.spreadsheet").Upload();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
string[] scopes = new string[] { "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/userinfo.profile" };
IAuthorizationState state = new AuthorizationState(scopes);
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
After inserting file and clicking on it on google-drive page(logged as owner) I get message
"We're sorry.
The spreadsheet at this URL could not be found. Make sure that you have the right URL and that the owner of the spreadsheet hasn't deleted it"
When I change MimeType to "text/csv" and insert file, after clicking on it, I get message
"No preview available
This item was created with (MyApp'sName), a Google Drive app.
Download this file or use one of the apps you have installed to open it."
I can also right click on this file(that one created with "text/csv" MimeType) and choose option "Export to Google Docs" and this gives me result that I'd like to reach - spreadsheet file with my .csv's file content. But such indirect method doesn`t fully satify me. Is there any method to make spreadsheet file on google drive, with content from .csv file direct from my application?
I don't know c#, but on the basis it mirrors Java, within the line
service.Files.Insert(body, stream,
"application/vnd.google-apps.spreadsheet").Upload();
you need to insert the equivalent of
.setConvert(true)
also ...
the mimetype should be "text/csv"
I've found the answer :)
How to programmatically convert a file into an appropriate Google Documents format:
var service = new DriveService(new BaseClientService.Initializer
{
...
});
...
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, _mimeType);
request.Convert = true;
request.Upload();

Passing parameters to Facebook Open Graph API

I'm trying to upload a video to the Facebook open graph using the C# SDK. The video seems to upload fine and I get an Id for the activity, but only the sample metadata appears.
After a little digging, I found this:
Before being able to publish an Open Graph action for a user and having define its corresponding connected object type in Step 3, you will now need to create a publicly accessible web page that represents this object using Open Graph metatags. Once this object page is created, you can use the Graph API to publish an action.
Since this is a client-side app, I don't have a web page that I can refer Facebook to. So how do I pass in the right parameters?
Here's my code:
var parameters = new Dictionary<string, object>();
parameters["source"] = new FacebookMediaObject { ContentType = "video/mpeg", FileName = "video.mpeg" }.SetValue(File.ReadAllBytes(#"D:\sample video.MP4"));
parameters["og:title"] = "Sample video";
parameters["title"] = "Sample video";
parameters["og:description"] = "Test description";
parameters["highlight"] = "http://samples.ogp.me/287287444686523"; // If I don't put this, the upload fails
fb.PostAsync("/me/myobjectname:share", parameters);
Thanks!
For version 6, you can do:
var fb = new FacebookClient(accessToken);
string attachementPath = #"C:\image.jpg";
using (var stream = File.OpenRead(attachementPath))
{
dynamic result = fb.Post("me/photos",
new
{
message = "upload using Facebook C# SDK",
file = new FacebookMediaStream
{
ContentType = "image/jpg",
FileName = Path.GetFileName(attachementPath)
}.SetValue(stream)
});
}
More details here.

Categories