Represents a media object such as a photo or video.
        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 } });
        }
コード例 #2
0
        /// <summary>
        /// Builds the request post data if the request contains a media object
        /// such as an image or video to upload.
        /// </summary>
        /// <param name="parameters">
        /// The request parameters.
        /// </param>
        /// <param name="boundary">
        /// The multipart form request boundary.
        /// </param>
        /// <returns>
        /// The request post data.
        /// </returns>
        internal static byte[] BuildMediaObjectPostData(IDictionary <string, object> parameters, string boundary)
        {
            FacebookMediaObject mediaObject = null;

            // Build up the post message header
            var sb = new StringBuilder();

            foreach (var kvp in parameters)
            {
                if (kvp.Value is FacebookMediaObject)
                {
                    // Check to make sure the file upload hasn't already been set.
                    if (mediaObject != null)
                    {
//                        throw new InvalidOperationException(Facebook.Properties.Resources.MultipleMediaObjectsError);
                    }

                    mediaObject = kvp.Value as FacebookMediaObject;
                }
                else
                {
                    sb.Append(FacebookUtils.MultiPartFormPrefix).Append(boundary).Append(FacebookUtils.MultiPartNewLine);
                    sb.Append("Content-Disposition: form-data; name=\"").Append(kvp.Key).Append("\"");
                    sb.Append(FacebookUtils.MultiPartNewLine);
                    sb.Append(FacebookUtils.MultiPartNewLine);
                    sb.Append(kvp.Value);
                    sb.Append(FacebookUtils.MultiPartNewLine);
                }
            }

            Debug.Assert(mediaObject != null, "The mediaObject is null.");

            if (mediaObject.ContentType == null || mediaObject.GetValue() == null || mediaObject.FileName == null)
            {
//                throw new InvalidOperationException(Facebook.Properties.Resources.MediaObjectMustHavePropertiesSetError);
            }

            sb.Append(FacebookUtils.MultiPartFormPrefix).Append(boundary).Append(FacebookUtils.MultiPartNewLine);
            sb.Append("Content-Disposition: form-data; filename=\"").Append(mediaObject.FileName).Append("\"").Append(FacebookUtils.MultiPartNewLine);
            sb.Append("Content-Type: ").Append(mediaObject.ContentType).Append(FacebookUtils.MultiPartNewLine).Append(FacebookUtils.MultiPartNewLine);

            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString());
            byte[] fileData        = mediaObject.GetValue();
            byte[] boundaryBytes   = Encoding.UTF8.GetBytes(String.Concat(FacebookUtils.MultiPartNewLine, FacebookUtils.MultiPartFormPrefix, boundary, FacebookUtils.MultiPartFormPrefix, FacebookUtils.MultiPartNewLine));

            // Combine all bytes to post
            var postData = new byte[postHeaderBytes.Length + fileData.Length + boundaryBytes.Length];

            Buffer.BlockCopy(postHeaderBytes, 0, postData, 0, postHeaderBytes.Length);
            Buffer.BlockCopy(fileData, 0, postData, postHeaderBytes.Length, fileData.Length);
            Buffer.BlockCopy(boundaryBytes, 0, postData, postHeaderBytes.Length + fileData.Length, boundaryBytes.Length);

            return(postData);
        }
コード例 #3
0
ファイル: Facebook.cs プロジェクト: thewindev/CoLiW
 public bool AddPhoto(PhotoDetails photoDetails)
 {
     var mediaObject = new FacebookMediaObject
     {
         FileName = photoDetails.FacebookName,
         ContentType = "image/jpeg"
     };
     byte[] fileBytes = photoDetails.ImageStream;
     mediaObject.SetValue(fileBytes);
     IDictionary<string, object> upload = new Dictionary<string, object>();
     upload.Add("name", photoDetails.FacebookName);
     upload.Add("message", photoDetails.PhotoDescription);
     upload.Add("@file.jpg", mediaObject);
     Post("/" + photoDetails.AlbumId + "/photos", upload);
     return true;
 }
コード例 #4
0
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     // upload to facebook
     FacebookMediaObject image = new FacebookMediaObject
     {
         FileName = imgPath,
         ContentType = "image/jpeg"
     };
     byte[] fileBytes = File.ReadAllBytes(imgPath);
     image.SetValue(fileBytes);
     IDictionary<string, object> upload = new Dictionary<string, object>();
     upload.Add("name", imgName);
     upload.Add("message", imgMsg);
     upload.Add("@file.jpg", image);
     fb.UploadProgressChanged += uploadProgressChanged;
     fb.PostAsync("/me/photos", new Dictionary<string, object> {{"source", image}});
 }
