private void InsertPictureFromFile()
        {
            if (!uploadingPicture)
            {
                String pictureUrl = string.Empty;
                using (Microsoft.WindowsMobile.Forms.SelectPictureDialog s = new Microsoft.WindowsMobile.Forms.SelectPictureDialog())
                {
                    if (s.ShowDialog() == DialogResult.OK)
                    {
                        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PostUpdate));
                        this.pictureFromCamers.Image = PockeTwit.Themes.FormColors.GetThemeIcon("takepicture.png");
                        if (DetectDevice.DeviceType == DeviceType.Standard)
                        {
                            this.pictureFromCamers.Visible = false;
                        }
                        uploadedPictureOrigin = "file";

                        pictureService = GetMediaService();
                        if (pictureService.CanUploadMessage && ClientSettings.SendMessageToMediaService)
                        {
                            AddPictureToForm(s.FileName, pictureFromStorage);
                            picturePath = s.FileName;
                            //Reduce length of message 140-pictureService.UrlLength
                            pictureUsed = true;
                        }
                        else
                        {
                            uploadingPicture = true;
                            AddPictureToForm(ClientSettings.IconsFolder() + "wait.png", pictureFromStorage);
                            using (PicturePostObject ppo = new PicturePostObject())
                            {
                                ppo.Filename = s.FileName;
                                ppo.Username = AccountToSet.UserName;
                                ppo.Password = AccountToSet.Password;
                                ppo.UseAsync = false;
                                Cursor.Current = Cursors.WaitCursor;
                                pictureService.PostPicture(ppo);
                            }
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Uploading picture...");
            }
        }
        private bool PostTheUpdate()
        {
            LocationFinder.StopGPS();
            if (!string.IsNullOrEmpty(StatusText))
            {
                Cursor.Current = Cursors.WaitCursor;
                string UpdateText = TrimTo140(StatusText);

                if (string.IsNullOrEmpty(UpdateText))
                {
                    MessageBox.Show("There was an error shortening the text. Please shorten the message or try again later.");
                    return false;
                }


                if (!string.IsNullOrEmpty(picturePath) && pictureService.CanUploadMessage && ClientSettings.SendMessageToMediaService )
                {
                    PicturePostObject ppo = new PicturePostObject();
                    ppo.Filename = picturePath;
                    ppo.Username = AccountToSet.UserName;
                    ppo.Password = AccountToSet.Password;
                    ppo.Message = StatusText;

                    if (pictureService.CanUploadGPS && this.GPSLocation != null)
                    {
                        try
                        {
                            ppo.Lat = GPSLocation.Split(',')[0];
                            ppo.Lon = GPSLocation.Split(',')[1];
                        }
                        catch { }
                    }

                    return pictureService.PostPictureMessage(ppo);
                }
                else
                {


                    Yedda.Twitter TwitterConn = new Yedda.Twitter();
                    TwitterConn.AccountInfo = this.AccountToSet;

                    try
                    {
                        if (this.GPSLocation != null)
                        {
                            TwitterConn.SetLocation(this.GPSLocation);
                        }
                    }
                    catch { }


                    string retValue = TwitterConn.Update(UpdateText, in_reply_to_status_id, Yedda.Twitter.OutputFormatType.XML);

                    uploadedPictureURL = string.Empty;
                    uploadingPicture = false;

                    if (string.IsNullOrEmpty(retValue))
                    {
                        MessageBox.Show("Error posting status -- empty response.  You may want to try again later.");
                        return false;
                    }
                    try
                    {
                        Library.status.DeserializeSingle(retValue, AccountToSet);
                    }
                    catch
                    {
                        MessageBox.Show("Error posting status -- bad response.  You may want to try again later.");
                        return false;
                    }

                    return true;
                }
            }
            return true;
        }
Exemple #3
0
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPictureMessage(string url, PicturePostObject ppo)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                string boundary = System.Guid.NewGuid().ToString();
                request.Credentials = new NetworkCredential(ppo.Username, ppo.Password);
                request.Headers.Add("Accept-Language", "cs,en-us;q=0.7,en;q=0.3");
                request.PreAuthenticate = true;
                request.ContentType = string.Format("multipart/form-data;boundary={0}", boundary);

                //request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "POST";
                request.Timeout = 20000;
                string header = string.Format("--{0}", boundary);
                string ender = "\r\n" + header + "\r\n";

                StringBuilder contents = new StringBuilder();

                contents.Append(CreateContentPartString(header, "username", ppo.Username));
                contents.Append(CreateContentPartString(header, "password", ppo.Password));
                contents.Append(CreateContentPartString(header, "message", ppo.Message));

                contents.Append(CreateContentPartPicture(header));

                //Create the form message to send in bytes
                byte[] message = Encoding.UTF8.GetBytes(contents.ToString());
                byte[] footer = Encoding.UTF8.GetBytes(ender);
                request.ContentLength = message.Length + ppo.PictureData.Length + footer.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(message, 0, message.Length);
                    requestStream.Write(ppo.PictureData, 0, ppo.PictureData.Length);
                    requestStream.Write(footer, 0, footer.Length);
                    requestStream.Flush();
                    requestStream.Close();

                    using (WebResponse response = request.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            XmlDocument responseXML = new XmlDocument();
                            string resp = reader.ReadToEnd();
                            responseXML.LoadXml(resp);
                            return responseXML;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_UPLOAD));
                return null;
            }

        }
