private async Task ParseMediaEntry(string mediaEntryString, PicasaPostImage postImage)
        {
            postImage.srcUrl = null;

            // First try <content src>
            var xmlDoc = new Windows.Data.Xml.Dom.XmlDocument();

            xmlDoc.LoadXml(mediaEntryString);
            var contentEl = xmlDoc.SelectSingleNodeNS("/atom:entry/atom:content", _nsMgr.ToNSMethodFormat());

            if (contentEl != null)
            {
                postImage.srcUrl = XmlHelper.GetUrl(contentEl, "@src", _nsMgr, null);
            }

            // Then try media RSS
            if (postImage.srcUrl == null || postImage.srcUrl.Length == 0)
            {
                contentEl = xmlDoc.SelectSingleNodeNS("/atom:entry/media:group/media:content[@medium='image']", _nsMgr.ToNSMethodFormat());
                if (contentEl == null)
                {
                    throw new ArgumentException("Picasa photo entry was missing content element");
                }
                postImage.srcUrl = XmlHelper.GetUrl(contentEl, "@url", _nsMgr, null);
            }

            postImage.editUri = AtomEntry.GetLink(xmlDoc.SelectSingleNodeNS("/atom:entry", _nsMgr.ToNSMethodFormat()), _nsMgr, "edit-media", null, null, null);
        }
        private async Task UpdateImage(string editUri, Stream fileStream, string filename, PicasaPostImage postImage)
        {
            for (int retry = 0; retry < MaxRetries; retry++)
            {
                var transientCredentials = await Login();

                HttpResponseMessage response;
                bool conflict = false;
                try
                {
                    response = await RedirectHelper.GetResponse(editUri, new RedirectHelper.RequestFactory(new UploadFileRequestFactory(this, fileStream, filename, "PUT").Create));

                    if (!response.IsSuccessStatusCode)
                    {
                        if (retry < MaxRetries - 1)
                        {
                            if (response.StatusCode == Windows.Web.Http.HttpStatusCode.Conflict)
                            {
                                //response = we.Response;
                                conflict = true;
                            }
                            else if (response.StatusCode == Windows.Web.Http.HttpStatusCode.Forbidden)
                            {
                                // HTTP 403 Forbidden means our OAuth access token is not valid.
                                await RefreshAccessToken(transientCredentials);

                                continue;
                            }
                        }
                    }
                }
                catch (WebException we)
                {
                    if (retry < MaxRetries - 1 &&
                        we.Response as HttpWebResponse != null)
                    {
                        if (((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Conflict)
                        {
                            //response = we.Response;
                            conflict = true;
                        }
                        else if (((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Forbidden)
                        {
                            // HTTP 403 Forbidden means our OAuth access token is not valid.
                            await RefreshAccessToken(transientCredentials);

                            continue;
                        }
                    }

                    throw;
                }

                var mediaEntry = await response.Content.ReadAsStringAsync();

                {
                    await ParseMediaEntry(mediaEntry, postImage);
                }

                if (!conflict)
                {
                    return; // success!
                }
            }

            Debug.Fail("Should never get here");
            throw new Exception("Should never get here");
        }
        private async Task PostNewImage(string albumName, Stream fileStream, string filename, PicasaPostImage postImage)
        {
            for (int retry = 0; retry < MaxRetries; retry++)
            {
                var transientCredentials = await Login();

                try
                {
                    string albumUrl = await GetBlogImagesAlbum(albumName);

                    var response = await RedirectHelper.GetResponse(albumUrl, new UploadFileRequestFactory(this, fileStream, filename, "POST").Create);

                    if (!response.IsSuccessStatusCode)
                    {
                        if (retry < MaxRetries - 1 &&
                            response.StatusCode == Windows.Web.Http.HttpStatusCode.Forbidden)
                        {
                            // HTTP 403 Forbidden means our OAuth access token is not valid.
                            await RefreshAccessToken(transientCredentials);

                            continue;
                        }
                    }

                    var mediaEntry = await response.Content.ReadAsStringAsync();

                    await ParseMediaEntry(mediaEntry, postImage);

                    return;
                }
                catch (WebException we)
                {
                    if (retry < MaxRetries - 1 &&
                        we.Response as HttpWebResponse != null &&
                        ((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Forbidden)
                    {
                        // HTTP 403 Forbidden means our OAuth access token is not valid.
                        await RefreshAccessToken(transientCredentials);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            Debug.Fail("Should never get here");
            throw new Exception("Should never get here");
        }
        public async Task <string> DoBeforePublishUploadWork(IFileUploadContext uploadContext)
        {
            string albumName = ApplicationEnvironment.ProductName;

            string fileName   = uploadContext.PreferredFileName;
            var    fileStream = uploadContext.GetContents();

            if (Options.FileUploadNameFormat != null && Options.FileUploadNameFormat.Length > 0)
            {
                string   formattedFileName = uploadContext.FormatFileName(uploadContext.PreferredFileName);
                string[] chunks            = StringHelper.Reverse(formattedFileName).Split(new char[] { '/' }, 2);
                if (chunks.Length == 2)
                {
                    albumName = StringHelper.Reverse(chunks[1]);
                }
            }

            string EDIT_MEDIA_LINK = "EditMediaLink";

            var postImage = new PicasaPostImage();

            //postImage.editUri = uploadContext.Settings.GetString(EDIT_MEDIA_LINK, null);

            if (postImage.editUri == null || postImage.editUri.Length == 0)
            {
                await PostNewImage(albumName, fileStream, fileName, postImage);
            }
            else
            {
                try
                {
                    await UpdateImage(postImage.editUri, fileStream, fileName, postImage);
                }
                catch (Exception e)
                {
                    Debug.Fail(e.ToString());
                    if (e is WebException)
                    {
                        HttpRequestHelper.LogException((WebException)e);
                    }

                    bool success = false;
                    postImage.srcUrl = null; // compiler complains without this line
                    try
                    {
                        // couldn't update existing image? try posting a new one
                        await PostNewImage(albumName, fileStream, fileName, postImage);

                        success = true;
                    }
                    catch
                    {
                    }
                    if (!success)
                    {
                        throw;  // rethrow the exception from the update, not the post
                    }
                }
            }
            //uploadContext.Settings.SetString(EDIT_MEDIA_LINK, postImage.editUri);

            postImage.srcUrl = await PicasaRefererBlockingWorkaround(uploadContext.BlogId, uploadContext.Role, postImage.srcUrl);

            return(postImage.srcUrl);
        }