コード例 #5
0
ファイル: Tea.aspx.cs プロジェクト: MnHung/kerkertea
        /// <summary>
        /// 上傳照片方法
        /// </summary>
        /// <param name="fbApp"></param>
        /// <param name="ImagePath"></param>
        /// <returns></returns>
        private JsonObject UploadPhoto(Facebook.FacebookClient fbApp, string ImagePath, byte[] filebytes, string ContentType)
        {
            Facebook.FacebookMediaObject media = new Facebook.FacebookMediaObject();
            if (ContentType == null)
            {
                ContentType = "image/jpeg";
            }
            media.ContentType = ContentType;
            media.FileName    = ImagePath;

            media.SetValue(filebytes);
            Dictionary <string, object> upload = new Dictionary <string, object>();

            upload.Add("name", "照片名稱");
            upload.Add("message", "照片描述");
            upload.Add("no_story", "1"); // 是否要發佈訊息
            upload.Add("access_token", Session["PageAccessToken"]);
            upload.Add("@file.jpg", media);

            return(fbApp.Post(_pageID + "/photos", upload) as JsonObject);
        }
コード例 #6
0
        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;
            }
        }
コード例 #7
0
 /// <summary>
 /// This method uploads the stored photo to Facebook on the given album Id.
 /// </summary>
 /// <param name="accessToken">the OAuth access token</param>
 /// <param name="AlbumId">The album Id to which the photo will belong.</param>
 private void UploadPhoto(string accessToken, string AlbumId)
 {
     FacebookApp facebookClient = new FacebookApp(accessToken);
     FacebookMediaObject mediaObject = new FacebookMediaObject
     {
         FileName = "image",
         ContentType = "image/png"
     };
     byte[] fileBytes = bytes;
     mediaObject.SetValue(fileBytes);
     IDictionary<string, object> upload = new Dictionary<string, object>();
     upload.Add("name", "photo name");
     upload.Add("message", PhotoLegend);
     upload.Add("@file.jpg", mediaObject);
     facebookClient.PostAsync("/" + AlbumId + "/photos", upload, UploadPhotoAsyncCallback);
 }
コード例 #8
0
        private void postearEnElMuro()
        {
            /*StreamResourceInfo sri = Application.GetResourceStream(new Uri("imagenes/iron_man.jpg", UriKind.Relative));
            
            BitmapImage src = new BitmapImage();
            src.SetSource(sri.Stream);
            
            var parametros = new Dictionary<string,object>();
            parametros["message"] = Message.Text;


            string attachementPath = "iron man";

            var file = new FacebookMediaStream
            {
                ContentType = "imagenes/iron_man.jpg",
                FileName = "iron man"
            };
            parametros["photos"] = file;*/

            //Se obtiene la imagen desde una ruta
            var res = Application.GetResourceStream(new Uri("imagenes/iron_man.jpg", UriKind.Relative));
            //se crea el streaming para leer el archivo
            var fileStream = res.Stream;
            //se crea el array de bytes con el largo del archivo
            byte[] buffer = new byte[fileStream.Length];
            //se leen los bytes del archivo y se almacena en el buffer
            fileStream.Read(buffer, 0, (int)fileStream.Length);
            //Se crea el diccionario que contiene todos los datos que seran enviados a fb
            var parameters = new Dictionary<string, object>();
           //Se coloca el texto de la imagen
            parameters["name"] = "Description for the pic";
            //se crea el tipo de imagen a postear
            parameters["TestPic"] = new FacebookMediaObject
            {
                //Tipo de objeto
                ContentType = "image/jpeg",
                //nombre del archivo para facebook
                FileName = "photo_name.jpg"

                //se setea el contenido de imagen (array de bytes)
            }.SetValue(buffer);
            //se envia la foto  (me/fotos) solo texto (me/feed)
            fbClient.PostAsync("me/photos", parameters);
        }
コード例 #9
0
        private static FacebookInfo UploadToFacebook(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename, bool repeated)
        {
            FacebookCredentials oAuth = createSession(true);
            if (oAuth == null)
            {
                return null;
            }

            SurfaceContainer container = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
            var client = new FacebookClient(config.Token);
            var img = new FacebookMediaObject {FileName = filename};
            img.SetValue(container.ToByteArray());
            img.ContentType = "multipart/form-data";

            var param = new Dictionary<string, object> {{"attachment", img}};
            if (!string.IsNullOrEmpty(title))
                param.Add("message", title);

            // Not on timeline?
            if (config.NotOnTimeline)
                param.Add("no_story", "1");

            JsonObject result;
            try
            {
                result = (JsonObject) client.Post("me/photos", param);
            }
            catch (FacebookOAuthException ex)
            {
                if (!repeated && ex.ErrorCode == 190) // App no long authorized, reauthorize if possible
                {
                    config.Token = null;
                    return UploadToFacebook(surfaceToUpload, outputSettings, title, filename, true);
                }
                throw;
            }
            catch (Exception ex)
            {
                LOG.Error("Error uploading to Facebook.", ex);
                throw;
            }

            FacebookInfo facebookInfo = FacebookInfo.FromUploadResponse(result);
            LOG.Debug("Upload to Facebook was finished");
            return facebookInfo;
        }
