/// <summary>
        /// Gets the response text from a web response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>The web response contents.</returns>
        protected static string GetResponseText(WebResponse response)
        {
            if (response == null)
            {
                return(String.Empty);
            }
            MemoryStream memStream = new MemoryStream();

            MediaUtilities.CopyStream(response.GetResponseStream(), memStream);
            return(Encoding.UTF8.GetString(memStream.ToArray()));
        }
        /// <summary>
        /// Downloads a report to stream.
        /// </summary>
        /// <param name="downloadUrl">The download url.</param>
        /// <param name="returnMoneyInMicros">True if money values are returned
        /// in micros.</param>
        /// <param name="postBody">The POST body.</param>
        /// <param name="outputStream">The stream to which report is downloaded.
        /// </param>
        private void DownloadReportToStream(string downloadUrl, bool?returnMoneyInMicros,
                                            string postBody, Stream outputStream)
        {
            AdWordsErrorHandler errorHandler = new AdWordsErrorHandler(user);

            while (true)
            {
                WebResponse    response = null;
                HttpWebRequest request  = BuildRequest(downloadUrl, returnMoneyInMicros, postBody);
                try {
                    response = request.GetResponse();
                    MediaUtilities.CopyStream(response.GetResponseStream(), outputStream);
                    return;
                } catch (WebException ex) {
                    Exception reportsException = null;

                    try {
                        response = ex.Response;

                        if (response != null)
                        {
                            MemoryStream memStream = new MemoryStream();
                            MediaUtilities.CopyStream(response.GetResponseStream(), memStream);
                            String exceptionBody = Encoding.UTF8.GetString(memStream.ToArray());
                            reportsException = ParseException(exceptionBody);
                        }

                        if (AdWordsErrorHandler.IsOAuthTokenExpiredError(reportsException))
                        {
                            reportsException = new AdWordsCredentialsExpiredException(
                                request.Headers["Authorization"]);
                        }
                    } catch (Exception) {
                        reportsException = ex;
                    }
                    if (errorHandler.ShouldRetry(reportsException))
                    {
                        errorHandler.PrepareForRetry(reportsException);
                    }
                    else
                    {
                        throw reportsException;
                    }
                } finally {
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
        }
        /// <summary>
        /// Downloads the report to memory and closes the underlying stream.
        /// </summary>
        /// <exception cref="AdsReportsException">If there was an error downloading the report.
        /// </exception>
        public byte[] Download()
        {
            this.EnsureStreamIsOpen();

            try {
                MemoryStream memStream = new MemoryStream();
                MediaUtilities.CopyStream(this.Stream, memStream);
                this.contents = memStream.ToArray();
                this.CloseWebResponse();
            } catch (Exception e) {
                throw new AdsReportsException("Failed to download report. See inner exception " +
                                              "for more details.", e);
            }

            return(this.contents);
        }
        /// <summary>
        /// Saves the report to a specified path and closes the underlying stream.
        /// </summary>
        /// <param name="path">The path to which report is saved.</param>
        /// <exception cref="AdsReportsException">If there was an error saving the report.</exception>
        public void Save(string path)
        {
            this.EnsureStreamIsOpen();

            try {
                using (FileStream fileStream = File.OpenWrite(path)) {
                    fileStream.SetLength(0);
                    MediaUtilities.CopyStream(this.Stream, fileStream);
                    this.CloseWebResponse();
                }
                this.Path = path;
            } catch (Exception e) {
                throw new AdsReportsException("Failed to save report. See inner exception " +
                                              "for more details.", e);
            }
        }
 /// <summary>
 /// Copy the contents from old stream to new stream.
 /// </summary>
 private void CopyContentsFromOldStream()
 {
     MediaUtilities.CopyStream(oldStream, newStream);
     newStream.Position = 0;
 }
 /// <summary>
 /// Copy the contents from new stream to old stream.
 /// </summary>
 private void CopyContentsToOldStream()
 {
     newStream.Position = 0;
     MediaUtilities.CopyStream(newStream, oldStream);
 }
 public void TestCopyStream()
 {
     MediaUtilities.CopyStream(sourceStream, targetStream);
     Assert.AreEqual(FILE_CONTENTS, Encoding.UTF8.GetString(sourceStream.ToArray()));
 }
Esempio n. 8
0
        private bool DownloadReportToStream(string downloadUrl, AdWordsAppConfig config, bool returnMoneyInMicros, Stream outputStream, string postBody, AdWordsUser user)
        {
            this.response.Text += "\n Creating request...";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(downloadUrl);

            if (!string.IsNullOrEmpty(postBody))
            {
                request.Method = "POST";
            }
            request.Proxy     = config.Proxy;
            request.Timeout   = config.Timeout;
            request.UserAgent = config.GetUserAgent();

            if (!string.IsNullOrEmpty(config.ClientEmail))
            {
                request.Headers.Add("clientEmail: " + config.ClientEmail);
            }
            else if (!string.IsNullOrEmpty(config.ClientCustomerId))
            {
                request.Headers.Add("clientCustomerId: " + config.ClientCustomerId);
            }
            request.ContentType = "application/x-www-form-urlencoded";
            if (config.EnableGzipCompression)
            {
                (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.GZip
                                                                     | DecompressionMethods.Deflate;
            }
            else
            {
                (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.None;
            }
            if (config.AuthorizationMethod == AdWordsAuthorizationMethod.OAuth2)
            {
                if (user.OAuthProvider != null)
                {
                    request.Headers["Authorization"] = user.OAuthProvider.GetAuthHeader(downloadUrl);
                }
                else
                {
                    //throw new AdWordsApiException(null, AdWordsErrorMessages.OAuthProviderCannotBeNull);
                }
            }
            else if (config.AuthorizationMethod == AdWordsAuthorizationMethod.ClientLogin)
            {
                string authToken = (!string.IsNullOrEmpty(config.AuthToken)) ? config.AuthToken :
                                   new AuthToken(config, AdWordsSoapClient.SERVICE_NAME, config.Email,
                                                 config.Password).GetToken();
                request.Headers["Authorization"] = "GoogleLogin auth=" + authToken;
            }

            request.Headers.Add("returnMoneyInMicros: " + returnMoneyInMicros.ToString().ToLower());
            request.Headers.Add("developerToken: " + config.DeveloperToken);
            // The client library will use only apiMode = true.
            request.Headers.Add("apiMode", "true");

            if (!string.IsNullOrEmpty(postBody))
            {
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(postBody);
                }
            }

            // AdWords API now returns a 400 for an API error.
            bool        retval   = false;
            WebResponse response = null;

            try
            {
                this.response.Text += "\n Getting server response...";
                response            = request.GetResponse();
                retval              = true;
            }
            catch (WebException ex)
            {
                response = ex.Response;
                byte[] preview       = ConvertStreamToByteArray(response.GetResponseStream(), MAX_ERROR_LENGTH);
                string previewString = ConvertPreviewBytesToString(preview);
                retval = false;
                this.webExceptionTextBox.Text = previewString;
            }
            MediaUtilities.CopyStream(response.GetResponseStream(), outputStream);
            response.Close();
            return(retval);
        }