public void TestMediaService() { var service = PictureServiceFactory.Instance.GetServiceByName("TweetPhoto"); string testFile = (ClientSettings.AppPath + "\\testcode\\desert.jpg").Substring(6); var ppo = new PicturePostObject { Filename = testFile, Message = "Test upload", Username = "******", //REPLACE WITH YOUR OWN TEST ACCOUNT INFO Password = "******" }; Assert.IsTrue(service.PostPictureMessage(ppo)); }
/// <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, 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 (var file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read)) { try { //Load the picture data var 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(ProcessUpload){Name = "PictureUpload"}; _workerThread.Start(); } else { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.NotReady, string.Empty, "A request is already running.")); } } else { //use sync. postData.PictureData = incoming; XmlDocument uploadResult = UploadPictureMessage(API_UPLOAD, postData); if (uploadResult == null) { return; } var nm = new XmlNamespaceManager(uploadResult.NameTable); nm.AddNamespace("tweetPhoto", "http://tweetphotoapi.com"); if (uploadResult.SelectSingleNode("//tweetPhoto:Status",nm).InnerText!= "OK") { 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 { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD)); } } }
/// <summary> /// Upload the picture /// </summary> /// <param name="url">URL to upload picture to</param> /// <param name="ppo">Postdata</param> /// <returns></returns> /// <summary> /// Upload the picture /// </summary> /// <param name="url">URL to upload picture to</param> /// <param name="ppo">Postdata</param> /// <returns></returns> private XmlDocument UploadPictureMessage(string url, PicturePostObject ppo) { try { HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url); request.ContentType = string.Format("application/x-www-form-urlencoded"); request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String( Encoding.Default.GetBytes( String.Format("{0}:{1}", ppo.Username, ppo.Password) ) ))); request.Method = "POST"; request.Headers.Add("TPUTF8", Boolean.TrueString); if (!string.IsNullOrEmpty(ppo.Message)) { request.Headers.Add("TPMSG", GetUTF8EncodedHeaderString(ppo.Message)); } request.Headers.Add("TPAPIKEY", API_KEY); request.Headers.Add("TPMIMETYPE", "image/"+Path.GetExtension(ppo.Filename).ToLower().Substring(1)); request.Headers.Add("TPPOST", (!string.IsNullOrEmpty(ppo.Message)).ToString()); if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon)) { request.Headers.Add("longitude", ppo.Lon); request.Headers.Add("latitude", ppo.Lat); } //Create the form message to send in bytes //byte[] message = Encoding.UTF8.GetBytes(ppo.PictureData); request.ContentLength = ppo.PictureData.Length; request.Timeout = 1000 * 60 * 3; //3 minute time out using (Stream requestStream = request.GetRequestStream()) { const int len = 1024 * 64; for (int i = 0; i < ppo.PictureData.Length; i += len) { int writeLen = len; if ((i + len) > ppo.PictureData.Length) { writeLen = ppo.PictureData.Length - i; } requestStream.Write(ppo.PictureData, i, writeLen); } requestStream.Flush(); requestStream.Close(); using (WebResponse response = request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { var responseXML = new XmlDocument(); string rsp = reader.ReadToEnd(); responseXML.LoadXml(rsp); return responseXML; } } } } catch (Exception ex) { //Socket exception 10054 could occur when sending large files. OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, ex.Message, API_ERROR_UPLOAD)); return null; } }
/// <summary> /// Post a picture including a message to the media service. /// </summary> /// <param name="postData"></param> /// <returns></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 (var file = new FileStream(postData.Filename, FileMode.Open, FileAccess.Read)) { try { //Load the picture data var 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; } var nm = new XmlNamespaceManager(uploadResult.NameTable); nm.AddNamespace("tweetPhoto", "http://tweetphotoapi.com"); if (uploadResult.SelectSingleNode("//tweetPhoto:Status",nm).InnerText!= "OK") { string errorText = uploadResult.SelectSingleNode("//err").Attributes["msg"].Value; OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, errorText)); return false; } } catch { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD)); return false; } } return true; }
/// <summary> /// Fetch a picture /// </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, "", API_ERROR_DOWNLOAD)); } #endregion try { _workerPpo = new PicturePostObject {Message = pictureURL}; if (_workerThread == null) { _workerThread = new System.Threading.Thread(ProcessDownload){Name = "PictureUpload"}; _workerThread.Start(); } else { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.NotReady, "", "A request is already running.")); } } catch { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_DOWNLOAD)); } }
/// <summary> /// Post a picture including a message to the media service. /// </summary> /// <param name="postData"></param> /// <returns></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 (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) { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty,API_ERROR_UPLOAD)); return false; } } return true; }
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) { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD)); return false; } } return true; }
/// <summary> /// Upload picture /// </summary> /// <param name="ppo"></param> /// <returns></returns> private XmlDocument UploadPictureAndPost(PicturePostObject ppo) { try { HttpWebRequest request = WebRequestFactory.CreateHttpRequest(API_UPLOAD2); string boundary = Guid.NewGuid().ToString(); request.AllowWriteStreamBuffering = true; //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; charset=iso-8859-1; boundary={0}", boundary); request.TransferEncoding = "binary"; //request.Headers.Add("Action", "uploadAndPost"); //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(CreateContentPartString(header, "action", "uploadAndPost")); int imageIdStartIndex = ppo.Filename.LastIndexOf('\\') + 1; string filename = ppo.Filename.Substring(imageIdStartIndex, ppo.Filename.Length - imageIdStartIndex); contents.Append(CreateContentPartPicture(header, filename)); //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 { //Socket exception 10054 could occur when sending large files. OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD)); return null; } }
/// <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 = WebRequestFactory.CreateHttpRequest(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(CreateContentPartString(header, "source", "PockeTwit")); if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon)) { //string geotag = string.Format("geotagged,geo:lat={0},geo:lon={1}", ppo.Lat, ppo.Lon); string geotag = string.Format("geotagged,geo:lat={0},geo:lon={1}", ppo.Lat, ppo.Lon); contents.Append(CreateContentPartString(header, "tags", geotag)); } if (!string.IsNullOrEmpty(ppo.Message)) { contents.Append(CreateContentPartString(header, "message", ppo.Message)); } int imageIdStartIndex = ppo.Filename.LastIndexOf('\\') + 1; string filename = ppo.Filename.Substring(imageIdStartIndex, ppo.Filename.Length - imageIdStartIndex); contents.Append(CreateContentPartPicture(header, filename)); //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) { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_DOWNLOAD)); return null; } }
/// <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, "", "Failed to download picture from yFrog.")); } #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, "", "A request is already running.")); } } catch (Exception) { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", "Failed to download picture from yFrog.")); } }
public override void PostPicture(PicturePostObject postData) { throw new NotImplementedException(); }
/// <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);
/// <summary> /// PostPicture method that must be overridden. /// </summary> /// <param name="postData">Data to post</param> public abstract void PostPicture(PicturePostObject postData);
/// <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 = WebRequestFactory.CreateHttpRequest(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) )); } string hashTags = FindHashTags(ppo.Message, ",", 32); if (!string.IsNullOrEmpty(hashTags)) { contents.Append(CreateContentPartString(header, "ht", hashTags)); } int imageIdStartIndex = ppo.Filename.LastIndexOf('\\') + 1; string filename = ppo.Filename.Substring(imageIdStartIndex, ppo.Filename.Length - imageIdStartIndex); contents.Append(CreateContentPartMedia(header, filename)); //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; } } } } catch (Exception) { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD)); return string.Empty; } }
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_UPLOAD)); } #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, API_ERROR_NOTREADY)); } } catch (Exception) { 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 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 == null) { //event allready thrown in upload return false; } if (uploadResult.SelectSingleNode("rsp").Attributes["staust"].Value != "fail") { XmlNode UrlKeyNode = uploadResult.SelectSingleNode("rsp/picture_url"); string URL = UrlKeyNode.InnerText; URL = URL.Replace("\n", ""); } else { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD)); return false; } } catch (Exception) { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD)); return false; } } return true; }
private bool DoUpload(IPictureService Service, UploadAttachment a) { PicturePostObject ppo = new PicturePostObject(); if(a.MediaType != null) ppo.ContentType = a.MediaType.ContentType; if (a.Position != null) { ppo.Lat = a.Position.Lat.ToString(System.Globalization.CultureInfo.InvariantCulture); ppo.Lon = a.Position.Lat.ToString(System.Globalization.CultureInfo.InvariantCulture); } ppo.Message = a.Caption; //ppo.PictureStream = a.Contents; ppo.Filename = a.Name; ppo.UseAsync = false; // This is only temporary -> PostUpdate form has event handlers reg'd a.Status = UploadAttachment.AttachmentStatus.Uploading; Service.PostPicture(ppo, Account); if (!string.IsNullOrEmpty(ppo.URL)) { a.UploadedUri = new Uri(ppo.URL); a.Status = UploadAttachment.AttachmentStatus.Complete; } else { a.Status = UploadAttachment.AttachmentStatus.Error; } return true; }
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 = UploadPicture(postData); if (uploadResult == null) { return; } if (uploadResult.SelectSingleNode("rsp").Attributes["status"].Value != "fail") { XmlNode UrlKeyNode = uploadResult.SelectSingleNode("rsp/mediaurl"); 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) { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD)); } } }
/// <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) { OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD)); } } }