コード例 #10
0
        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() }
            });
        }
コード例 #11
0
ファイル: User.cs プロジェクト: PatriceS/Medienprogrammierung
        /*
        public void uploadPicture(string albumID, String FileName)
        {
            if (this.fmo == null)
            {
                fmo = new FacebookMediaObject { FileName = FileName, ContentType = "image/jpg" };
            }
            else
            {
                fmo.FileName = FileName;
                fmo.ContentType = "image/jpg";
            }

            var bytes = System.IO.File.ReadAllBytes(fmo.FileName);
            fmo.SetValue(bytes);

            var postInfo = new Dictionary<string, object>();
            postInfo.Add("message", "Tolle Nachricht");
            postInfo.Add("image", fmo);
            this.fb.UploadProgressChanged += fb_UploadProgressChanged;
            this.fb.PostCompleted += fb_PostCompleted;
            this.fb.PostAsync("/" + albumID + "/photos", postInfo);
            this.mainForm.cancelUploadButton.Enabled = true;
            this.mainForm.publishFacebook.Enabled = false;

        }
        */
        public void uploadPicture(string albumID, PictureBox pictureBox)
        {
            String path = Config.SAVE_TEMP_PATH;

            Bitmap bitmap = (Bitmap)pictureBox.Image;
            Graphics g = Graphics.FromImage(bitmap);
            g.Save();
            g.Dispose();

            bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
            //bitmap.Dispose();

            /*
            BitmapData bmData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
            ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            int stride = bmData.Stride;

            System.IntPtr Scan0 = bmData.Scan0;

            // Get the address of the first line.
               //     IntPtr ptr = bmpData.Scan0;

            // Declare an array to hold the bytes of the bitmap.
            int testBytes = Math.Abs(bmData.Stride) * bmData.Height;
            byte[] rgbValues = new byte[testBytes];

            // Copy the RGB values into the array.
            System.Runtime.InteropServices.Marshal.Copy(Scan0, rgbValues, 0, testBytes);

            // Unlock the bits.
            bitmap.UnlockBits(bmData);
            */

            if (this.fmo == null)
            {
                fmo = new FacebookMediaObject
                {
                    FileName = path,
                    ContentType = "image/jpeg" };
            }
            else
            {
                fmo.FileName = path;
                fmo.ContentType = "image/jpeg";
            }
               // MessageBox.Show(rgbValues.Length.ToString());

            var bytes = System.IO.File.ReadAllBytes(fmo.FileName);
            fmo.SetValue(bytes);

            var postInfo = new Dictionary<string, object>();
            postInfo.Add("message", "Tolle Nachricht");
            postInfo.Add("image", fmo);
            this.fb.UploadProgressChanged += fb_UploadProgressChanged;
            this.fb.PostCompleted += fb_PostCompleted;
            this.fb.PostAsync("/" + albumID + "/photos", postInfo);
            this.mainForm.cancelUploadButton.Enabled = true;
            this.mainForm.publishFacebook.Enabled = false;
        }
コード例 #12
0
        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);
        }
コード例 #13
0
        public string FacebookComposeMessageForPage(String message, String profileid, string userid, string currentdatetime, string imagepath, string link)
        {
            string ret = "";
            Domain.Socioboard.Domain.FacebookAccount objFacebookAccount = objFacebookAccountRepository.getFacebookAccountDetailsById(profileid, Guid.Parse(userid));
            FacebookClient fb = new FacebookClient();

            fb.AccessToken = objFacebookAccount.AccessToken;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            var args = new Dictionary<string, object>();
            if (!string.IsNullOrEmpty(message))
            {
                args["message"] = message;
            }
            try
            {
                if (!string.IsNullOrEmpty(imagepath))
                {
                    Uri u = new Uri(imagepath);
                    string filename = string.Empty;
                    string extension = string.Empty;
                    extension = Path.GetExtension(u.AbsolutePath).Replace(".", "");
                    var media = new FacebookMediaObject
                    {
                        FileName = "filename",
                        ContentType = "image/" + extension
                    };
                    //byte[] img = System.IO.File.ReadAllBytes(imagepath);
                    var webClient = new WebClient();
                    byte[] img = webClient.DownloadData(imagepath);
                    media.SetValue(img);
                    args["source"] = media;
                    ret = fb.Post("v2.0/" + objFacebookAccount.FbUserId + "/photos", args).ToString();
                }
                else
                {
                    if (!string.IsNullOrEmpty(link))
                    {
                        args["link"] = link;
                    }
                    ret = fb.Post("v2.0/" + objFacebookAccount.FbUserId + "/feed", args).ToString();
                }
                ret = "success";
            }
            catch (Exception ex)
            {
                ret = "failure";
            }
            return ret;
        }
