public void Publish_Photo_To_Existing_Album() { #if DEBUG string photoPath = @"..\..\..\Facebook.Tests\bin\Debug\monkey.jpg"; #else string photoPath = @"..\..\..\Facebook.Tests\bin\Release\monkey.jpg"; #endif string albumId = ConfigurationManager.AppSettings["AlbumId"]; byte[] photo = File.ReadAllBytes(photoPath); FacebookClient app = new FacebookClient(); dynamic parameters = new ExpandoObject(); parameters.access_token = ConfigurationManager.AppSettings["AccessToken"]; parameters.message = "This is a test photo of a monkey that has been uploaded " + "by the Facebook C# SDK (http://facebooksdk.codeplex.com)" + "using the Graph API"; var mediaObject = new FacebookMediaObject { FileName = "monkey.jpg", ContentType = "image/jpeg", }; mediaObject.SetValue(photo); parameters.source = mediaObject; dynamic result = app.Post(String.Format("/{0}/photos", albumId), parameters); Assert.NotNull(result); Assert.NotEqual(null, result.id); }
public ActionResult PublicarFoto() { if (Session["FbuserToken"] != null) { var _fb = new FacebookClient(Session["FbuserToken"].ToString()); //upload de imagem FacebookMediaObject media = new FacebookMediaObject { FileName = "Nome da foto", ContentType = "image/jpeg" }; byte[] img = System.IO.File.ReadAllBytes(Server.MapPath("~/Content/rodolfo.jpg")); media.SetValue(img); dynamic parameters = new ExpandoObject(); parameters.source = media; parameters.message = "Descricao"; try { dynamic result = _fb.Post("/me/photos", parameters); } catch (Exception ex) { } } return(RedirectToAction("Index")); }
/// <summary> /// Transfer the chunk of data /// </summary> /// <param name="upload_session_id"></param> /// <param name="start_offset"></param> /// <param name="index"></param> /// <returns></returns> async public Task <int[]> TransferInChunk(string upload_session_id, int start_offset, int index, byte[] bytes) { try { int[] output = new int[2]; var mediaObject = new FacebookMediaObject { FileName = "@chunk" + index + ".mp4", ContentType = "video/mp4" }; mediaObject.SetValue(bytes); Dictionary <string, object> parameter = new Dictionary <string, object> { { "upload_phase", "transfer" }, { "upload_session_id", upload_session_id }, { "start_offset", start_offset }, { "video_file_chunk", mediaObject } }; dynamic result = await fb.PostTaskAsync(base.pageID + "/videos", parameter); output[0] = Convert.ToInt32(result.start_offset); output[1] = Convert.ToInt32(result.end_offset); return(output); } catch (Exception ex) { throw ex; } }
private void btnUpload_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(_filename)) { MessageBox.Show("Please select the image file first."); return; } var mediaObject = new FacebookMediaObject { ContentType = "image/jpeg", FileName = Path.GetFileName(_filename) } .SetValue(File.ReadAllBytes(_filename)); progressBar1.Value = 0; var fb = new FacebookClient(_accessToken); fb.UploadProgressChanged += fb_UploadProgressChanged; fb.PostCompleted += fb_PostCompleted; // for cancellation _fb = fb; fb.PostAsync("/me/photos", new Dictionary <string, object> { { "source", mediaObject } }); }
public void Publish_Video_To_Wall() { var videoPath = TestHelpers.GetPathRelativeToExecutable("do-beer-not-drugs.3gp"); byte[] video = File.ReadAllBytes(videoPath); var mediaObject = new FacebookMediaObject { FileName = "do-beer-not-drugs.3gp", ContentType = "video/3gpp" }; mediaObject.SetValue(video); dynamic parameters = new ExpandoObject(); parameters.source = mediaObject; parameters.method = "video.upload"; parameters.access_token = ConfigurationManager.AppSettings["AccessToken"]; var fb = new FacebookClient(); dynamic result = fb.Post(parameters); Assert.NotNull(result); Assert.NotEqual(null, result.vid); }
// [TestCategory("RequiresOAuth")] public void Publish_Photo_To_Existing_Album() { #if DEBUG string photoPath = @"..\..\..\Facebook.Tests\bin\Debug\monkey.jpg"; #else string photoPath = @"..\..\..\Facebook.Tests\bin\Release\monkey.jpg"; #endif string albumId = ConfigurationManager.AppSettings["AlbumId"]; byte[] photo = File.ReadAllBytes(photoPath); FacebookClient app = new FacebookClient(); dynamic parameters = new ExpandoObject(); parameters.access_token = ConfigurationManager.AppSettings["AccessToken"]; parameters.message = "This is a test photo of a monkey that has been uploaded " + "by the Facebook C# SDK (http://facebooksdk.codeplex.com)" + "using the Graph API"; var mediaObject = new FacebookMediaObject { FileName = "monkey.jpg", ContentType = "image/jpeg", }; mediaObject.SetValue(photo); parameters.source = mediaObject; dynamic result = app.Post(String.Format("/{0}/photos", albumId), parameters); Assert.NotNull(result); Assert.NotEqual(null, result.id); }
private void UploadPhoto() { if (!File.Exists(_filename)) { lblStatus.Text = GlobalSetting.LangPack.Items["frmFacebook._StatusInvalid"]; return; } var mediaObject = new FacebookMediaObject { ContentType = "image/jpeg", FileName = Path.GetFileName(_filename) }.SetValue(File.ReadAllBytes(_filename)); lblPercent.Text = "0 %"; picStatus.Visible = true; lblStatus.Text = GlobalSetting.LangPack.Items["frmFacebook._StatusUploading"]; var fb = new FacebookClient(GlobalSetting.FacebookAccessToken); fb.UploadProgressChanged += fb_UploadProgressChanged; fb.PostCompleted += fb_PostCompleted; // for cancellation _fb = fb; fb.PostAsync("/me/photos", new Dictionary <string, object> { { "source", mediaObject }, { "message", txtMessage.Text.Trim() } }); }
private void PostToWall() { IsCalculating = true; var parameters = new Dictionary <string, object> { { "message", Message } }; using (var memoryStream = new MemoryStream()) { Image.SaveJpeg(memoryStream, Image.PixelWidth, Image.PixelHeight, 0, 100); memoryStream.Seek(0, 0); var data = new byte[memoryStream.Length]; memoryStream.Read(data, 0, data.Length); memoryStream.Close(); var fbUpl = new FacebookMediaObject { ContentType = "image/jpeg", FileName = "image.jpeg", }; fbUpl.SetValue(data); parameters.Add("file", fbUpl); } client.PostAsync("me/photos", parameters); }
// [TestCategory("RequiresOAuth")] public void publish_photo_to_application_album() { #if DEBUG string photoPath = @"..\..\..\Facebook.Tests\bin\Debug\monkey.jpg"; #else string photoPath = @"..\..\..\Facebook.Tests\bin\Release\monkey.jpg"; #endif byte[] photo = File.ReadAllBytes(photoPath); FacebookClient app = new FacebookClient(); dynamic parameters = new ExpandoObject(); parameters.access_token = ConfigurationManager.AppSettings["AccessToken"]; parameters.caption = "This is a test photo of a monkey that has been uploaded " + "by the Facebook C# SDK (http://facebooksdk.codeplex.com)" + "using the REST API"; parameters.method = "facebook.photos.upload"; parameters.uid = ConfigurationManager.AppSettings["UserId"]; var mediaObject = new FacebookMediaObject { FileName = "monkey.jpg", ContentType = "image/jpeg", }; mediaObject.SetValue(photo); parameters.source = mediaObject; dynamic result = app.Post(parameters); Assert.NotNull(result); Assert.NotEqual(result.aid, null); }
public long PostPhoto(string pageId, FacebookPostViewModel model) { dynamic parameters = new ExpandoObject(); parameters.link = model.Link ?? string.Empty; parameters.place = model.LocationId ?? string.Empty; parameters.caption = model.Content; try { foreach (var item in model.Picture.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList()) { byte[] photo = File.ReadAllBytes(item); var mediaObject = new FacebookMediaObject { FileName = Path.GetFileNameWithoutExtension(item), ContentType = "image/jpeg" }; mediaObject.SetValue(photo); parameters.source = mediaObject; } InitializeFacebookClient(model.AccessToken); var result = _fbClient.Post(String.Format("/{0}/photos", pageId), parameters); var jsonResult = (JObject)JsonConvert.DeserializeObject(result.ToString()); return(Convert.ToInt64(jsonResult.First.First.ToString())); } catch (FacebookOAuthException) { } catch (Exception) { } return(0); }
// [TestCategory("RequiresOAuth")] public void publish_photo_to_application_album() { #if DEBUG string photoPath = @"..\..\..\Facebook.Tests\bin\Debug\monkey.jpg"; #else string photoPath = @"..\..\..\Facebook.Tests\bin\Release\monkey.jpg"; #endif byte[] photo = File.ReadAllBytes(photoPath); FacebookClient app = new FacebookClient(); dynamic parameters = new ExpandoObject(); parameters.access_token = ConfigurationManager.AppSettings["AccessToken"]; parameters.caption = "This is a test photo of a monkey that has been uploaded " + "by the Facebook C# SDK (http://facebooksdk.codeplex.com)" + "using the REST API"; parameters.method = "facebook.photos.upload"; parameters.uid = ConfigurationManager.AppSettings["UserId"]; var mediaObject = new FacebookMediaObject { FileName = "monkey.jpg", ContentType = "image/jpeg", }; mediaObject.SetValue(photo); parameters.source = mediaObject; dynamic result = app.Post(parameters); Assert.NotNull(result); Assert.NotEqual(result.aid, null); }
public static string ComposeMessage(Domain.Socioboard.Enum.FbProfileType profiletype, string accessToken, string fbUserId, string message, string profileId, long userId, string imagePath, string link, Domain.Socioboard.Models.ScheduledMessage schmessage) { string ret = ""; DatabaseRepository dbr = new DatabaseRepository(); FacebookClient fb = new FacebookClient(); fb.AccessToken = accessToken; System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls; var args = new Dictionary <string, object>(); if (!string.IsNullOrEmpty(message)) { args["message"] = message; } if (profiletype == Domain.Socioboard.Enum.FbProfileType.FacebookProfile) { args["privacy"] = FbUser.SetPrivacy("Public", fb, profileId); } try { if (!string.IsNullOrEmpty(imagePath)) { Uri u = new Uri(imagePath); string filename = string.Empty; string extension = string.Empty; extension = System.IO.Path.GetExtension(u.AbsolutePath).Replace(".", ""); var media = new FacebookMediaObject { FileName = "filename", ContentType = "image/" + extension }; var webClient = new WebClient(); byte[] img = webClient.DownloadData(imagePath); media.SetValue(img); args["source"] = media; ret = fb.Post("v2.1/" + fbUserId + "/photos", args).ToString(); } else { if (!string.IsNullOrEmpty(link)) { args["link"] = link; } ret = fb.Post("v2.1/" + fbUserId + "/feed", args).ToString(); } schmessage.status = Domain.Socioboard.Enum.ScheduleStatus.Compleated; schmessage.url = ret; dbr.Update <ScheduledMessage>(schmessage); } catch (Exception ex) { apiHitsCount = MaxapiHitsCount; } return(ret); }
/// <summary> /// This is to post local image on wall /// </summary> /// <param name="m_StorageFile"></param> /// <param name="strMessage"></param> /// <param name="strPrivacy"></param> /// <returns></returns> public async Task <string> PostLocalImageOnWall(StorageFile m_StorageFile, string strMessage, string strPrivacy) { string strResponse = string.Empty; await Task.Run(async() => { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { try { byte[] imageByte = new byte[0]; if (m_StorageFile != null) { var stream = await m_StorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); var reader = new DataReader(stream.GetInputStreamAt(0)); imageByte = new byte[stream.Size]; await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(imageByte); } var mediaObject = new FacebookMediaObject(); await Task.Run(() => { var source = File.OpenRead(m_StorageFile.Path); mediaObject = new FacebookMediaObject { ContentType = m_StorageFile.ContentType.ToString(), FileName = Path.GetFileName(m_StorageFile.Path) }; mediaObject.SetValue(imageByte); }); var parameters = new Dictionary <string, object> { { "message", strMessage }, { "source", mediaObject }, { "privacy", new Dictionary <string, object> { { "value", strPrivacy } } } }; dynamic fbPostTaskResult = await GlobalVariable.fbclient.PostTaskAsync("/me/photos", parameters); var responseresult = (IDictionary <string, object>)fbPostTaskResult; strResponse = "Image posted sucessfully on facebook wall"; } catch (Exception ex) { //MessageDialog ErrMsg = new MessageDialog("Error Ocuured!"); System.Diagnostics.Debug.WriteLine("Exception Occur BtnFaceBookPost_Click : " + ex.ToString()); strResponse = ex.Message; } }); }); return(strResponse); }
// could store it here but not sure we really need to, as can be re-requested via JS methods easily, and search page doesn't reload anyway so shouldn't lose it..? /*public ActionResult fbLoginAjax(string access_token) * { * Session["fbAccessToken"] = access_token; * return Json(access_token, JsonRequestBehavior.AllowGet); * }*/ public ActionResult fbUploadPhotoAjax(string id_str, string access_token) { string r = "?"; var results = getItemsFromIDStringList(id_str, false); if (results.Count == 1) { var result = results[0]; var client = new FacebookClient(access_token); //Create a new dictionary of objects, with string keys Dictionary <string, object> parameters = new Dictionary <string, object>(); var ImageName = String.Format("{0}.jpg", result.Title); var ImagePath = String.Format(@"F:\Shared Documents\Test Images\{0}", ImageName); string strDescription = result.Title; //Add elements to the dictionary if (string.IsNullOrEmpty(ImagePath) == false) { //There is an Image to add to the parameters var media = new FacebookMediaObject { FileName = ImageName, ContentType = "image/jpeg" }; var img_src = _IJP2Helper.GetImageUri(result.ImageMetadata, MediaDirectoryFullUri, _IJP2Helper.ResolverUri, ExportImageWidth, ExportImageHeight); media.SetValue(ImageHelper.GetImageBytes(img_src, ImageNotFound)); parameters.Add("source", media); parameters.Add("message", strDescription); try { //client.PostCompleted += fbPostCompleted; //dynamic result = client.PostTaskAsync("/me/photos", parameters); dynamic post_result = client.Post("/me/photos", parameters); r = "ok"; Helper.LogHelper.StatsLog(null, "fbUploadPhotoAjax() [async] ", r, null, null); } catch (Exception ex) { r = ex.Message; } } } else { r = "Error finding item"; } return(Json(r, JsonRequestBehavior.AllowGet)); }
public ActionResult PublicarFotos() { if (Session["FbuserToken"] != null) { var path = PhotoPath; var files_text = Directory.GetFiles(path); var files = files_text.Select(e => new filesOrdered { file = e, id = int.Parse(Path.GetFileNameWithoutExtension(e)) }).OrderBy(e => e.id).ToArray(); foreach (var item in files) { var _fb = new FacebookClient(Session["FbuserToken"].ToString()); //upload de imagem FacebookMediaObject media = new FacebookMediaObject { FileName = "Nome da foto", ContentType = "image/jpeg" }; byte[] img = System.IO.File.ReadAllBytes(item.file); media.SetValue(img); dynamic parameters = new ExpandoObject(); var xx = Path.GetFileNameWithoutExtension(item.file); parameters.source = media; parameters.message = Path.GetFileName(item.file); parameters.name = xx; parameters.caption = xx; parameters.description = xx; parameters.privacy = new Dictionary <string, string> { ["value"] = "EVERYONE" }; try { dynamic result = _fb.Post(AlbumId + "/photos", parameters); System.IO.File.Delete(item.file); } catch (Exception ex) { throw ex; } } } return(RedirectToAction("Index")); }
private void PostData(string sFile) { var fb = new FacebookClient("AAAEZA95pDXoABACHuViSkXFRUw72lZCy7F0ePDW6UWtjqODm76FoWZAxCH8GkBcTUsJ7eK0ZBu5z9ejDqnXyOu4BbMj7ku9nMqL5HXaiq4dIBpGJG6gl"); var parameters = new Dictionary <string, object>(); parameters["message"] = "MVT: Send from auto post..."; parameters["source"] = new FacebookMediaObject { ContentType = "image/jpeg", FileName = Path.GetFileName(sFile) }.SetValue(File.ReadAllBytes(sFile)); fb.PostAsync("me/photos", parameters); }
protected void TagShare_Click(object sender, EventArgs e) { List <ListItem> checkedItems = new List <ListItem>(); foreach (ListItem item in FriendList.Items) { if (item.Selected) { checkedItems.Add(item); } } var fb = new FacebookClient(Session["AccessToken"].ToString()); int x = 10, y = 10; UserTags[] tags = new UserTags[checkedItems.Count]; for (int i = 0; i < checkedItems.Count; i++) { ListItem item = checkedItems[i]; UserTags tag = new UserTags(); tag.tag_uid = long.Parse(item.Value); tag.x = x; tag.y = y; tags[i] = tag; x += 10; y += 10; } string sportsperson = ViewState["SportsPerson"].ToString(); var parameters = new Dictionary <string, object>(); parameters["name"] = "If " + ViewState["FBName"] + " was a sports person, he would have been " + sportsperson; parameters["tags"] = tags; parameters["TestPic"] = new FacebookMediaObject { ContentType = "image/jpeg", FileName = sportsperson + ".jpg" }.SetValue(File.ReadAllBytes(Server.MapPath("~\\Images\\" + sportsperson + ".jpg"))); dynamic res = fb.Post("me/Photos", parameters); Status.Text = "Photo Uploaded. Photo ID: " + res.id; }
public static void Publish(string text, MediaFile.MediaFile mediaFile) { if (Accessik != null) { facebookClient = new FacebookClient(Accessik); if (text != null && mediaFile == null) { facebookClient.Post("/me/feed", new { message = text }); MessageBox.Show("Opublikowano status!"); } else { if (text != null && mediaFile._openFileDialog.FilterIndex == 5) { FacebookMediaObject facebookMediaObject = new FacebookMediaObject { FileName = mediaFile._openFileDialog.FileName, ContentType = "video/mp4" }; facebookMediaObject.SetValue(mediaFile._fileBytes); var postInfo = new Dictionary <string, object>(); postInfo.Add("message", text); postInfo.Add("image", facebookMediaObject); facebookClient.Post("/" + "117306115306848" + "/videos", postInfo); MessageBox.Show("Opublikowano status z plikiem video"); } else if (text != null) { FacebookMediaObject facebookMediaObject = new FacebookMediaObject { FileName = mediaFile._openFileDialog.FileName, ContentType = "image/jpg" }; facebookMediaObject.SetValue(mediaFile._fileBytes); var postInfo = new Dictionary <string, object>(); postInfo.Add("message", text); postInfo.Add("image", facebookMediaObject); facebookClient.Post("/" + "117306115306848" + "/photos", postInfo); MessageBox.Show("Opublikowano status z obrazkiem"); } } } else { MessageBox.Show("Zaloguj się"); } }
public dynamic GraphVideoUploadTests(string accessToken, byte[] data, string contentType, string fileName) { return(Test("graph video upload tests", () => { var fb = new FacebookClient(accessToken); var parameters = new Dictionary <string, object>(); parameters["source"] = new FacebookMediaObject { ContentType = contentType, FileName = fileName }.SetValue(data); parameters["message"] = "graph video upload test"; return fb.Post("/me/videos", parameters); })); }
public bool PublishToFacebook(string post, byte[] imageBytes) { var accessToken = Properties.Settings.Default.FBAccessToken; var AppId = Properties.Settings.Default.FBAppId; FacebookClient fbClient = new FacebookClient(accessToken); var args = new Dictionary <string, object>(); try { if (imageBytes != null && imageBytes.Length > 0) { Image postImage = Image.FromStream(new MemoryStream(imageBytes)); string fileName = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + @"\" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".jpg"; postImage.Save(fileName); args["caption"] = post; args["source"] = new FacebookMediaObject { ContentType = "image/gif", FileName = Path.GetFileName(fileName) }.SetValue(File.ReadAllBytes(fileName)); var result = fbClient.Post("/" + AppId + "/photos", args); } else { args["message"] = post; var result = fbClient.Post("/" + AppId + "/feed", args); } return(true); } catch (FacebookOAuthException ex) { throw ex; return(false); } catch (FacebookApiException ex) { throw ex; return(false); } }
public void PostToFacebook(string pageAccessToken, string pageId, MessageOptions messageOptions) { var fbClient = new FacebookClient(pageAccessToken); var webClient = new WebClient(); var image = webClient.DownloadData(messageOptions.ImageUrl); var facebookUploader = new FacebookMediaObject { FileName = Path.GetFileName(messageOptions.ImageUrl), ContentType = "image/png,image/jpg" }; facebookUploader.SetValue(image); var fbParams = new Dictionary <string, object> { ["description"] = messageOptions.Description, ["picture"] = facebookUploader, ["caption"] = messageOptions.Title, ["link"] = messageOptions.Link, ["no_story"] = true }; try { var result = fbClient.Post($"/{pageId}/photos", fbParams); var response = (IDictionary <string, object>)result; if (response == null) { throw new ArgumentNullException(nameof(response)); } var fbPostParams = new Dictionary <string, object>() { ["object_attachment"] = response["id"], ["message"] = messageOptions.Message, }; fbClient.Post($"/{pageId}/feed", fbPostParams); } catch (FacebookOAuthException e) { Console.WriteLine(e); throw; } }
private JsonObject UploadPhoto(FacebookClient fbApp, byte[] bytes, string pageAccessToken) { FacebookMediaObject media = new FacebookMediaObject(); media.ContentType = "image/png"; media.FileName = "test.png"; media.SetValue(bytes); Dictionary <string, object> upload = new Dictionary <string, object>(); upload.Add("name", "照片名稱"); upload.Add("message", "照片描述"); upload.Add("no_story", "1"); // 是否要發佈訊息 upload.Add("access_token", pageAccessToken); upload.Add("@file.png", media); return(fbApp.Post(_pageID + "/photos", upload) as JsonObject); }
private async void PostToWall(string status) { try { facebookClient = new Facebook.FacebookClient(App.fbaccesstokenkey); var parameters = new Dictionary <string, object>(); //var parameters1 = new Dictionary<string, object>(); parameters["message"] = status; parameters["caption"] = string.Empty; parameters["description"] = string.Empty; parameters["req_perms"] = "publish_stream"; parameters["scope"] = "publish_stream"; parameters["type"] = "normal"; dynamic fbPostTaskResult = null; if (imageStatus) { var mediaObject = new FacebookMediaObject { ContentType = "image/jpeg", FileName = "pokemon.jpg" }.SetValue(byteImage); parameters["source"] = mediaObject; fbPostTaskResult = await facebookClient.PostTaskAsync("/me/photos", parameters); } else { fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", parameters); } var result = (IDictionary <string, object>)fbPostTaskResult; Dispatcher.BeginInvoke(() => { MessageBox.Show("Posted Open Graph Action, id: " + (string)result["id"], "Result", MessageBoxButton.OK); }); } catch (Exception ex) { Dispatcher.BeginInvoke(() => { MessageBox.Show("Exception during post: " + ex.ToString(), "Error", MessageBoxButton.OK); }); } }
protected void SharePhoto_Click(object sender, EventArgs e) { var fb = new FacebookClient(Session["AccessToken"].ToString()); string sportsperson = ViewState["SportsPerson"].ToString(); var parameters = new Dictionary <string, object>(); parameters["name"] = "If " + ViewState["FBName"] + " was a sports person, he would have been " + sportsperson; parameters["TestPic"] = new FacebookMediaObject { ContentType = "image/jpeg", FileName = sportsperson + ".jpg" }.SetValue(File.ReadAllBytes(Server.MapPath("~\\Images\\" + sportsperson + ".jpg"))); dynamic res = fb.Post("me/Photos", parameters); Status.Text = "Photo Uploaded. Photo ID: " + res.id; }
/// <summary> /// Post to facebook /// </summary> /// <param name="uid"></param> /// <param name="message"></param> /// <param name="image"></param> public void PostToFacebook(int uid, string message, string image) { var user = userRepository.FindBy(uid); var accessToken = user.FacebookAccessToken; var clientId = user.Account.FacebookAPPID; var clientSecret = user.Account.FacebookAPPSecret; if (string.IsNullOrEmpty(accessToken)) { throw new Exception("Access token is empty for user " + uid); } accessToken = GetExtendedFacebookAccessToken(accessToken, clientId, clientSecret); userRepository.UpdateFacebookAccessToken(uid, accessToken); var fb = new FacebookClient(accessToken); fb.AppId = clientId; fb.AppSecret = clientSecret; var fbValues = (IDictionary <string, object>)fb.Get("me"); var parameters = new Dictionary <string, object>(); if (!string.IsNullOrEmpty(image)) { byte[] byteArray = null; using (var webClient = new WebClient()) { byteArray = webClient.DownloadData(image); } parameters["picture"] = new FacebookMediaObject { ContentType = "image/jpeg", FileName = Path.GetFileName(image) }.SetValue(byteArray); parameters["caption"] = message; fb.Post(fbValues["id"].ToString() + "/photos", parameters); } else { parameters["message"] = message; fb.Post(fbValues["id"].ToString() + "/feed", parameters); } }
public void LegacyRestApiVideoUploadTests(string accessToken, byte[] data, string contentType, string fileName) { Test("legacy rest api video upload tests", () => { var fb = new FacebookClient(accessToken); var mediaObject = new FacebookMediaObject { ContentType = contentType, FileName = fileName }.SetValue(data); var parameters = new Dictionary <string, object>(); parameters["source"] = mediaObject; parameters["caption"] = "video upload using fb c# sdk"; parameters["method"] = "video.upload"; return(fb.Post(parameters)); }); }
protected void Page_Load(object sender, EventArgs e) { //if (Request.Params.AllKeys.Contains("photo")) byte[] imageBytes = Request.BinaryRead(Request.TotalBytes); { string _pageID = "837621709595360"; string accessToken = "CAAKagaljuDIBAOyEnKelOTgJFIDFT3U6Eg9aa8Q7uhlRHh0MQg0Hz3ZANSBB7T1q4ZAucq0apDUNXewIP91kk546UYYmr2Iz49ZCjko1r6e9o9H2dVbmWvaDQxCvt5rWpOooRc8dTrbeMroFCJUu6hGUmwtqqqaEzo8YAGQLvS6guzGk25MRIU3F0tBxB8ZD"; FacebookClient fb = new FacebookClient(accessToken); // 上傳照片 //string imageUrl = Request["photo"].ToString(); //imageBytes = Convert.FromBase64String(imageUrl.Substring("data:image/jpeg;base64,".Length)); //imageBytes = Convert.FromBase64String(imageUrl.Substring("data:image/png;base64,".Length)); FacebookMediaObject media = new FacebookMediaObject(); media.ContentType = "image/jpeg"; media.FileName = "image.jpg"; media.SetValue(imageBytes); Dictionary <string, object> upload = new Dictionary <string, object>(); upload.Add("name", "今天我來到六堆客家文化園區,參觀了新茶特展,還體驗了品茶的奇幻之地!你趕快也ㄧ起來看看吧! https://www.facebook.com/liuduihakkatea"); upload.Add("message", ""); upload.Add("access_token", accessToken); upload.Add("@file.jpg", media); try { fb.Post(_pageID + "/photos", upload); } catch (Exception ex) { Response.Write("false, exception: " + ex.Message); } } Response.Write("true"); }
protected void Page_Load(object sender, EventArgs e) { //if (Request.Params.AllKeys.Contains("photo")) byte[] imageBytes = Request.BinaryRead(Request.TotalBytes); { string _pageID = "1474519026152103"; string accessToken = "CAAJ1UqBRmVEBAIsYnYEOIof9KMLJtZAnkEYsEZARYs4kgoTKhz0H8eIxgD7st0Da4B1sUgjjjaWJsKxxHBu5MCu7j5ez29nPTvRRFIskpJrbZARLKX4ZA89muEgZAA67wA9n2ZCx3lc4rGZCG0rk4YZCOwLrcKLSVXxDRZC9Vo2GJqB6XXGcGrlyJ43OacWYsDwuaarwxQ9tZB2cKvyPX5UQRA"; FacebookClient fb = new FacebookClient(accessToken); // 上傳照片 //string imageUrl = Request["photo"].ToString(); //imageBytes = Convert.FromBase64String(imageUrl.Substring("data:image/jpeg;base64,".Length)); //imageBytes = Convert.FromBase64String(imageUrl.Substring("data:image/png;base64,".Length)); FacebookMediaObject media = new FacebookMediaObject(); media.ContentType = "image/jpeg"; media.FileName = "image.jpg"; media.SetValue(imageBytes); Dictionary <string, object> upload = new Dictionary <string, object>(); upload.Add("name", "(測試)今天我來到六堆客家文化園區,參觀了新茶特展,還體驗了品茶的奇幻之地!你趕快也ㄧ起來看看吧! https://www.facebook.com/liuduihakkatea"); upload.Add("message", ""); upload.Add("access_token", accessToken); upload.Add("@file.jpg", media); try { fb.Post(_pageID + "/photos", upload); } catch (Exception ex) { Response.Write("false, exception: " + ex.Message); } } Response.Write("true"); }
protected void btnSubmit_Click(object sender, EventArgs e) { if (fileUpload.HasFile) { FacebookClient facebookClient = new FacebookClient(access_token); FacebookMediaObject mediaObject = new FacebookMediaObject { FileName = "file.jpg", ContentType = "image/jpeg" }; mediaObject.SetValue(fileUpload.FileBytes); IDictionary <string, object> upload = new Dictionary <string, object>(); upload.Add("name", caption.Text); upload.Add("@file.jpg", mediaObject); dynamic res = facebookClient.Post("/me/photos", upload) as JsonObject; form1.Visible = false; msg.Text = "<p>Photo uploaded successfully. " + "<a href=\"https://www.facebook.com/photo.php?fbid=" + res.id + "\">View on facebook</a><p>" + "<p><a href=\"upload.aspx\">Back</a>"; } }
private async void btnUpload_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(_filename)) { MessageBox.Show("Please select the image file first."); return; } _cts = new CancellationTokenSource(); var mediaObject = new FacebookMediaObject { ContentType = "image/jpeg", FileName = Path.GetFileName(_filename) }.SetValue(File.ReadAllBytes(_filename)); var uploadProgress = new Progress <FacebookUploadProgressChangedEventArgs>(); uploadProgress.ProgressChanged += (o, args) => progressBar1.Value = args.ProgressPercentage; try { await _fb.PostTaskAsync("me/photos", new Dictionary <string, object> { { "source", mediaObject } }, null, _cts.Token, uploadProgress); } catch (OperationCanceledException ex) { MessageBox.Show("Upload Cancelled"); } catch (FacebookApiException ex) { MessageBox.Show(ex.Message); } finally { progressBar1.Value = 0; } }
/// <summary> /// Must login to facebook first! /// Will not error if you have not done this /// /// creates a narrative based on your news articles /// posts image stored in vars.filepath from the image maker /// </summary> public static async Task PostToFacebookAsync() { //heres an error handler hippie if (Vars.AccessToken == "") { return; } using (var fStream = File.OpenRead(Vars.FilePath)) { _client.AccessToken = Vars.AccessToken; FacebookMediaObject mediaObject = new FacebookMediaObject { FileName = "michaelmoore.jpg", ContentType = "image/jpeg" }; var bytes = ReadFully(fStream); mediaObject.SetValue(bytes); IDictionary <string, object> upload = new Dictionary <string, object> { { "name", $"{Vars.Activity} with my buddies" }, { "@file.jpg", mediaObject } }; dynamic res = _client.Post("me/photos", upload) as JsonObject; dynamic parameters = new ExpandoObject(); parameters.message = await Vars.GetMessageAsync(); parameters.object_attachment = res.id; _client.Post("me/feed", parameters); Vars.StatusMessage.Text = "Successfully posted to facebook\n" + Vars.StatusMessage.Text; } }
public static string UploadVideo(string accessToken, string filePath) { // sample usage: UploadVideo(accessToken, @"C:\video.3gp"); var mediaObject = new FacebookMediaObject { FileName = System.IO.Path.GetFileName(filePath), ContentType = "video/3gpp" }; mediaObject.SetValue(System.IO.File.ReadAllBytes(filePath)); try { var fb = new FacebookClient(accessToken); var parameters = new Dictionary <string, object>(); parameters["method"] = "video.upload"; parameters["caption"] = "video upload using rest api"; parameters["source"] = mediaObject; var result = (IDictionary <string, object>)fb.Post(parameters); var videoId = (string)result["vid"]; Console.WriteLine("Video Id: {0}", videoId); // Note: This json result is not the orginal json string as returned by Facebook. Console.WriteLine("Json: {0}", result.ToString()); return(videoId); } catch (FacebookApiException ex) { // Note: make sure to handle this exception. throw; } }
public void Publish_Video_To_Wall() { var videoPath = TestHelpers.GetPathRelativeToExecutable("do-beer-not-drugs.3gp"); byte[] video = File.ReadAllBytes(videoPath); var mediaObject = new FacebookMediaObject { FileName = "do-beer-not-drugs.3gp", ContentType = "video/3gpp" }; mediaObject.SetValue(video); dynamic parameters = new ExpandoObject(); parameters.source = mediaObject; parameters.method = "video.upload"; parameters.access_token = ConfigurationManager.AppSettings["AccessToken"]; var fb = new FacebookClient(); dynamic result = fb.Post(parameters); Assert.NotNull(result); Assert.NotEqual(null, result.vid); }
public GivenMoreThanOneMediaObjectsOnlyThen() { _parameters = new Dictionary<string, object>(); _parameters["file1"] = new FacebookMediaObject(); _parameters["file2"] = new FacebookMediaObject(); }
public GivenOneMediaObjectThen() { _parameters = new Dictionary<string, object>(); _parameters["source"] = new FacebookMediaObject(); _parameters["message"] = "hello world"; }
private void btnPostPicture_Click(object sender, EventArgs e) { var ofd = new OpenFileDialog { Filter = "JPEG Files|*.jpg", Title = "Select picture to upload" }; if (ofd.ShowDialog() == DialogResult.OK) { var picture = File.ReadAllBytes(ofd.FileName); var fb = new FacebookClient(_accessToken); fb.PostCompleted += (o, args) => { if (args.Error == null) { MessageBox.Show("Picture posted to wall successfully."); } else { MessageBox.Show(args.Error.Message); } }; dynamic parameters = new ExpandoObject(); parameters.caption = txtMessage.Text; parameters.method = "facebook.photos.upload"; var mediaObject = new FacebookMediaObject { FileName = Path.GetFileName(ofd.FileName), ContentType = "image/jpeg" }; mediaObject.SetValue(picture); parameters.source = mediaObject; fb.PostAsync(parameters); } }
public void LegacyRestApiVideoUploadTests(string accessToken, byte[] data, string contentType, string fileName) { Test("legacy rest api video upload tests", () => { var fb = new FacebookClient(accessToken); var mediaObject = new FacebookMediaObject { ContentType = contentType, FileName = fileName }.SetValue(data); var parameters = new Dictionary<string, object>(); parameters["source"] = mediaObject; parameters["caption"] = "video upload using fb c# sdk"; parameters["method"] = "video.upload"; return fb.Post(parameters); }); }
public dynamic GraphVideoUploadTests(string accessToken, byte[] data, string contentType, string fileName) { return Test("graph video upload tests", () => { var fb = new FacebookClient(accessToken); var parameters = new Dictionary<string, object>(); parameters["source"] = new FacebookMediaObject { ContentType = contentType, FileName = fileName }.SetValue(data); parameters["message"] = "graph video upload test"; return fb.Post("/me/videos", parameters); }); }