Exemple #4
0
        /// <summary>
        /// Post a picture.
        /// </summary>
        /// <param name="postData"></param>
        public override void PostPicture(PicturePostObject postData)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "",API_ERROR_UPLOAD));
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(postData.Username) ||
                string.IsNullOrEmpty(postData.Password) )
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_UPLOAD));
            }

            #endregion

            using (System.IO.FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    //Load the picture data
                    byte[] incoming = new byte[file.Length];
                    file.Read(incoming, 0, incoming.Length);

                    if (postData.UseAsync)
                    {
                        workerPPO = (PicturePostObject) postData.Clone();
                        workerPPO.PictureData = incoming;

                        if (workerThread == null)
                        {
                            workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessUpload));
                            workerThread.Name = "PictureUpload";
                            workerThread.Start();
                        }
                        else
                        {
                            OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.NotReady, "", API_ERROR_NOTREADY));
                        }
                    }
                    else
                    {
                        //use sync.
                        postData.PictureData = incoming;
                        XmlDocument uploadResult = UploadPicture(API_UPLOAD, postData);

                        if (uploadResult == null)
                        {
                            return;
                        }

                        if (uploadResult.SelectSingleNode("rsp").Attributes["status"].Value == "fail")
                        {
                            string ErrorText = uploadResult.SelectSingleNode("//err").Attributes["msg"].Value;
                            OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, ErrorText));
                        }
                        else
                        {
                            string URL = uploadResult.SelectSingleNode("//mediaurl").InnerText;
                            OnUploadFinish(new PictureServiceEventArgs(PictureServiceErrorLevel.OK, URL, string.Empty, postData.Filename));
                        }
                    }
                }
                catch (Exception e)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Fetch a URL.
        /// </summary>
        /// <param name="pictureURL"></param>
        public override void FetchPicture(string pictureURL)
        {
            #region Argument check

            //Need a url to read from.
            if (string.IsNullOrEmpty(pictureURL))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_DOWNLOAD));
            }

            #endregion

            try
            {
                workerPPO = new PicturePostObject();
                workerPPO.Message = pictureURL;

                if (workerThread == null)
                {
                    workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessDownload));
                    workerThread.Name = "PictureUpload";
                    workerThread.Start();
                }
                else
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.NotReady, string.Empty, "A request is already running."));
                }
            }
            catch (Exception e)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_DOWNLOAD));
            } 
        }