コード例 #14
0
        internal override void PublishWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            #region Check for cancellation

            if (CheckForCancelledWorker())
            {
                PublishWorkerResult = PublishWorkerResults.Cancelled;
                facebookClient = null;
                return;
            }

            if (activationState == Protection.ActivationState.Activated)
                AnalyticsHelper.FireEvent("Each share - activation state - activated");
            else if (activationState == Protection.ActivationState.Trial)
                AnalyticsHelper.FireEvent("Each share - activation state - trial");
            else if (activationState == Protection.ActivationState.TrialExpired)
                AnalyticsHelper.FireEvent("Each share - activation state - trial expired");
            else if (activationState == Protection.ActivationState.Unlicensed)
                AnalyticsHelper.FireEvent("Each share - activation state - unlicensed");

            #endregion Check for cancellation

            #region Prepare video. We always do this, even if the user already saved it, because Facebook has formats it prefers

            using (var saveWorker = new SaveWorker(HighlightObject))
            {
                saveWorker.ProgressChanged += saveWorker_ProgressChanged;

            #if RELEASE
                saveWorker.HideOutputFile = true;
            #endif

                saveWorker.OutputFormat = SaveWorker.OutputFormats.Facebook;

                try
                {
                    string tempOutputFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + HighlightObject.InputFileObject.SourceFileInfo.Extension);
                    saveWorker.RunWorkerAsync(tempOutputFilePath);

                    // try connecting while we start the saving
                    if (InitializeFacebookClient() == false)
                    {
                        PublishWorkerResult = PublishWorkerResults.UnableToAuthenticate;
                        saveWorker.CancelAsync();
                        return;
                    }

                    while (saveWorker.IsBusy)
                    { // wait for the scanworker to finish
                        if (CheckForCancelledWorker())
                        {
                            saveWorker.CancelAsync();
                            while (saveWorker.IsBusy) { System.Windows.Forms.Application.DoEvents(); } // DoEvents is required: http://social.msdn.microsoft.com/Forums/en-US/clr/thread/ad9a9a02-8a11-4bb8-b50a-613bcaa46886
                            PublishWorkerResult = PublishWorkerResults.Cancelled;
                            facebookClient = null;
                            return;
                        }

                        System.Threading.Thread.Sleep(500);
                    }
                }
                catch (InvalidOperationException ex)
                {
                    Logger.Error("Error starting SaveWorker! " + ex.ToString());
                }

                if (saveWorker.PublishWorkerResult != PublishWorkerResults.Success ||
                    saveWorker.OutputFileInfo == null)
                {
                    ErrorMessage = saveWorker.ErrorMessage;
                    PublishWorkerResult = PublishWorkerResults.UnableToShare;
                    facebookClient = null;
                    return;
                }

            #endregion Prepare video. We always do this, even if the user already saved it, because Facebook has formats it prefers

                #region Upload to Facebook

                var parameters = new Dictionary<string, object>();
                var bytes = File.ReadAllBytes(saveWorker.OutputFileInfo.FullName);

                parameters["source"] = new FacebookMediaObject { ContentType = "video/mpeg", FileName = "video.mp4" }.SetValue(bytes);
                parameters["title"] = HighlightObject.Title;

                // let's be more subtle and not spam their video.
                // it looks like Facebook is using the description field in the newsfeed instead of the title. lame.
                //parameters["description"] = "Found with Highlight Hunter. Download free for Mac and PC at www.HighlightHunter.com.";
                parameters["description"] = HighlightObject.Title;

                facebookClient.PostAsync("/me/videos", parameters);

                Logger.Info("Posted in background");

                trackFirstShare();

                while (!uploadCompleted)
                {
                    if (CheckForCancelledWorker())
                    {
                        facebookClient.CancelAsync();
                        PublishWorkerResult = PublishWorkerResults.Cancelled;
                        break;
                    }

                    Thread.Sleep(500); // this is on a background thread
                }

                #endregion Upload to Facebook

                #region Cleanup

                try
                {
                    saveWorker.OutputFileInfo.Delete();
                }
                catch (Exception ex)
                {
                    Logger.Error("Unable to delete " + ex);
                }

                #endregion Cleanup
            }

            facebookClient = null;

            // result is determined by facebookClient_PostCompleted
            AnalyticsHelper.FireEvent("Each share - Facebook - result - " + PublishWorkerResult);
        }
