private static async Task <XmlDocument> SimpleRequest(string method, HttpAsyncRequestFilter filter, XmlRequestResult result, params string[] parameters)
        {
            string absUri = UrlHelper.SafeToAbsoluteUri(result.uri);

            if (parameters.Length > 0)
            {
                FormData formData = new FormData(true, parameters);

                if (absUri.IndexOf('?') == -1)
                {
                    absUri += "?" + formData.ToString();
                }
                else
                {
                    absUri += "&" + formData.ToString();
                }
            }

            RedirectHelper.SimpleRequest simpleRequest = new RedirectHelper.SimpleRequest(method, filter);
            var response = await RedirectHelper.GetResponse(absUri, new RedirectHelper.RequestFactory(simpleRequest.Create));

            try
            {
                result.uri             = response.RequestMessage.RequestUri;
                result.responseHeaders = response.Headers;
                return(await ParseXmlResponse(response));
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                }
            }
        }
Пример #2
0
 /// <param name="uri"></param>
 /// <param name="methods">An array of HTTP methods that should be tried until one of them does not return 405.</param>
 private static string GetEtagImpl(string uri, HttpRequestFilter requestFilter, params string[] methods)
 {
     try
     {
         HttpWebResponse response = RedirectHelper.GetResponse(uri,
                                                               new RedirectHelper.RequestFactory(new RedirectHelper.SimpleRequest(methods[0], requestFilter).Create));
         try
         {
             return(FilterWeakEtag(response.Headers["ETag"]));
         }
         finally
         {
             response.Close();
         }
     }
     catch (WebException we)
     {
         if (methods.Length > 1 && we.Status == WebExceptionStatus.ProtocolError)
         {
             HttpWebResponse resp = we.Response as HttpWebResponse;
             if (resp != null && (resp.StatusCode == HttpStatusCode.MethodNotAllowed || resp.StatusCode == HttpStatusCode.NotImplemented))
             {
                 string[] newMethods = new string[methods.Length - 1];
                 Array.Copy(methods, 1, newMethods, 0, newMethods.Length);
                 return(GetEtagImpl(uri, requestFilter, newMethods));
             }
         }
         throw;
     }
 }