Exemple #6
0
        public override bool PostPictureMessage(PicturePostObject postData)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return false;
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(postData.Username) ||
                string.IsNullOrEmpty(postData.Password))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return false;
            }

            #endregion

            using (System.IO.FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    //Load the picture data
                    byte[] incoming = new byte[file.Length];
                    file.Read(incoming, 0, incoming.Length);

                    postData.PictureData = incoming;
                    XmlDocument uploadResult = UploadPictureMessage(API_UPLOAD_POST, postData);

                    if (uploadResult == null)
                    {
                        //event allready thrown in upload
                        return false;
                    }

                    if (uploadResult.SelectSingleNode("rsp").Attributes["status"].Value == "fail")
                    {
                        string ErrorText = uploadResult.SelectSingleNode("//err").Attributes["msg"].Value;
                        OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, ErrorText));
                        return false;
                    }

                }
                catch (Exception e)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private string UploadPictureMessage(string url, PicturePostObject ppo)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                string boundary = System.Guid.NewGuid().ToString();
                request.Credentials = new NetworkCredential(ppo.Username, ppo.Password);
                request.Headers.Add("Accept-Language", "cs,en-us;q=0.7,en;q=0.3");
                request.PreAuthenticate = true;
                request.ContentType = string.Format("multipart/form-data;boundary={0}", boundary);
                request.Headers.Add("action", "postMedia");

                //request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "POST";
                request.Timeout = 20000;
                string header = string.Format("--{0}", boundary);
                string ender = "\r\n" + header + "\r\n";

                StringBuilder contents = new StringBuilder();

                contents.Append(CreateContentPartString(header, "u", ppo.Username));
                contents.Append(CreateContentPartString(header, "p", ppo.Password));
                contents.Append(CreateContentPartString(header, "k", APPLICATION_NAME));
                contents.Append(CreateContentPartString(header, "t", ppo.Message));
                contents.Append(CreateContentPartString(header, "d", ppo.Message));
                contents.Append(CreateContentPartString(header, "action", "postMedia"));

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    contents.Append(CreateContentPartString(header, "latlong", string.Format("{0},{1}",ppo.Lat,ppo.Lon) ));
                }

                contents.Append(CreateContentPartMedia(header));

                //Create the form message to send in bytes

                byte[] message = Encoding.UTF8.GetBytes(contents.ToString());
                byte[] footer = Encoding.UTF8.GetBytes(ender);
                request.ContentLength = message.Length + ppo.PictureData.Length + footer.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(message, 0, message.Length);
                    requestStream.Write(ppo.PictureData, 0, ppo.PictureData.Length);
                    requestStream.Write(footer, 0, footer.Length);
                    requestStream.Flush();
                    requestStream.Close();

                    using (WebResponse response = request.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            String receiverResponse = reader.ReadToEnd();
                            //should be 0 with a following URL for the picture.

                            return receiverResponse;
                        }
                    }

                }
                return string.Empty;
            }
            catch (Exception e)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return string.Empty;
            }
        }
