Connectster.Shopify.ShopifyCommunicator.ShopifyPutPost C# (CSharp) Method

ShopifyPutPost() private method

PUT/POSTs the given XMLDocument to the path w/ the storePassword.
private ShopifyPutPost ( string path, string storePassword, XmlDocument xDocPost, string method ) : XmlDocument
path string Full path to post this XMLDocument to.
storePassword string HashString(shopsterSecret + storeAuthToken)
xDocPost System.Xml.XmlDocument XMLDocument to post to the server
method string 'PUT' or 'POST' to determine the http method
return System.Xml.XmlDocument
        private XmlDocument ShopifyPutPost(string path, string storePassword, XmlDocument xDocPost, string method)
        {
            switch (method)
            {
                case "POST":
                case "PUT":
                    break;
                default:
                    throw new ArgumentException("method must be 'PUT' or 'POST'");
            }

            XmlDocument cleanedXDoc = CleanupXmlForShopifySubmission(xDocPost);

            HttpWebResponse response = null;
            var request = (HttpWebRequest) WebRequest.Create(path);

            request.ServicePoint.Expect100Continue = false;
            request.KeepAlive = false;

            //add credentials to the POST
            var cCache = new CredentialCache
                             {{new Uri(path), "Basic", new NetworkCredential(_appAuth.User, storePassword)}};
            request.Credentials = cCache;

            request.Method = method;
            request.ContentType = "application/xml";

            var sw = new StringWriter();
            var xw = new XmlTextWriter(sw);
            cleanedXDoc.WriteTo(xw);

            //Insert the xmlString into the byte buffer.
            byte[] postBuffer = Encoding.UTF8.GetBytes(sw.ToString());
            request.ContentLength = postBuffer.Length;

            //TODO learn how to do this compiler directive [if DEBUG]
            string xmlString = sw.ToString();
            if (xmlString == null) throw new NotImplementedException();
            ApiLogger.DebugFormat("ShopifyPutPost():: HTTP {0} URL={1}", method, path);
            //[endif]

            try
            {
                //Actually do the POST
                Stream postStream = request.GetRequestStream();
                postStream.Write(postBuffer, 0, postBuffer.Length);
                postStream.Close();

                response = (HttpWebResponse) request.GetResponse();

                if (response != null)
                {
                    // Open the stream using a StreamReader for easy access.
                    var reader = new StreamReader(response.GetResponseStream());
                    var xD = new XmlDocument();
                    xD.Load(reader);

                    // Cleanup the streams and the response.
                    reader.Close();
                    response.Close();
                    XmlDocument returnedDoc = CleanupXmlForDeserialization(xD);
                    returnedDoc.WriteTo(xw);

                    //todo learn how to do this compiler directive [if DEBUG]
                    ApiLogger.DebugFormat("ShopifyPutPost():: Shopify's Response is HTTP {0}", response.StatusCode);
                    //[endif]

                    return returnedDoc;
                }
                else
                {
                    throw new WebException("ShopifyPutPost Expects a Response");
                }
            }
            catch (WebException web)
            {
                //TODO: refactor all this error handling code from Post,Get,Delete into a single method.
                //Todo: add ShopifyError object so responses can be handled nicely. Especially 422, 503, 402
                //Todo: Consider creating own form of exception.
                Logger.ErrorFormat("ShopifyCommunicator::ShopifyPutPost() web exception: {0} , {1} ", web.Message,
                                   web.Response);
                if (web.Response != null)
                {
                    if (web.Response.Headers.AllKeys.Contains("Status"))
                    {
                        if (web.Response.Headers["Status"] == "422")
                        {
                            cleanedXDoc.WriteTo(xw);
                            //Todo: If Debug, next line
                            ApiLogger.DebugFormat(
                                "ShopifyCommunicator::ShopifyPutPost(): Shopify responded with HTTP 422 (Unprocessable Entity), xml was \n {0}",
                                sw);
                            Logger.ErrorFormat(
                                "ShopifyCommunicator::ShopifyPutPost(): Shopify responded with HTTP 422 (Unprocessable Entity), path = {0}",
                                path);
                        }
                        else if (web.Response.Headers["Status"] == "402")
                        {
                            Logger.WarnFormat(
                                "ShopifyCommunicator::ShopifyPutPost(): Shopify responded with HTTP 402 (Payment Required). User is out of skus or some other limit.");
                        }
                    }

                    Stream wResponse = web.Response.GetResponseStream();
                    var reader = new StreamReader(wResponse);
                    string responseMessage = reader.ReadToEnd();
                    reader.Close();

                    ApiLogger.DebugFormat("ShopifyPutPost():: Shopify's Response is HTTP {0}, Content={1}", web.Status,
                                          responseMessage);
                    return IsValidXml(responseMessage); //returns XmlDocument if valid error, or null.
                }
            }
            catch (Exception e)
            {
                Logger.Error("ShopifyCommunicator:: ShopifyPutPost() caught exception" + e);
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            Logger.Warn("ShopifyCommunicator:: ShopifyPutPost() is returning null XmlDocument");
            return null;
        }