Пример #3
0
        private void PostNewImage(string albumName, string filename, out string srcUrl, out string editUri)
        {
            for (int retry = 0; retry < MaxRetries; retry++)
            {
                var transientCredentials = Login();
                try
                {
                    string          albumUrl = GetBlogImagesAlbum(albumName);
                    HttpWebResponse response = RedirectHelper.GetResponse(albumUrl, new RedirectHelper.RequestFactory(new UploadFileRequestFactory(this, filename, "POST").Create));
                    using (Stream s = response.GetResponseStream())
                    {
                        ParseMediaEntry(s, out srcUrl, out editUri);
                        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.
                        RefreshAccessToken(transientCredentials);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            Trace.Fail("Should never get here");
            throw new ApplicationException("Should never get here");
        }
Пример #4
0
        public async Task DeletePost(string blogId, string postId, bool publish)
        {
            await Login();

            FixupBlogId(ref blogId);
            Uri editUri = PostIdToPostUri(postId);

            try
            {
                RedirectHelper.SimpleRequest sr = new RedirectHelper.SimpleRequest("DELETE", new HttpAsyncRequestFilter(DeleteRequestFilter));
                var response = await RedirectHelper.GetResponse(UrlHelper.SafeToAbsoluteUri(editUri), new RedirectHelper.RequestFactory(sr.Create));

                if (!response.IsSuccessStatusCode)
                {
                    if (response.StatusCode != Windows.Web.Http.HttpStatusCode.NotFound && response.StatusCode !=
                        Windows.Web.Http.HttpStatusCode.Gone)
                    {
                        throw new Exception();
                    }
                    {
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                if (!AttemptDeletePostRecover(e, blogId, UrlHelper.SafeToAbsoluteUri(editUri), publish))
                {
                    throw;
                }
            }
        }
Пример #5
0
        private static XmlDocument SimpleRequest(string method, ref Uri uri, HttpRequestFilter filter, out WebHeaderCollection responseHeaders, params string[] parameters)
        {
            string absUri = UrlHelper.SafeToAbsoluteUri(uri);

            if (parameters.Length > 0)
            {
                FormData formData = new FormData(true, parameters);

                if (absUri.IndexOf('?') == -1)
                {
                    absUri += "?" + formData.ToString();
                }
                else
                {
                    absUri += "&" + formData.ToString();
                }
            }

            RedirectHelper.SimpleRequest simpleRequest = new RedirectHelper.SimpleRequest(method, filter);
            HttpWebResponse response = RedirectHelper.GetResponse(absUri, new RedirectHelper.RequestFactory(simpleRequest.Create));

            try
            {
                uri             = response.ResponseUri;
                responseHeaders = response.Headers;
                return(ParseXmlResponse(response));
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
Пример #6
0
        public void DeletePost(string blogId, string postId, bool publish)
        {
            Login();

            FixupBlogId(ref blogId);
            Uri editUri = PostIdToPostUri(postId);

            try
            {
                RedirectHelper.SimpleRequest sr = new RedirectHelper.SimpleRequest("DELETE", new HttpRequestFilter(DeleteRequestFilter));
                HttpWebResponse response        = RedirectHelper.GetResponse(UrlHelper.SafeToAbsoluteUri(editUri), new RedirectHelper.RequestFactory(sr.Create));
                response.Close();
            }
            catch (Exception e)
            {
                if (e is WebException)
                {
                    WebException we = (WebException)e;
                    if (we.Response != null && we.Response is HttpWebResponse)
                    {
                        switch (((HttpWebResponse)we.Response).StatusCode)
                        {
                        case HttpStatusCode.NotFound:
                        case HttpStatusCode.Gone:
                            return;     // these are acceptable responses to a DELETE
                        }
                    }
                }

                if (!AttemptDeletePostRecover(e, blogId, UrlHelper.SafeToAbsoluteUri(editUri), publish))
                {
                    throw;
                }
            }
        }
Пример #7
0
        private void PostNewImage(string albumName, string filename, out string srcUrl, out string editUri)
        {
            TransientCredentials transientCredentials = Credentials.TransientCredentials as TransientCredentials;

            GDataCredentials.FromCredentials(transientCredentials).EnsureLoggedIn(transientCredentials.Username, transientCredentials.Password, GDataCredentials.PICASAWEB_SERVICE_NAME, false);

            string          albumUrl = GetBlogImagesAlbum(albumName);
            HttpWebResponse response = RedirectHelper.GetResponse(albumUrl, new RedirectHelper.RequestFactory(new UploadFileRequestFactory(this, filename, "POST").Create));

            using (Stream s = response.GetResponseStream())
                ParseMediaEntry(s, out srcUrl, out editUri);
        }
        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");
        }
Пример #9
0
        private void UpdateImage(string editUri, string filename, out string srcUrl, out string newEditUri)
        {
            for (int retry = 0; retry < MaxRetries; retry++)
            {
                var             transientCredentials = Login();
                HttpWebResponse response;
                bool            conflict = false;
                try
                {
                    response = RedirectHelper.GetResponse(editUri, new RedirectHelper.RequestFactory(new UploadFileRequestFactory(this, filename, "PUT").Create));
                }
                catch (WebException we)
                {
                    if (retry < MaxRetries - 1 &&
                        we.Response as HttpWebResponse != null)
                    {
                        if (((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Conflict)
                        {
                            response = (HttpWebResponse)we.Response;
                            conflict = true;
                        }
                        else if (((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Forbidden)
                        {
                            // HTTP 403 Forbidden means our OAuth access token is not valid.
                            RefreshAccessToken(transientCredentials);
                            continue;
                        }
                    }

                    throw;
                }

                using (Stream s = response.GetResponseStream())
                {
                    ParseMediaEntry(s, out srcUrl, out newEditUri);
                }

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

                editUri = newEditUri;
            }

            Trace.Fail("Should never get here");
            throw new ApplicationException("Should never get here");
        }
        public virtual void PostNewImage(string path, bool allowWriteStreamBuffering, out string srcUrl, out string editMediaUri, out string editEntryUri)
        {
            string mediaCollectionUri = _collectionUri;

            if (mediaCollectionUri == null || mediaCollectionUri == "")
            {
                throw new BlogClientFileUploadNotSupportedException();
            }

            HttpWebResponse response = null;

            try
            {
                response = RedirectHelper.GetResponse(mediaCollectionUri,
                                                      new RedirectHelper.RequestFactory(new ImageUploadHelper(this, path, "POST", null, allowWriteStreamBuffering).Create));

                string      entryUri;
                string      etag;
                string      selfPage;
                XmlDocument xmlDoc = GetCreatedEntity(response, out entryUri, out etag);
                ParseResponse(xmlDoc, out srcUrl, out editMediaUri, out editEntryUri, out selfPage);
            }
            catch (WebException we)
            {
                // The error may have been due to the server requiring stream buffering (WinLive 114314, 252175)
                // Try again with stream buffering.
                if (we.Status == WebExceptionStatus.ProtocolError && !allowWriteStreamBuffering)
                {
                    PostNewImage(path, true, out srcUrl, out editMediaUri, out editEntryUri);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
        public virtual async Task PostNewImage(string path, bool allowWriteStreamBuffering, PostNewImageResult result)
        {
            string mediaCollectionUri = _collectionUri;

            if (mediaCollectionUri == null || mediaCollectionUri == "")
            {
                throw new BlogClientFileUploadNotSupportedException();
            }

            HttpResponseMessage response = null;

            try
            {
                response = await RedirectHelper.GetResponse(mediaCollectionUri,
                                                            new RedirectHelper.RequestFactory(new ImageUploadHelper(this, path, "POST", null, allowWriteStreamBuffering).Create));

                string      selfPage = string.Empty;
                XmlDocument xmlDoc   = await GetCreatedEntity(response, result);

                result.selfPage = selfPage;
                ParseResponse(xmlDoc, result);
            }
            catch (WebException we)
            {
                // The error may have been due to the server requiring stream buffering (WinLive 114314, 252175)
                // Try again with stream buffering.
                if (we.Status == WebExceptionStatus.ProtocolError && !allowWriteStreamBuffering)
                {
                    await PostNewImage(path, true, result);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                //if (response != null)
                //response.Close();
            }
        }
        protected virtual async Task <XmlDocument> Send(string method, string etag, HttpAsyncRequestFilter filter, string contentType, XmlDocument doc, string encoding, string filename, bool ignoreResponse, XmlRequestResult result)
        {
            if (!String.IsNullOrEmpty(filename))
            {
                return(MultipartSend(method, etag, filter, contentType, doc, encoding, filename, ignoreResponse,
                                     result));
            }

            string absUri = UrlHelper.SafeToAbsoluteUri(result.uri);

            Debug.WriteLine("XML Request to " + absUri + ":\r\n" + doc.GetXml());

            SendFactory sf       = new SendFactory(etag, method, filter, contentType, doc, encoding);
            var         response = await RedirectHelper.GetResponse(absUri, new RedirectHelper.RequestFactory(sf.Create));

            try
            {
                result.responseHeaders = response.Headers;
                result.uri             = response.RequestMessage.RequestUri;
                if (ignoreResponse || response.StatusCode == Windows.Web.Http.HttpStatusCode.NoContent)
                {
                    return(null);
                }
                else
                {
                    XmlDocument xmlDocResponse = await ParseXmlResponse(response);

                    return(xmlDocResponse);
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                }
            }
        }
Пример #13
0
        protected virtual XmlDocument Send(string method, ref Uri uri, string etag, HttpRequestFilter filter, string contentType, XmlDocument doc, string encoding, string filename, bool ignoreResponse, out WebHeaderCollection responseHeaders)
        {
            if (!String.IsNullOrEmpty(filename))
            {
                return(MultipartSend(method, ref uri, etag, filter, contentType, doc, encoding, filename, ignoreResponse,
                                     out responseHeaders));
            }

            string absUri = UrlHelper.SafeToAbsoluteUri(uri);

            Debug.WriteLine("XML Request to " + absUri + ":\r\n" + doc.InnerXml);

            SendFactory     sf       = new SendFactory(etag, method, filter, contentType, doc, encoding);
            HttpWebResponse response = RedirectHelper.GetResponse(absUri, new RedirectHelper.RequestFactory(sf.Create));

            try
            {
                responseHeaders = response.Headers;
                uri             = response.ResponseUri;
                if (ignoreResponse || response.StatusCode == HttpStatusCode.NoContent)
                {
                    return(null);
                }
                else
                {
                    XmlDocument xmlDocResponse = ParseXmlResponse(response);
                    return(xmlDocResponse);
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
Пример #14
0
        private void UpdateImage(string editUri, string filename, out string srcUrl, out string newEditUri)
        {
            for (int retry = 5; retry > 0; retry--)
            {
                HttpWebResponse response;
                bool            conflict = false;
                try
                {
                    response = RedirectHelper.GetResponse(editUri, new RedirectHelper.RequestFactory(new UploadFileRequestFactory(this, filename, "PUT").Create));
                }
                catch (WebException we)
                {
                    if (retry > 1 &&
                        we.Response as HttpWebResponse != null &&
                        ((HttpWebResponse)we.Response).StatusCode == HttpStatusCode.Conflict)
                    {
                        response = (HttpWebResponse)we.Response;
                        conflict = true;
                    }
                    else
                    {
                        throw;
                    }
                }
                using (Stream s = response.GetResponseStream())
                    ParseMediaEntry(s, out srcUrl, out newEditUri);
                if (!conflict)
                {
                    return; // success!
                }
                editUri = newEditUri;
            }

            Trace.Fail("Should never get here");
            throw new ApplicationException("Should never get here");
        }
Пример #15
0
        public void EnsureLoggedIn(string username, string password, string service, bool showUi, string uri)
        {
            try
            {
                if (IsValid(username, password, service))
                {
                    return;
                }

                string captchaToken = null;
                string captchaValue = null;

                string source = string.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2}", ApplicationEnvironment.CompanyName, ApplicationEnvironment.ProductName, ApplicationEnvironment.ProductVersion);

                while (true)
                {
                    GoogleLoginRequestFactory glrf = new GoogleLoginRequestFactory(username,
                                                                                   password,
                                                                                   service,
                                                                                   source,
                                                                                   captchaToken,
                                                                                   captchaValue);
                    if (captchaToken != null && captchaValue != null)
                    {
                        captchaToken = null;
                        captchaValue = null;
                    }

                    HttpWebResponse response;
                    try
                    {
                        response = RedirectHelper.GetResponse(uri, new RedirectHelper.RequestFactory(glrf.Create));
                    }
                    catch (WebException we)
                    {
                        response = (HttpWebResponse)we.Response;
                        if (response == null)
                        {
                            Trace.Fail(we.ToString());
                            if (showUi)
                            {
                                showUi = false;
                                ShowError(MessageId.WeblogConnectionError, we.Message);
                            }
                            throw;
                        }
                    }

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Hashtable ht = ParseAuthResponse(response.GetResponseStream());
                        if (ht.ContainsKey("Auth"))
                        {
                            _auths[new AuthKey(username, password, service)] = new AuthValue((string)ht["Auth"], ht["YouTubeUser"] as string);
                            return;
                        }
                        else
                        {
                            if (showUi)
                            {
                                showUi = false;
                                ShowError(MessageId.GoogleAuthTokenNotFound);
                            }
                            throw new BlogClientInvalidServerResponseException(uri, "No Auth token was present in the response.", string.Empty);
                        }
                    }
                    else if (response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        // login failed

                        Hashtable ht    = ParseAuthResponse(response.GetResponseStream());
                        string    error = ht["Error"] as string;
                        if (error != null && error == "CaptchaRequired")
                        {
                            captchaToken = (string)ht["CaptchaToken"];
                            string captchaUrl = (string)ht["CaptchaUrl"];

                            GDataCaptchaHelper helper = new GDataCaptchaHelper(
                                new Win32WindowImpl(BlogClientUIContext.ContextForCurrentThread.Handle),
                                captchaUrl);

                            BlogClientUIContext.ContextForCurrentThread.Invoke(new ThreadStart(helper.ShowCaptcha), null);

                            if (helper.DialogResult == DialogResult.OK)
                            {
                                captchaValue = helper.Reply;
                                continue;
                            }
                            else
                            {
                                throw new BlogClientOperationCancelledException();
                            }
                        }

                        if (showUi)
                        {
                            if (error == "NoLinkedYouTubeAccount")
                            {
                                if (DisplayMessage.Show(MessageId.YouTubeSignup, username) == DialogResult.Yes)
                                {
                                    ShellHelper.LaunchUrl(GLink.Instance.YouTubeRegister);
                                }
                                return;
                            }

                            showUi = false;

                            if (error == "BadAuthentication")
                            {
                                ShowError(MessageId.LoginFailed, ApplicationEnvironment.ProductNameQualified);
                            }
                            else
                            {
                                ShowError(MessageId.BloggerError, TranslateError(error));
                            }
                        }
                        throw new BlogClientAuthenticationException(error, TranslateError(error));
                    }
                    else
                    {
                        if (showUi)
                        {
                            showUi = false;
                            ShowError(MessageId.BloggerError, response.StatusCode + ": " + response.StatusDescription);
                        }
                        throw new BlogClientAuthenticationException(response.StatusCode + "", response.StatusDescription);
                    }
                }
            }
            catch (BlogClientOperationCancelledException)
            {
                throw;
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.ToString());
                if (showUi)
                {
                    ShowError(MessageId.UnexpectedErrorLogin, e.Message);
                }
                throw;
            }
        }
        protected virtual async Task UpdateImage(bool allowWriteStreamBuffering, string editMediaUri, string path, string editEntryUri, string etag, bool getEditInfo, PostNewImageResult result)
        {
            HttpResponseMessage response = null;

            try
            {
                response = await RedirectHelper.GetResponse(editMediaUri,
                                                            new RedirectHelper.RequestFactory(new ImageUploadHelper(this, path, "PUT", etag, allowWriteStreamBuffering).Create));
            }
            catch (WebException we)
            {
                bool recovered = false;

                if (we.Status == WebExceptionStatus.ProtocolError && we.Response != null)
                {
                    HttpWebResponse errResponse = we.Response as HttpWebResponse;
                    if (errResponse != null && errResponse.StatusCode == HttpStatusCode.PreconditionFailed)
                    {
                        string newEtag = await AtomClient.GetEtag(editMediaUri, _requestFilter);

                        if (newEtag != null && newEtag.Length > 0 && newEtag != etag)
                        {
                            if (!AtomClient.ConfirmOverwrite())
                            {
                                throw new BlogClientOperationCancelledException();
                            }

                            try
                            {
                                response = await RedirectHelper.GetResponse(editMediaUri,
                                                                            new RedirectHelper.RequestFactory(new ImageUploadHelper(this, path, "PUT", newEtag, allowWriteStreamBuffering).Create));
                            }
                            finally
                            {
                                if (response != null)
                                {
                                    response.Dispose();
                                }
                            }

                            recovered = true;
                        }
                    }
                    else if (!allowWriteStreamBuffering)
                    {
                        // The error may have been due to the server requiring stream buffering (WinLive 114314, 252175)
                        // Try again with stream buffering.
                        await UpdateImage(true, editMediaUri, path, editEntryUri, etag, getEditInfo, result);

                        recovered = true;
                    }
                }
                if (!recovered)
                {
                    throw;
                }
            }

            // Check to see if we are going to get the src url and the etag, in most cases we will want to get this
            // information, but in the case of a photo album, since we never edit the image or link directly to them
            // we don't need the information and it can saves an http request.
            if (getEditInfo)
            {
                string selfPage;

                XmlRestRequestHelper.XmlRequestResult xmlResult = new XmlRestRequestHelper.XmlRequestResult();
                xmlResult.uri = new Uri(editEntryUri);
                XmlDocument mediaLinkEntry = await xmlRestRequestHelper.Get(_requestFilter, xmlResult);

                ParseResponse(mediaLinkEntry, result);
            }
            else
            {
                //thumbnailSmall = null;
                //thumbnailLarge = null;
                //srcUrl = 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");
        }