/// <summary> /// Prints the successful result /// </summary> /// <param name="statusCode">Status code</param> /// <param name="queryStringData">Query string data</param> /// <param name="constantValue">Constant value</param> private void PrintSuccessfulResult(int statusCode, QueryStringData queryStringData, string constantValue) { PrintResultImpl(statusCode, () => { Console.WriteLine(string.Format("\tfileName: => {0}, id => {1}, value => {2}", queryStringData.FileName, queryStringData.ConstantID, constantValue)); }); }
/// <summary> /// CallBack method for handling request /// </summary> /// <param name="o">object to be casted to HttpListenerContext</param> private void ProcessRequest(object obj) { Console.WriteLine("Processing the request..."); HttpListenerContext context = obj as HttpListenerContext; //try //{ using (StreamWriter writer = new StreamWriter(context.Response.OutputStream)) { List <string> errors = GetQueryStringValidationErrors(context.Request.QueryString).ToList(); //There is no any error in validation if (!errors.Any()) { QueryStringData queryStringData = GetQueryStringData(context); string value = GetConstantValueByID(queryStringData); //Constant is found, everything is ok if (value != null) { context.Response.StatusCode = (int)HttpStatusCode.OK; writer.Write(value); } //Constant is not found else { context.Response.StatusCode = (int)HttpStatusCode.NotFound; writer.Write(string.Format("constant {0} you have requested is not found", queryStringData.ConstantID)); } PrintSuccessfulResult(context.Response.StatusCode, queryStringData, value); } //There is an error in validation else { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; errors.ForEach(writer.WriteLine); PrintErrorResult(context.Response.StatusCode, errors); } } //} //catch (Exception e) //{ // Console.WriteLine("There is an exception thrown - {0}", e.Message); //} }
/// <summary> /// Returns constant value by its id /// </summary> /// <param name="queryStringData">QueryStringData</param> /// <returns>constant value</returns> private string GetConstantValueByID(QueryStringData queryStringData) { const string regexPattern = @"(^\d+),\s+(.+)"; foreach (string item in File.ReadLines(queryStringData.FileName)) { Match match = Regex.Match(item, regexPattern); if (match.Success) { int currentConstantID = int.Parse(match.Groups[1].Value); if (currentConstantID == queryStringData.ConstantID) { return(match.Groups[2].Value); } } } return(null); }