Exemple #8
0
        /// <summary>
        /// Request authorisation key for use in posting.
        /// </summary>
        /// <param name="ppo"></param>
        private void RequestAuthKey(PicturePostObject ppo)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(API_AUTH);

                string boundary = System.Guid.NewGuid().ToString();
                NetworkCredential myCred = new NetworkCredential(ppo.Username, ppo.Password);
                CredentialCache MyCrendentialCache = new CredentialCache();
                Uri uri = new Uri(API_AUTH);
                MyCrendentialCache.Add(uri, "Basic", myCred);
                request.Credentials = MyCrendentialCache;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)";
                request.Headers.Set("Pragma", "no-cache");
                request.ContentType = string.Format("multipart/form-data;boundary={0}", boundary);

                //request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "POST";
                request.Timeout = 20000;

                string header = string.Format("--{0}", boundary);
                string ender = header + "\r\n";

                StringBuilder contents = new StringBuilder();

                contents.Append(CreateContentPartStringForm(header, "data[api][username]", ppo.Username, "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][password]", ppo.Password, "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][service]", "twitter", "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][key]", API_KEY, "application/octet-stream"));

                //Create the form message to send in bytes
                byte[] message = Encoding.UTF8.GetBytes(contents.ToString());

                request.ContentLength = message.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(message, 0, message.Length);
                    requestStream.Flush();
                    requestStream.Close();

                    using (WebResponse response = request.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            XmlDocument responseXML = new XmlDocument();
                            string responseFromService = reader.ReadToEnd();
                            responseXML.LoadXml(responseFromService);
                            if (responseXML.SelectSingleNode("pikchur/error") == null)
                            {
                                XmlNode authKeyNode = responseXML.SelectSingleNode("pikchur/auth_key");
                                AUTH_KEY = authKeyNode.InnerText;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_DOWNLOAD));
            }
        }
 private void InsertPictureFromFile()
 {
     if (!uploadingPicture)
     {
         String pictureUrl = string.Empty;
         String filename = string.Empty;
         //using (Microsoft.WindowsMobile.Forms.SelectPictureDialog s = new Microsoft.WindowsMobile.Forms.SelectPictureDialog())
         try
         {
             pictureService = GetMediaService();
             using (Microsoft.WindowsMobile.Forms.SelectPictureDialog s = new Microsoft.WindowsMobile.Forms.SelectPictureDialog())
             {
                 //s.Filter = string.Empty; //all files //pictureService.FileFilter;
                 s.Filter = pictureService.FileFilter;
                 
                 if (s.ShowDialog() == DialogResult.OK)
                 {
                     filename = s.FileName;
                     ComponentResourceManager resources = new ComponentResourceManager(typeof(PostUpdate));
                     pictureFromCamers.Image = FormColors.GetThemeIcon("takepicture.png");
                     if (DetectDevice.DeviceType == DeviceType.Standard)
                     {
                         pictureFromCamers.Visible = false;
                     }
                     uploadedPictureOrigin = "file";
                 }
                 else //cancelled
                 {
                     pictureUsed = true;
                 }
             }
         }
         catch
         {
             MessageBox.Show("Unable to select picture.", "PockeTwit");
         }
         if  (string.IsNullOrEmpty(filename))
         {
             return;
         }
         try
         {
             if (pictureService.CanUploadMessage && ClientSettings.SendMessageToMediaService)
             {
                 AddPictureToForm(filename, pictureFromStorage);
                 picturePath = filename;
                 //Reduce length of message 140-pictureService.UrlLength
                 pictureUsed = true;
             }
             else
             {
                 uploadingPicture = true;
                 AddPictureToForm(FormColors.GetThemeIconPath("wait.png"), pictureFromStorage);
                 using (PicturePostObject ppo = new PicturePostObject())
                 {
                     ppo.Filename = filename;
                     ppo.Username = AccountToSet.UserName;
                     ppo.Password = AccountToSet.Password;
                     ppo.UseAsync = false;
                     Cursor.Current = Cursors.WaitCursor;
                     pictureService.PostPicture(ppo);
                 }
             }
         }
         catch
         {
             MessageBox.Show("Unable to upload picture.", "PockeTwit");
         } 
     }
     else
     {
         MessageBox.Show("Uploading picture...");
     }
 }
        public override bool PostPictureMessage(PicturePostObject postData)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return false;
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(postData.Username) ||
                string.IsNullOrEmpty(postData.Password))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return false;
            }

            #endregion

            using (System.IO.FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    //Load the picture data
                    byte[] incoming = new byte[file.Length];
                    file.Read(incoming, 0, incoming.Length);

                    postData.PictureData = incoming;
                    string uploadResult = UploadPictureMessage(API_UPLOAD_POST, postData);

                    if (string.IsNullOrEmpty(uploadResult))
                    {
                        //OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                        return false;
                    }
                    

                }
                catch (Exception e)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                    return false;
                }
            }
            return true;
        }