コード例 #15
0
        private void WebBrowserOnLoadCompleted(object sender, NavigationEventArgs navigationEventArgs)
        {
            FacebookOAuthResult oauthResult;
            if (!_facebookClient.TryParseOAuthCallbackUrl(navigationEventArgs.Uri, out oauthResult))
            {
                return;
            }

            if (oauthResult.IsSuccess)
            {
                try
                {
                    byte[] imageBytes = new byte[0];
                    using (MemoryStream ms = new MemoryStream())
                    {
                        Resource.va55qx0t.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                        imageBytes = ms.ToArray();
                    }

                    _facebookClient.AccessToken = oauthResult.AccessToken;

                    _facebookClient.PostCompleted += (o, e) =>
                    {
                        if (e.Cancelled || e.Error != null)
                        {
                            return;
                        }

                        var result = e.GetResultData();
                    };

                    var parameters = new Dictionary<string, object>();
                    parameters["message"] = "my first photo upload using Facebook C# SDK";
                    parameters["file"] = new FacebookMediaObject
                    {
                        ContentType = "image/jpeg",
                        FileName = "image.jpeg"
                    }.SetValue(imageBytes);

                    _facebookClient.PostTaskAsync("me/photos", parameters);
                }
                catch (FacebookApiException ex)
                {
                    // handel error message
                }
            }
        }
コード例 #16
0
        public string SheduleFacebookGroupMessage(string FacebookId, string UserId, string sscheduledmsgguid)
        {
            string str = string.Empty;
            int facint = 0;
            try
            {
                objScheduledMessage = objScheduledMessageRepository.GetScheduledMessageDetails(Guid.Parse(sscheduledmsgguid));
                GroupScheduleMessageRepository grpschedulemessagerepo = new GroupScheduleMessageRepository();
                Domain.Socioboard.Domain.GroupScheduleMessage _GroupScheduleMessage = grpschedulemessagerepo.GetScheduleMessageId(objScheduledMessage.Id);
                if (objFacebookAccountRepository.checkFacebookUserExists(FacebookId, Guid.Parse(UserId)))
                {
                    objFacebookAccount = objFacebookAccountRepository.getFacebookAccountDetailsById(FacebookId, Guid.Parse(UserId));
                }
                else
                {
                    objFacebookAccount = objFacebookAccountRepository.getFacebookAccountDetailsById(FacebookId);
                }
                if (objFacebookAccount != null)
                {
                    FacebookClient fbclient = new FacebookClient(objFacebookAccount.AccessToken);
                    var args = new Dictionary<string, object>();
                    args["message"] = objScheduledMessage.ShareMessage;
                    string imagepath = objScheduledMessage.PicUrl;

                    var facebookpost = "";
                    try
                    {
                        if (!string.IsNullOrEmpty(imagepath))
                        {
                            var media = new FacebookMediaObject
                            {
                                FileName = "filename",
                                ContentType = "image/jpeg"
                            };
                            byte[] img = System.IO.File.ReadAllBytes(imagepath);
                            media.SetValue(img);
                            args["source"] = media;
                            facebookpost = fbclient.Post("v2.0/" + _GroupScheduleMessage.GroupId + "/photos", args).ToString();
                        }
                        else
                        {
                            facebookpost = fbclient.Post("v2.0/" + _GroupScheduleMessage.GroupId + "/feed", args).ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        objFacebookAccountRepository = new FacebookAccountRepository();
                        objFacebookAccount.IsActive = 2;
                        objFacebookAccountRepository.updateFacebookUserStatus(objFacebookAccount);
                        Domain.Socioboard.Domain.SocialProfile objSocialProfile = new Domain.Socioboard.Domain.SocialProfile();
                        SocialProfilesRepository objSocialProfilesRepository = new SocialProfilesRepository();
                        string errormsg = ex.Message;
                        if (errormsg.Contains("access token"))
                        {
                            objSocialProfile.UserId = objFacebookAccount.UserId;
                            objSocialProfile.ProfileId = objFacebookAccount.FbUserId;
                            objSocialProfile.ProfileStatus = 2;
                            objSocialProfilesRepository.updateSocialProfileStatus(objSocialProfile);
                        }
                        Console.WriteLine(ex.Message);
                        str = ex.Message;
                    }

                    if (!string.IsNullOrEmpty(facebookpost))
                    {
                        facint++;
                        str = "Message post on facebook for Id :" + objFacebookAccount.FbUserId + " and Message: " + objScheduledMessage.ShareMessage;
                        ScheduledMessage schmsg = new ScheduledMessage();
                        schmsg.UpdateScheduledMessageByMsgId(Guid.Parse(sscheduledmsgguid));
                        logger.Error("SheduleFacebookGroupMessageCount" + facint);
                    }
                }
                else
                {
                    str = "facebook account not found for id" + objScheduledMessage.ProfileId;
                }
            }
            catch (Exception ex)
            {
                str = ex.Message;
            }
            return str;
        }
コード例 #17
0
        /// <summary>
        /// picture post to facebook
        /// <summary>
        public void postToFB(String url, byte[] data, Action retf)
        {
            FacebookClient _fbClient = new FacebookClient(_accessToken);
            var parameters = new Dictionary<string, object>();
            parameters["message"] = "WP7 app presentation";            

            parameters["file"] = new FacebookMediaObject
            {
                ContentType = "image/jpeg",
                FileName = "image.jpg"
            }.SetValue(data);

            _fbClient.PostCompleted += _fbClient_PostCompleted;
             // async request
            _fbClient.PostAsync(url, parameters, retf);
        }
コード例 #18
0
ファイル: LegacyRestApi.cs プロジェクト: rehabriad/MyNokat
        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;
            }
        }
