I wonder how could I simplify the code below? Please note that it's not allowed to use instance variables here for some reason.
private bool ValidateQueryString(NameValueCollection queryString, out byte[] errorMessages)
{
var errorsList = new List<string>();
int _aId;
if (!int.TryParse(queryString["a_id"], out _aId))
{
errorMessageList.Add("aId invalid");
}
string bName = queryString["b"];
if (string.IsNullOrWhiteSpace(bName))
{
errorsList.Add("b invalid");
}
else
{
string fullFileName = Path.Combine(MainFolder, bName);
if (!File.Exists(fullFileName))
{
errorsList.Add("file not exist;");
}
}
if (errorsList.Any())
{
using (var memoryStream = new MemoryStream())
{
byte[] newLineByteArray = Encoding.UTF8.GetBytes(Environment.NewLine);
foreach (var item in errorsList)
{
byte[] currentErrorMessage = Encoding.UTF8.GetBytes(item);
memoryStream.Write(currentErrorMessage, 0, currentErrorMessage.Length);
memoryStream.Write(newLineByteArray, 0, newLineByteArray.Length);
}
errorMessages = memoryStream.ToArray();
return false;
}
}
else
{
errorMessages = null;
return true;
}
}
private QueryStringData GetQueryStringData(NameValueCollection queryString)
{
string bName = Path.Combine(_folder, queryString["b"]);
int aId = int.Parse(queryString["a_id"]);
return new QueryStringData(bName, aId);
}
private void ProcessData()
{
using (Stream outputStream = context.Response.OutputStream)
using (MemoryStream outputMemoryStream = new MemoryStream())
{
byte[] errorMessages;
long streamLength;
if (ValidateQueryString(context.Request.QueryString, out errorMessages))
{
QueryStringData queryStringData = GetQueryStringData(context.Request.QueryString);
byte[] value = GetValueByID();
if (value != null)
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
outputMemoryStream.Write(value, 0, value.Length);
streamLength = value.LongLength;
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
byte[] errorMessage = Encoding.UTF8.GetBytes(string.Format("not found", queryStringData.Var1));
outputMemoryStream.Write(errorMessage, 0, errorMessage.Length);
streamLength = errorMessage.LongLength;
}
context.Response.ContentLength64 = streamLength;
outputStream.Write(outputMemoryStream.ToArray(), 0, (int)streamLength);
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
outputMemoryStream.Write(errorMessages, 0, errorMessages.Length);
streamLength = errorMessages.LongLength;
context.Response.ContentLength64 = streamLength;
outputStream.Write(outputMemoryStream.ToArray(), 0, (int)streamLength);
}
}
}
}
ValidateQueryStringfixed or can it be changed? – Rob White Nov 14 '12 at 15:45please note that it's not allowed to use instance variables here for some reasonthat you later accidentally clarify in comments such as(...) it's multithreaded app and IEnumerable make local variables be shared among the other threads. Sorry, I forgot to mention it.– ANeves Nov 15 '12 at 16:07