I wrote a method early of our development last year about getting the content of a webrequest
where it contains an xml data that we need to process and insert to database. I wanted to improve this, so I'm asking a feedback on these code snippets.
public async Task<BulkStatusCode> AuthenticateConnection(string url, string user, string access, string recordType)
{
try
{
// TODO : this is just a quickfix, create a logic that will determine if the url is using ssl or not
url = url.Replace("http://", "https://");
var uri = new Uri(url);
//ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, SslPolicyErrors) => true);
var request = WebRequest.Create(uri) as HttpWebRequest;
request.PreAuthenticate = true;
//will ignore certificate validation
request.ServerCertificateValidationCallback = ((sender, certificate, chain, SslPolicyErrors) => true);
request.Method = WebRequestMethods.Http.Get;
request.Credentials = BulkAuthentication.GetCredentialCache(uri, user, access);
//check if status is 200 and content type is correct
using (var response = await request.GetResponseAsync() as HttpWebResponse)
{
if (response.StatusCode.Equals(HttpStatusCode.OK))
{
if (!ReferenceEquals(response.ContentType, null) && IsValidContentType(response.ContentType))
{
using (var stream = response.GetResponseStream())
{
//store stream to variable
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
var storeStreamToCache = ms.ToArray();
var storeStreamToValidate = ms.ToArray();
using (Stream streamToValidate = new MemoryStream(storeStreamToValidate))
{
using (var reader2 = new StreamReader(streamToValidate))
{
if (!XmlValidator.IsValidXml(reader2, XmlSchemaType(recordType)))
return BulkStatusCode.UnsupportedXML;
}
}
using (Stream streamToCache = new MemoryStream(storeStreamToCache))
{
using (var reader = new StreamReader(streamToCache))
{
if (recordType.Equals("Foo"))
{
var serializer = new XmlSerializer(typeof(BulkFooRoot));
userXmlData = (BulkFooRoot)serializer.Deserialize(reader);
_cache.Add("BulkFooUserXml", fooXmlData);
}
else if (recordType.Equals("Bar"))
{
var serializer = new XmlSerializer(typeof(BulkBarRoot));
projectXmlData = (BulkBarRoot)serializer.Deserialize(reader);
_cache.Add("BulkUploadBarXml", projectXmlData);
}
}
}
}
}
//valid content type but has invalid xml content
return BulkStatusCode.OK;
}
//invalid content type
return BulkStatusCode.UnsupportedMediaType;
}
}
}
catch (WebException ex)
{
var responseStatusCode = ((HttpWebResponse)ex.Response).StatusCode;
if (ReferenceEquals(ex.Response, null) || !responseStatusCode.Equals(HttpStatusCode.Unauthorized))
//invalid request (http not found)
return BulkStatusCode.NotFound;
}
// retry status to retry to login again
return BulkStatusCode.Retry;
}
private static bool IsValidContentType(string contentType)
{
switch (contentType)
{
case "text/xml":
case "application/xml; charset=utf-8":
return true;
}
return false;
}