コード例 #19
0
        public string SheduleFacebookMessage(string FacebookId, string UserId, string sscheduledmsgguid)
        {
            string str = string.Empty;
            try
            {
                objScheduledMessage = objScheduledMessageRepository.GetScheduledMessageDetails(Guid.Parse(sscheduledmsgguid));

                if (objFacebookAccountRepository.checkFacebookUserExists(FacebookId, Guid.Parse(UserId)))
                {
                    objFacebookAccount = objFacebookAccountRepository.getFacebookAccountDetailsById(FacebookId, Guid.Parse(UserId));
                }
                else
                {
                    objFacebookAccount = objFacebookAccountRepository.getFacebookAccountDetailsById(FacebookId);
                }
                if (objFacebookAccount != null)
                {
                    FacebookClient fbclient = new FacebookClient(objFacebookAccount.AccessToken);
                    var args = new Dictionary<string, object>();
                    args["message"] = objScheduledMessage.ShareMessage;
                    string imagepath = objScheduledMessage.PicUrl;

                    var facebookpost = "";
                    try
                    {


                        if (!string.IsNullOrEmpty(imagepath))
                        {
                            try
                            {
                                Uri u = new Uri(imagepath);
                                string filename = string.Empty;
                                string extension = string.Empty;
                                extension = Path.GetExtension(u.AbsolutePath).Replace(".", "");
                                var media = new FacebookMediaObject
                                {
                                    FileName = "filename",
                                    ContentType = "image/" + extension
                                };
                                //byte[] img = System.IO.File.ReadAllBytes(imagepath);
                                var webClient = new WebClient();
                                byte[] img = webClient.DownloadData(imagepath);
                                media.SetValue(img);
                                args["source"] = media;
                                facebookpost = fbclient.Post("v2.0/" + objFacebookAccount.FbUserId + "/photos", args).ToString();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(imagepath + "not Found");
                                if (!string.IsNullOrEmpty(objScheduledMessage.Url))
                                {
                                    args["link"] = objScheduledMessage.Url;
                                }
                                facebookpost = fbclient.Post("v2.0/" + objFacebookAccount.FbUserId + "/feed", args).ToString();
                            }
                        }
                        else
                        {
                            facebookpost = fbclient.Post("v2.0/" + objFacebookAccount.FbUserId + "/feed", args).ToString();
                        }
                    }

                    catch (Exception ex)
                    {
                        //FacebookAccount ObjFacebookAccount = new FacebookAccount();
                        //objFacebookAccount = new Domain.Socioboard.Domain.FacebookAccount();
                        objFacebookAccountRepository = new FacebookAccountRepository();
                        //objFacebookAccount.IsActive = 2;
                        objFacebookAccountRepository.updateFacebookUserStatus(objFacebookAccount);
                        Domain.Socioboard.Domain.SocialProfile objSocialProfile = new Domain.Socioboard.Domain.SocialProfile();
                        SocialProfilesRepository objSocialProfilesRepository = new SocialProfilesRepository();
                        //logger.Error(ex.Message);
                        string errormsg = ex.Message;
                        if (errormsg.Contains("access token"))
                        {
                            objSocialProfile.UserId = objFacebookAccount.UserId;
                            objSocialProfile.ProfileId = objFacebookAccount.FbUserId;
                            objSocialProfile.ProfileStatus = 2;
                            objSocialProfilesRepository.updateSocialProfileStatus(objSocialProfile);
                        }
                        Console.WriteLine(ex.Message);
                        str = ex.Message;
                    }

                    if (!string.IsNullOrEmpty(facebookpost))
                    {
                        str = "Message post on facebook for Id :" + objFacebookAccount.FbUserId + " and Message: " + objScheduledMessage.ShareMessage;
                        ScheduledMessage schmsg = new ScheduledMessage();
                        schmsg.UpdateScheduledMessageByMsgId(Guid.Parse(sscheduledmsgguid));
                    }
                }
                else
                {
                    str = "facebook account not found for id" + objScheduledMessage.ProfileId;
                }
            }
            catch (Exception ex)
            {
                str = ex.Message;
            }
            return str;
        }