Exemple #11
0
 private void InsertPictureFromCamera()
 {
     if (!uploadingPicture)
     {
         String pictureUrl = string.Empty;
         String filename = string.Empty;
         try
         {
             using (Microsoft.WindowsMobile.Forms.CameraCaptureDialog c = new Microsoft.WindowsMobile.Forms.CameraCaptureDialog())
             {
                 if (c.ShowDialog() == DialogResult.OK)
                 {
                     System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PostUpdate));
                     pictureFromStorage.Image = PockeTwit.Themes.FormColors.GetThemeIcon("existingimage.png");
                     if (DetectDevice.DeviceType == DeviceType.Standard)
                     {
                         pictureFromStorage.Visible = false;
                     }
                     uploadedPictureOrigin = "camera";
                     filename = c.FileName;                            
                 }
                 else //cancelled
                 {
                     pictureUsed = true;
                 }
             }
         }
         catch
         {
             MessageBox.Show("The camera is not available.", "PockeTwit");
             return;
         }
         if (string.IsNullOrEmpty(filename))
         {
             return; //no file selected, so don't upload
         }
         try
         {
             pictureService = GetMediaService();
             if (pictureService.CanUploadMessage && ClientSettings.SendMessageToMediaService)
             {
                 AddPictureToForm(filename, pictureFromCamers);
                 picturePath = filename;
                 //Reduce length of message 140-pictureService.UrlLength
                 pictureUsed = true;
             }
             else
             {
                 AddPictureToForm(FormColors.GetThemeIconPath("wait.png"), pictureFromCamers);
                 uploadingPicture = true;
                 using (PicturePostObject ppo = new PicturePostObject())
                 {
                     ppo.Filename = filename;
                     ppo.Username = AccountToSet.UserName;
                     ppo.Password = AccountToSet.Password;
                     ppo.UseAsync = false;
                     Cursor.Current = Cursors.WaitCursor;
                     pictureService.PostPicture(ppo);
                 }
             }
         }
         catch
         {
             MessageBox.Show("Unable to upload picture.", "PockeTwit");
         }
     }
     else
     {
         MessageBox.Show("Uploading picture...");
     }
 }
Exemple #12
0
        public override void PostPicture(PicturePostObject postData)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed,string.Empty , API_ERROR_UPLOAD));
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(postData.Username) ||
                string.IsNullOrEmpty(postData.Password))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }

            #endregion

            using (FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    //Load the picture data
                    byte[] incoming = new byte[file.Length];
                    file.Read(incoming, 0, incoming.Length);

                    if (postData.UseAsync)
                    {
                        workerPPO = (PicturePostObject)postData.Clone();
                        workerPPO.PictureData = incoming;

                        if (workerThread == null)
                        {
                            workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessUpload));
                            workerThread.Name = "PictureUpload";
                            workerThread.Start();
                        }
                        else
                        {
                            OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.NotReady, string.Empty, API_ERROR_NOTREADY));
                        }
                    }
                    else
                    {
                        //use sync.
                        postData.PictureData = incoming;
                        XmlDocument uploadResult;
                        if (string.IsNullOrEmpty(postData.Message))
                        {
                            uploadResult = UploadPicture(postData);
                        }
                        else
                        {
                            uploadResult = UploadPictureAndPost(postData);
                        }

                        if (uploadResult.SelectSingleNode("pikchur/error") == null)
                        {
                            XmlNode UrlKeyNode = uploadResult.SelectSingleNode("pikchur/post/url");
                            string URL = UrlKeyNode.InnerText;
                            URL = URL.Replace("\n","");

                            OnUploadFinish(new PictureServiceEventArgs(PictureServiceErrorLevel.OK, URL, string.Empty, postData.Filename));
                        }
                        else
                        {
                            OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                        }
                    }
                }
                catch (Exception e)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// Upload picture
        /// </summary>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPictureAndPost(PicturePostObject ppo)
        {
            if (string.IsNullOrEmpty(AUTH_KEY))
            {
                RequestAuthKey(ppo);
            }
            if (string.IsNullOrEmpty(AUTH_KEY))
            {
                //Authorisation has failed.
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(API_UPLOAD);

                string boundary = Guid.NewGuid().ToString();
                request.Credentials = new NetworkCredential(ppo.Username, ppo.Password);
                request.Headers.Add("Accept-Language", "cs,en-us;q=0.7,en;q=0.3");
                request.PreAuthenticate = true;
                request.ContentType = string.Format("multipart/form-data;boundary={0}", boundary);

                //request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "POST";
                request.Timeout = 20000;
                string header = string.Format("--{0}", boundary);
                string ender = "\r\n" + header + "\r\n";

                StringBuilder contents = new StringBuilder();

                contents.Append(CreateContentPartStringForm(header, "data[api][key]", API_KEY, "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][status]", ppo.Message, "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][auth_key]", AUTH_KEY, "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][upload_only]", "FALSE", "application/octet-stream"));
                contents.Append(CreateContentPartStringForm(header, "data[api][origin]", API_ORIGIN_ID, "application/octet-stream"));

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    contents.Append(CreateContentPartStringForm(header, "data[api][geo][lat]", ppo.Lat, "application/octet-stream"));
                    contents.Append(CreateContentPartStringForm(header, "data[api][geo][lon]", ppo.Lon, "application/octet-stream"));
                }
                //image
                contents.Append(CreateContentPartPicture(header, "dataAPIimage", "image.jpg"));

                //Create the form message to send in bytes
                byte[] message = Encoding.UTF8.GetBytes(contents.ToString());
                byte[] footer = Encoding.UTF8.GetBytes(ender);
                request.ContentLength = message.Length + ppo.PictureData.Length + footer.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(message, 0, message.Length);
                    requestStream.Write(ppo.PictureData, 0, ppo.PictureData.Length);
                    requestStream.Write(footer, 0, footer.Length);
                    requestStream.Flush();
                    requestStream.Close();

                    using (WebResponse response = request.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            XmlDocument responseXML = new XmlDocument();
                            string responseFromService = reader.ReadToEnd();
                            responseXML.LoadXml(responseFromService);
                            return responseXML;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //Socket exception 10054 could occur when sending large files.
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
 /// <summary>
 /// PostPicture method that must be overridden.
 /// </summary>
 /// <param name="postData">Data to post</param>
 public abstract void PostPicture(PicturePostObject postData);
        /// <summary>
        /// Start posting a picture
        /// </summary>
        /// <param name="postData"></param>
        public override void PostPicture(PicturePostObject postData)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(postData.Username) ||
                string.IsNullOrEmpty(postData.Password))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
            }

            #endregion

            using (System.IO.FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    //Load the picture data
                    byte[] incoming = new byte[file.Length];
                    file.Read(incoming, 0, incoming.Length);

                    if (postData.UseAsync)
                    {
                        workerPPO = (PicturePostObject)postData.Clone();
                        workerPPO.PictureData = incoming;

                        if (workerThread == null)
                        {
                            workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(ProcessUpload));
                            workerThread.Name = "PictureUpload";
                            workerThread.Start();
                        }
                        else
                        {
                            OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.NotReady, string.Empty, "A request is already running."));
                        }
                    }
                    else
                    {
                        //use sync.
                        postData.PictureData = incoming;
                        string uploadResult = UploadPicture(API_UPLOAD, postData);

                        if (!string.IsNullOrEmpty(uploadResult))
                        {
                            OnUploadFinish(new PictureServiceEventArgs(PictureServiceErrorLevel.OK, uploadResult, string.Empty, postData.Filename));
                        }

                    }
                }
                catch (Exception e)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                }
            }
        }
 /// <summary>
 /// Send a picture to a twitter picture framework without the use of the finish event
 /// </summary>
 /// <param name="postData">Postdata</param>
 /// <returns>Returned URL from server</returns>
 public abstract bool PostPictureMessage(PicturePostObject postData);