コード例 #20
0
ファイル: GraphApi.cs プロジェクト: Adron/Regiztry
        public static string UploadPictureToWall(string accessToken, string filePath)
        {
            // sample usage: UploadPictureToWall(accessToken, @"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg");

            var mediaObject = new FacebookMediaObject
                                  {
                                      FileName = System.IO.Path.GetFileName(filePath),
                                      ContentType = "image/jpeg"
                                  };

            mediaObject.SetValue(System.IO.File.ReadAllBytes(filePath));

            try
            {
                var fb = new FacebookClient(accessToken);

                var result = (IDictionary<string, object>)fb.Post("me/photos", new Dictionary<string, object>
                                       {
                                           { "source", mediaObject },
                                           { "message","photo" }
                                       });

                var postId = (string)result["id"];

                Console.WriteLine("Post Id: {0}", postId);

                // Note: This json result is not the orginal json string as returned by Facebook.
                Console.WriteLine("Json: {0}", result.ToString());

                return postId;
            }
            catch (FacebookApiException ex)
            {
                // Note: make sure to handle this exception.
                throw;
            }
        }
コード例 #21
0
 public GiveOneMediaObjectOnlyThen()
 {
     _parameters = new Dictionary<string, object>();
     _parameters["source"] = new FacebookMediaObject();
 }
コード例 #22
0
        public string FacebookComposeMessageForPage(String message, String profileid, string userid, string currentdatetime, string imagepath)
        {
            string ret = "";
            Domain.Socioboard.Domain.FacebookAccount objFacebookAccount = objFacebookAccountRepository.getFacebookAccountDetailsById(profileid, Guid.Parse(userid));
            FacebookClient fb = new FacebookClient();

            fb.AccessToken = objFacebookAccount.AccessToken;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            var args = new Dictionary<string, object>();
            args["message"] = message;
            if (!string.IsNullOrEmpty(imagepath))
            {
                var media = new FacebookMediaObject
                {
                    FileName = "filename",
                    ContentType = "image/jpeg"
                };
                byte[] img = System.IO.File.ReadAllBytes(imagepath);
                media.SetValue(img);
                args["source"] = media;
                ret = fb.Post("v2.0/" + objFacebookAccount.FbUserId + "/photos", args).ToString();
            }
            else
            {
                ret = fb.Post("v2.0/" + objFacebookAccount.FbUserId + "/feed", args).ToString();
                //   ret = fb.Post("/" + objFacebookAccount.FbUserId + "/photos", args).ToString();

            }


            //Domain.Socioboard.Domain.FacebookAccount objFacebookAccount = objFacebookAccountRepository.getFacebookAccountDetailsById(profileid, Guid.Parse(userid));
            //FacebookClient fb = new FacebookClient();

            //fb.AccessToken = objFacebookAccount.AccessToken;
            //fb.AccessToken = "CAACEdEose0cBANZCpywnaiXtamEZBNRpaZAj3zY9y6e62hTfHQ9oKy5LSc9MiZATY4RV5F19CgLNadYuL1neTaCU3ikhQwB7x6FtFcYOuQlQZBNL1xjQuohzHGlL9xrzHd8lQZBcK4KPwObj2ALLgnbNLmqZAywMs2JL3Ke0Vk36lm8fPzHbeode7Kndw9gbgLC5o5CmhdtzWwWzhxxjljk";
            //System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            //ret = fb.Post("/" + objFacebookAccount.FbUserId + "/feed", args).ToString();
            return ret;
        }
コード例 #23
0
        private void postearEnElMuro()
        {
            //IsolatedStorageFileStream fileStream ;
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStreamm = myIsolatedStorage.OpenFile("FotoSacada", FileMode.Open, FileAccess.Read))
                {
                    //se crea el streaming para leer el archivo

                    //se crea el array de bytes con el largo del archivo
                    byte[] buffer = new byte[fileStreamm.Length];
                    //se leen los bytes del archivo y se almacena en el buffer
                    fileStreamm.Read(buffer, 0, (int)fileStreamm.Length);
                    //Se crea el diccionario que contiene todos los datos que seran enviados a fb
                    var parameters = new Dictionary<string, object>();
                    //Se coloca el texto de la imagen
                    parameters["name"] = post;
                    //se crea el tipo de imagen a postear
                    parameters["TestPic"] = new FacebookMediaObject
                    {
                        //Tipo de objeto
                        ContentType = "image/jpeg",
                        //nombre del archivo para facebook
                        FileName = "photo_name.jpg"

                        //se setea el contenido de imagen (array de bytes)
                    }.SetValue(buffer);
                    //se envia la foto  (me/fotos) solo texto (me/feed)
                    fbClient.PostAsync("me/photos", parameters);
                }
            }
        }
コード例 #24
0
        private void ShareToFacebook()
        {
            if( _fbClient == null || _fbClient.AccessToken == null)
            {
                LoginToFacebook();
                Interlocked.Exchange(ref uploadInProgres, 0);
                return;
            }

            loading.IsIndeterminate = true;
            byte[] contents = null;
            try
            {
                contents = GetLastSavedPictureContents();
                if (contents == null || contents.Length == 0)
                {
                    UploadFinished(false, SocialNetwork.FACEBOOK);
                    MessageBox.Show("Could not load last saved picture. Sorry.", "Error", MessageBoxButton.OK);
                    return;
                }
            }
            catch (Exception e)
            {
                UploadFinished(false, SocialNetwork.FACEBOOK);
                MessageBox.Show("Error occurred during reading saved image.", "Error", MessageBoxButton.OK);
                return;
            }

            var mediaObject = new FacebookMediaObject
            {
                FileName = filename,
                ContentType = "image/jpeg",
            };
            mediaObject.SetValue(contents);

            var parameters = new Dictionary<string, object>();
            parameters["access_token"] = _fbClient.AccessToken;

            parameters["source"] = mediaObject;
            if (titleBar.Text != null && !titleBar.Text.Equals(shareText))
            {
                parameters["message"] = titleBar.Text;
            }

            _fbClient.PostAsync("me/photos", parameters);
        }
コード例 #25
0
        public  void ShareOnFacebook()
        {
            string post = "";
            post = "";

            if (ffid == " " && fftoken == " " || ffid == null && fftoken == null)
            {
                NavigationService.Navigate(new Uri(string.Format("/FacebookLoginPage.xaml?vpost={0}", post), UriKind.Relative));
            }
            else
            {


                var fb = new FacebookClient(fftoken);

              fb.PostCompleted += (o, e) =>
                {
                    if (e.Cancelled || e.Error != null)
                    {
                        Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));
                        return;
                    }

                    var result = e.GetResultData();

                Dispatcher.BeginInvoke(() =>
                {
                    progbar1.IsIndeterminate = false;
                    progbar1.Visibility = Visibility.Collapsed;
                   // MessageBox.Show("Successfully shared on Facebook");
                    //if (NavigationService.CanGoBack)
                    //    NavigationService.GoBack();

                    buyNowScreen = new Popup();
                    buyNowScreen.Child =
                        new NotifyAlert
                            ("Successfully shared on Facebook");
                    buyNowScreen.IsOpen = true;
                    buyNowScreen.VerticalOffset = 0;
                    buyNowScreen.HorizontalOffset = 0;

                });
                };

              //IsolatedSettingsHelper.SetValue<bool>("sharedonfacebook", true);

              //Dispatcher.BeginInvoke(() =>
              //{
              //    buyNowScreen = new Popup();
              //    buyNowScreen.Child =
              //        new NotifyAlert
              //            ("Successfully shared on Facebook");
              //    buyNowScreen.IsOpen = true;
              //    buyNowScreen.VerticalOffset = 0;
              //    buyNowScreen.HorizontalOffset = 0;
              //});

                var parameters = new Dictionary<string, object>();
                parameters["name"] = photo_text.Text;

                var resized = img.Resize(img.PixelWidth / 2, img.PixelHeight / 2, WriteableBitmapExtensions.Interpolation.Bilinear);

                var fileStream = new MemoryStream();
                resized.SaveJpeg(fileStream, resized.PixelWidth, resized.PixelHeight, 100, 100);
                fileStream.Seek(0, SeekOrigin.Begin);

                parameters["TestPic"] = new FacebookMediaObject
                {
                    ContentType = "image/jpeg",
                    FileName = fileName + ".jpg"

                }.SetValue(fileStream.ToArray());//.SetValue(photoStream.ToArray());

                //fb.PostCompleted += fb_PostCompleted;

             fb.PostAsync("me/Photos", parameters);



                string channel = IsolatedSettingsHelper.GetValue<string>("latest_update_channel");

                IsolatedSettingsHelper.SetValue<string>("latest_update", "You shared a photo");
                IsolatedSettingsHelper.SetValue<string>("latest_update_channel", channel + " Facebook");
                IsolatedSettingsHelper.SetValue<string>("latest_update_time", DateTime.Now.ToString());
            }

        }