Exemple #17
0
        /// <summary>
        /// Send a picture to a twitter picture framework without the use of the finish event
        /// </summary>
        /// <param name="postData">Postdata</param>
        /// <returns>Returned URL from server</returns>
        public override bool PostPictureMessage(PicturePostObject postData)
        {
            #region Argument check

            //Check for empty path
            if (string.IsNullOrEmpty(postData.Filename))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty , API_ERROR_UPLOAD));
                return false;
            }

            //Check for empty credentials
            if (string.IsNullOrEmpty(postData.Username) ||
                string.IsNullOrEmpty(postData.Password))
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed,string.Empty , API_ERROR_UPLOAD));
                return false;
            }

            #endregion

            using (FileStream file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    //Load the picture data
                    byte[] incoming = new byte[file.Length];
                    file.Read(incoming, 0, incoming.Length);

                    //use sync.
                    postData.PictureData = incoming;
                    XmlDocument uploadResult = UploadPictureAndPost(postData);

                    if (uploadResult.SelectSingleNode("pikchur/error") == null)
                    {
                        XmlNode UrlKeyNode = uploadResult.SelectSingleNode("pikchur/post/url");
                        string URL = UrlKeyNode.InnerText;
                        URL = URL.Replace("\n", "");
                    }
                    else
                    {
                        OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                    }
                }
                catch (Exception e)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                    return false;
                }
            }
            return true;
        }