public async Task <HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage();

            sdssSIAP.SIAP siap = new sdssSIAP.SIAP();
            SiapTable     vout = new SiapTable();

            switch (casjobsTaskName)
            {
            case "getSIAP":
                vout = siap.getSiapInfo(dictionary["POS"], dictionary["SIZE"], dictionary["FORMAT"], "");
                break;

            case "getSIAPInfo":
                vout = siap.getSiapInfo(dictionary["POS"], dictionary["SIZE"], dictionary["FORMAT"], dictionary["bandpass"]);

                break;

            case "getSIAPInfoAll":
                vout = siap.getSiapInfo(dictionary["POS"], dictionary["SIZE"], "All", "*");
                break;

            default: break;
            }

            response.Content = new StringContent(ToXML(vout), Encoding.UTF8, "application/xml");
            //logging
            SciserverLogging logger = new SciserverLogging();

            logger.LogActivity(ActivityInfo, "SkyserverMessage");
            return(response);
        }
Beispiel #2
0
        public HttpResponseMessage Get([FromUri] string R = null, [FromUri] string C = null, [FromUri] string F = null, [FromUri] string Z = "0", [FromUri] String token = "")
        {
            RequestMisc rm = new RequestMisc(this.Request, "SkyserverWS.ImgCutout.getJpegCodec");

            this.Request.RequestUri = rm.AddTaskNameToURI(this.Request.RequestUri);
            LoggedInfo ActivityInfo = rm.ActivityInfo;

            HttpResponseMessage resp = new HttpResponseMessage();

            Validation valid = new Validation();

            if (R == null || C == null || F == null)
            {
                throw new ArgumentException("There are not enough parameters to process your request. Enter position (ra,dec) values properly. ");
            }
            if (valid.ValidateInput(R, C, F, Z))
            {
                ImgCutout.ImgCutout img = new ImgCutout.ImgCutout();
                resp.Content = new ByteArrayContent(img.GetJpegImg(valid.getRun(), valid.getCamcol(), valid.getField(), valid.getZoom(), token));
                resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                if (String.IsNullOrEmpty(img.errorMessage_Generic) && String.IsNullOrEmpty(img.errorMessage_OutOfFootprint))
                {
                    resp.StatusCode = HttpStatusCode.OK;
                }
                else
                {
                    if (!String.IsNullOrEmpty(img.errorMessage_Generic))
                    {
                        resp.StatusCode   = HttpStatusCode.InternalServerError;
                        resp.ReasonPhrase = "INTERNAL SERVER ERROR. " + img.errorMessage_Generic.Replace("\n", ". ");
                    }
                    else if (!String.IsNullOrEmpty(img.errorMessage_OutOfFootprint))
                    {
                        resp.StatusCode   = HttpStatusCode.NotFound;
                        resp.ReasonPhrase = "NOT FOUND.\n" + img.errorMessage_OutOfFootprint;
                    }
                    else
                    {
                        resp.StatusCode = HttpStatusCode.InternalServerError;
                    }
                }
                //logging
                SciserverLogging logger = new SciserverLogging();
                ActivityInfo.Message             = rm.GetLoggedMessage("");
                ActivityInfo.DoShowInUserHistory = false;
                logger.LogActivity(ActivityInfo, "SkyserverMessage");

                return(resp);
            }

            throw new Exception("Request is not processed, Enter parameters properly.  ra must be in [0,360], dec must be in [-90,90], scale must be in [0.015, 60.0], height and width must be in [64,2048].");
        }
Beispiel #3
0
        public async Task <HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            //response = new HttpResponseMessage();
            //HttpResponseMessage respMessage = null;
            //string ResponseResult = "";
            //string requestUri = "";
            try
            {
                if (ExtraInfo["FormatFromUser"] == "mydb")
                {
                    return(SendToMyDB());
                    //response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                }
                else
                {
                    return(SendToUser());
                }
                //logging

                //return processDBqueryResults(stream);
            }
            catch (Exception e)
            {
                if (ExtraInfo["DoReturnHtml"].ToLower() == "true")
                {
                    HttpStatusCode errorCode    = HttpStatusCode.InternalServerError;
                    string         reasonPhrase = errorCode.ToString();
                    string         errorMessage = e.Message + ((e.InnerException != null) ? (": " + e.InnerException.Message) : "");

                    SciserverLogging Logger = new SciserverLogging();
                    ActivityInfo.Exception = e;
                    Logger.LogActivity(ActivityInfo, "ErrorMessage");

                    StringBuilder strbldr = new StringBuilder();
                    StringWriter  sw      = new StringWriter(strbldr);
                    using (JsonWriter writer = new JsonTextWriter(sw))
                    {
                        writer.WriteStartObject();
                        writer.WritePropertyName("ErrorCode");
                        writer.WriteValue((int)errorCode);
                        writer.WritePropertyName("ErrorType");
                        writer.WriteValue(errorCode.ToString());
                        writer.WritePropertyName("ErrorMessage");
                        writer.WriteValue(errorMessage);
                        writer.WritePropertyName("LogMessageID");
                        writer.WriteValue(Logger.message.MessageId);
                        writer.WritePropertyName("LogTime");
                        writer.WriteValue(Logger.message.Time);
                    }
                    string TechnicalErrorInfo = strbldr.ToString();

                    strbldr = new StringBuilder();
                    sw      = new StringWriter(strbldr);
                    using (JsonWriter writer = new JsonTextWriter(sw))
                    {
                        writer.WriteStartObject();
                        writer.WritePropertyName("ErrorCode");
                        writer.WriteValue((int)errorCode);
                        writer.WritePropertyName("ErrorType");
                        writer.WriteValue(errorCode.ToString());
                        writer.WritePropertyName("ErrorMessage");
                        writer.WriteValue(errorMessage);
                        writer.WritePropertyName("LogMessageID");
                        writer.WriteValue(Logger.message.MessageId);
                        writer.WritePropertyName("username");
                        writer.WriteValue(Logger.user_name);
                        writer.WritePropertyName("userid");
                        writer.WriteValue(Logger.userid);
                        writer.WritePropertyName("pageurl");
                        writer.WriteValue(ActivityInfo.URI);
                        writer.WritePropertyName("referrer");
                        writer.WriteValue(ActivityInfo.Referrer);
                        writer.WritePropertyName("StackTrace");
                        writer.WriteValue(ActivityInfo.Exception.StackTrace);
                        writer.WritePropertyName("InnerTrace");
                        writer.WriteValue(ActivityInfo.Exception.InnerException != null ? ActivityInfo.Exception.InnerException.StackTrace : "");
                        writer.WritePropertyName("LogTime");
                        writer.WriteValue(Logger.message.Time);
                        writer.WritePropertyName("ClientIP");
                        writer.WriteValue(Logger.message.ClientIP);
                    }
                    string TechnicalErrorInfoAll = strbldr.ToString();

                    bool           IsSuccess = false;
                    ProcessDataSet proc      = new ProcessDataSet(query, format, TaskName, ExtraInfo, errorMessage, IsSuccess, positionType, queryType, TechnicalErrorInfo, TechnicalErrorInfoAll);
                    response.Content = proc.GetContent(ResultsDataSet);// this will log
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                    return(response);
                }
                else
                {
                    throw new Exception(e.Message);//throwing the exception takes to CustomFilter.cs, where error logging is performed and the error response is returned to the user.
                }
            }
        }
Beispiel #4
0
        public HttpResponseMessage SendToMyDB()
        {
            HttpResponseMessage respMessage = null;
            string ResponseResult           = "";
            string requestUri = "";

            if (logger.IsValidUser)
            {
                string TableName = ExtraInfo["TableName"];

                if (!string.IsNullOrEmpty(TableName))
                {
                    Regex rg = new Regex("[^a-zA-Z0-9]");
                    if (rg.IsMatch(TableName))
                    {
                        throw (new Exception("String TableName may only contain letters or numbers."));
                    }

                    /*
                     * string ForbiddenChar = ",./-?\!";
                     * for (int i = 0; i < ForbiddenChar.Length;i++)
                     * {
                     *  if (TableName.Contains(ForbiddenChar.Substring(i,1)))
                     *      throw (new Exception("TableName may not contain characters like " + ForbiddenChar ));
                     * }
                     */
                    requestUri = ConfigurationManager.AppSettings["CASJobsREST"] + "contexts/MyDB/tables/";
                    HttpClient client = new HttpClient();
                    client.Timeout     = new TimeSpan(0, 0, 0, KeyWords.TimeoutCASJobs);// default is 100000ms
                    client.BaseAddress = new Uri(requestUri);
                    client.DefaultRequestHeaders.Add("X-Auth-Token", logger.Token);
                    respMessage    = client.GetAsync(requestUri).Result;
                    ResponseResult = respMessage.Content.ReadAsStringAsync().Result;
                    if (!respMessage.IsSuccessStatusCode)
                    {
                        if (ExtraInfo["DoReturnHtml"].ToLower() == "false")
                        {
                            CreateErrorResponseMessageJSON(ResponseResult);
                        }
                        else
                        {
                            CreateErrorResponseMessageHTML(ResponseResult);
                        }

                        logger.LogActivity(ActivityInfo, "SkyserverMessage");
                        return(response);
                    }

                    Dictionary <string, string> values;
                    Newtonsoft.Json.Linq.JArray array = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(ResponseResult);//ResponseResult comes in json format
                    for (int i = 0; i < array.Count; i++)
                    {
                        values = JsonConvert.DeserializeObject <Dictionary <string, string> >(array[i].ToString());
                        if (values["Name"] == TableName)
                        {
                            if (ExtraInfo["DoReturnHtml"].ToLower() == "false")
                            {
                                throw (new Exception("Table \"" + TableName + "\" already exists in MyDB. Try changing the table name or see it in MyDB"));
                            }
                            else
                            {
                                ProcessDataSet proc         = new ProcessDataSet(query, format, TaskName, ExtraInfo, null, true, positionType, queryType, null, null);
                                string         queryResult1 = proc.getTableReSubmitHTMLresult(TableName, logger.Token);
                                response.Content = new StringContent(queryResult1, tCode, KeyWords.contentHTML);
                                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                            }
                            return(response);
                        }
                        //throw (new Exception("Table \"" + TableName + "\" already exists in MyDB. Try changing the table name or  <a target=INFO href=\"" + ConfigurationManager.AppSettings["CASJobs"] + "MyDB.aspx" + "\">LINK</a> "));
                    }
                }
                else// create a table name
                {
                    //DateTime2 now = DateTime2.Now;
                    TableName = "Table_" + DateTime.Now.ToString("yyyyMMdd_HHmmss_fff");
                }

/*
 *              if (!(ExtraInfo["EntryPoint"].ToLower().Contains("sqlsearch") || ExtraInfo["EntryPoint"].ToLower().Contains("crossid") || ExtraInfo["EntryPoint"].ToLower().Contains("proximity")))// sending query as a job
 *              {
 *                  string queryResult = "";
 *                  StringBuilder strbldr = new StringBuilder();
 *                  StringWriter sw = new StringWriter(strbldr);
 *                  using (JsonWriter writer = new JsonTextWriter(sw))
 *                  {
 *                      writer.WriteStartObject();
 *                      writer.WritePropertyName("query");
 *                      writer.WriteValue(ExtraInfo["QueryForUserDisplay"]);
 *                      writer.WritePropertyName("TaskName");
 *                      writer.WriteValue("SkyserverWS.SendToMyDB");
 *                      writer.WritePropertyName("CreateTable");
 *                      writer.WriteValue("true");
 *                      writer.WritePropertyName("TableName");
 *                      writer.WriteValue(TableName);
 *                  }
 *
 *                  StringContent content = new StringContent(strbldr.ToString());
 *                  content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
 *                  content.Headers.Add("X-Auth-Token", logger.Token);
 *
 *                  //posting the request and getting the result back.
 *                  HttpClient client2 = new HttpClient();
 *                  client2.Timeout = new TimeSpan(0, 0, 0, KeyWords.TimeoutCASJobs);// default is 100000ms
 *                  requestUri = ConfigurationManager.AppSettings["CASJobsREST"] + "contexts/" + KeyWords.DataRelease + "/jobs";
 *                  client2.BaseAddress = new Uri(requestUri);
 *                  respMessage = client2.PutAsync(requestUri, content).Result;
 *                  string JobID = "UNKNOWN";
 *                  if (respMessage.IsSuccessStatusCode)
 *                  {
 *                      JobID = respMessage.Content.ReadAsStringAsync().Result;
 *                      if (ExtraInfo["DoReturnHtml"].ToLower() == "false")
 *                      {
 *                          queryResult = "[{\"JobID\": \"" + JobID + "\", \"TableName\"= \"" + TableName + "\"}]";
 *                          response.Content = new StringContent(queryResult, tCode, KeyWords.contentJson);
 *                          response.Content.Headers.ContentType = new MediaTypeHeaderValue(KeyWords.contentJson);
 *                      }
 *                      else
 *                      {
 *                          ProcessDataSet proc = new ProcessDataSet(query, format, TaskName, ExtraInfo, null, true, positionType, queryType, null, null);
 *                          queryResult = proc.getCasJobsSubmitHTMLresult(JobID, TableName, logger.Token);
 *                          response.Content = new StringContent(queryResult, tCode, KeyWords.contentHTML);
 *                          response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
 *                      }
 *                  }
 *                  else
 *                  {
 *                      string ErrorMessage = respMessage.Content.ReadAsStringAsync().Result;
 *                      if (ExtraInfo["DoReturnHtml"].ToLower() == "false")
 *                          CreateErrorResponseMessageJSON(ErrorMessage);
 *                      else
 *                          CreateErrorResponseMessageHTML(ErrorMessage);
 *                  }
 *
 *                  logger.LogActivity(ActivityInfo, "SkyserverMessage");
 *                  return response;
 *
 *              }
 *              else // sending query results as a csv
 *              {
 *              }
 */

                //sending query result as a csv:
                string queryResult = "";
                RunQuery();
                Action <Stream, HttpContent, TransportContext> WriteToStream = null;
                DataSet ds = new DataSet();
                ds.Tables.Add(ResultsDataSet.Tables[0].Copy());
                WriteToStream = (stream, foo, bar) => { OutputUtils.writeCSV(ds, stream, false); stream.Close(); };
                HttpContent content = new PushStreamContent(WriteToStream, new MediaTypeHeaderValue((KeyWords.contentCSV)));
                //content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
                content.Headers.Add("X-Auth-Token", logger.Token);
                requestUri = ConfigurationManager.AppSettings["CASJobsREST"] + "contexts/MyDB/tables/" + TableName;
                HttpClient client2 = new HttpClient();
                client2.Timeout     = new TimeSpan(0, 0, 0, KeyWords.TimeoutCASJobs);// default is 100000ms
                client2.BaseAddress = new Uri(requestUri);
                respMessage         = client2.PostAsync(requestUri, content).Result;
                if (respMessage.IsSuccessStatusCode)
                {
                    if (ExtraInfo["DoReturnHtml"].ToLower() == "false")
                    {
                        queryResult      = "[{\"IsSuccessStatusCode\": \"true\", \"TableName\"= \"" + TableName + "\"}]";
                        response.Content = new StringContent(queryResult, tCode, KeyWords.contentJson);
                        response.Content.Headers.ContentType = new MediaTypeHeaderValue(KeyWords.contentJson);
                    }
                    else
                    {
                        ProcessDataSet proc = new ProcessDataSet(query, format, TaskName, ExtraInfo, null, true, positionType, queryType, null, null);
                        queryResult      = proc.getTableSubmitHTMLresult(TableName, logger.Token);
                        response.Content = new StringContent(queryResult, tCode, KeyWords.contentHTML);
                        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                    }
                }
                else
                {
                    string ErrorMessage = respMessage.Content.ReadAsStringAsync().Result;
                    if (ExtraInfo["DoReturnHtml"].ToLower() == "false")
                    {
                        CreateErrorResponseMessageJSON(ErrorMessage);
                    }
                    else
                    {
                        CreateErrorResponseMessageHTML(ErrorMessage);
                    }
                }

                logger.LogActivity(ActivityInfo, "SkyserverMessage");
                return(response);
            }
            else
            {
                throw (new UnauthorizedAccessException("You are not logged-in with SciServer. Please log-in and try again."));
            }
        }
        public HttpResponseMessage Get([FromUri] string ra = null, [FromUri] string dec = null, [FromUri] string scale = "0.396127",
                                       [FromUri] int width = 128, [FromUri] int height  = 128, [FromUri] String opt    = "", [FromUri] String query = "", [FromUri] String clientIP = "", [FromUri] String token = "", [FromUri] String TaskName = "")
        {
            RequestMisc rm = new RequestMisc(this.Request, "SkyserverWS.ImgCutout.getJpeg");

            this.Request.RequestUri = rm.AddTaskNameToURI(this.Request.RequestUri);
            LoggedInfo ActivityInfo = rm.ActivityInfo;
            string     ClientIP     = ActivityInfo.ClientIP;

            HttpResponseMessage resp = new HttpResponseMessage();

            Validation valid = new Validation();

            if (ra == null || dec == null || scale == null)
            {
                throw new ArgumentException("There are not enough parameters to process your request. Enter position (ra,dec) values properly.ra must be in [0,360], dec must be in [-90,90], scale must be in [0.015, 60.0]. ");
            }
            if (valid.ValidateInput(ra, dec, scale))
            {
                ImgCutout.ImgCutout img = new ImgCutout.ImgCutout();

                if (query == null)
                {
                    query = "";
                }
                /// This part can be changed later if we change internal ImgCutout code.
                if (opt != null)
                {
                    opt = "C" + opt;
                }
                else
                {
                    opt = "C";
                }

                resp.Content = new ByteArrayContent(img.GetJpeg(valid.getRa(), valid.getDec(), valid.getScale(), width, height, opt, query, "", "", token, ClientIP));
                resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                if (String.IsNullOrEmpty(img.errorMessage_Generic) && String.IsNullOrEmpty(img.errorMessage_OutOfFootprint))
                {
                    resp.StatusCode = HttpStatusCode.OK;
                }
                else
                {
                    if (!String.IsNullOrEmpty(img.errorMessage_Generic))
                    {
                        resp.StatusCode   = HttpStatusCode.InternalServerError;
                        resp.ReasonPhrase = "INTERNAL SERVER ERROR. " + img.errorMessage_Generic.Replace("\n", ". ");
                    }
                    else if (!String.IsNullOrEmpty(img.errorMessage_OutOfFootprint))
                    {
                        resp.StatusCode   = HttpStatusCode.NotFound;
                        resp.ReasonPhrase = "NOT FOUND. " + img.errorMessage_OutOfFootprint;
                    }
                    else
                    {
                        resp.StatusCode = HttpStatusCode.InternalServerError;
                    }
                }
                //logging
                SciserverLogging logger = new SciserverLogging();
                ActivityInfo.Message = rm.GetLoggedMessage(query);
                logger.LogActivity(ActivityInfo, "SkyserverMessage");

                return(resp);
            }

            throw new Exception("Request is not processed, Enter parameters properly.  ra must be in [0,360], dec must be in [-90,90], scale must be in [0.015, 60.0], height and width must be in [64,2048].");
        }
Beispiel #6
0
        public override void OnException(HttpActionExecutedContext context)
        {
            System.Text.Encoding tCode = System.Text.Encoding.UTF8;
            String responseType        = "application/json";
            String reasonPhrase        = "";
            String errorMessage        = "";

            HttpStatusCode errorCode = HttpStatusCode.InternalServerError;

            if (context.Exception is AuthException)
            {
                errorCode    = HttpStatusCode.Unauthorized;
                reasonPhrase = errorCode.ToString();
            }
            if (context.Exception is UnauthorizedAccessException)
            {
                errorCode    = HttpStatusCode.Unauthorized;
                reasonPhrase = errorCode.ToString();
            }
            else if (context.Exception is NotImplementedException)
            {
                errorCode    = HttpStatusCode.NotImplemented;
                reasonPhrase = errorCode.ToString();
                //reasonPhrase = "This method is not implemented";
            }
            else if (context.Exception is NotSupportedException)
            {
                errorCode    = HttpStatusCode.BadRequest; // ???
                reasonPhrase = errorCode.ToString();
                //reasonPhrase = "The action is not supported by web service";
            }
            else if (context.Exception is HttpUnhandledException)
            {
                errorCode    = HttpStatusCode.ExpectationFailed;
                reasonPhrase = errorCode.ToString();
                //reasonPhrase = "This error is not handled";
            }
            else if (context.Exception is ArgumentException)
            {
                errorCode    = HttpStatusCode.BadRequest;
                reasonPhrase = errorCode.ToString();
                //reasonPhrase = "Input parameters are not proper";
            }
            else if (context.Exception is NotFoundException)
            {
                errorCode    = HttpStatusCode.NotFound;
                reasonPhrase = errorCode.ToString();
            }
            else if (context.Exception is Exception)
            {
                errorCode    = HttpStatusCode.InternalServerError;
                reasonPhrase = errorCode.ToString();
                //reasonPhrase = "An internal error occured";
            }
            else
            {
                errorCode    = HttpStatusCode.InternalServerError;
                reasonPhrase = errorCode.ToString();
                //reasonPhrase = "An internal error occured";
            }


            //ProcessRequest pr = new ProcessRequest(context.Request, "");
            SciserverLogging Logger = new SciserverLogging();
            RequestMisc      rm     = new RequestMisc(context.Request, "");

            //// There should be some logging code here

            LoggedInfo ActivityInfo = rm.ActivityInfo;

            ActivityInfo.Exception = context.Exception;
            ActivityInfo.Message   = rm.GetLoggedMessage("");
            Logger.LogActivity(ActivityInfo, "ErrorMessage");

            //preparing the message sent to the user

            errorMessage = context.Exception.Message + ((context.Exception.InnerException != null) ? (": " + context.Exception.InnerException.Message) : "");

            StringBuilder strbldr = new StringBuilder();
            StringWriter  sw      = new StringWriter(strbldr);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.WriteStartObject();
                writer.WritePropertyName("ErrorCode");
                writer.WriteValue((int)errorCode);
                writer.WritePropertyName("ErrorType");
                writer.WriteValue(errorCode.ToString());
                writer.WritePropertyName("ErrorMessage");
                writer.WriteValue(errorMessage);
                writer.WritePropertyName("LogMessageID");
                writer.WriteValue(Logger.message.MessageId);
                writer.WritePropertyName("LogTime");
                writer.WriteValue(Logger.message.Time);
            }
            string TechInfoJson = strbldr.ToString();

            strbldr = new StringBuilder();
            sw      = new StringWriter(strbldr);
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.WriteStartObject();
                writer.WritePropertyName("ErrorCode");
                writer.WriteValue((int)errorCode);
                writer.WritePropertyName("ErrorType");
                writer.WriteValue(errorCode.ToString());
                writer.WritePropertyName("ErrorMessage");
                writer.WriteValue(errorMessage);
                writer.WritePropertyName("LogMessageID");
                writer.WriteValue(Logger.message.MessageId);
                writer.WritePropertyName("username");
                writer.WriteValue(Logger.user_name);
                writer.WritePropertyName("userid");
                writer.WriteValue(Logger.userid);
                writer.WritePropertyName("pageurl");
                writer.WriteValue(ActivityInfo.URI);
                writer.WritePropertyName("referrer");
                writer.WriteValue(ActivityInfo.Referrer);
                writer.WritePropertyName("StackTrace");
                writer.WriteValue(ActivityInfo.Exception.StackTrace);
                writer.WritePropertyName("InnerTrace");
                writer.WriteValue(ActivityInfo.Exception.InnerException != null ? ActivityInfo.Exception.InnerException.StackTrace : "");
                writer.WritePropertyName("LogTime");
                writer.WriteValue(Logger.message.Time);
                writer.WritePropertyName("ClientIP");
                writer.WriteValue(Logger.message.ClientIP);
            }
            string TechInfoJsonAll = strbldr.ToString();


            bool IsHTMLformat = false;

            try
            {
                if (rm.dictionary["format"].ToString().ToLower() == "html" || (rm.dictionary["format"].ToLower() == "mydb" && !rm.IsDirectUserConnection))   // || (rm.dictionary["format"].ToString().ToLower() == "mydb" && !rm.IsDirectUserConnection ) )
                {
                    IsHTMLformat = true;
                }
            }
            catch { }

            if (IsHTMLformat)// returns a HTML page with the error message, if the user wants an html reult
            {
                string HtmlContent = "<html><head>";
                HtmlContent += "<title>Skyserver Error</title>";
                HtmlContent += "</head><body bgcolor=white>";
                HtmlContent += "<h2>An error occured</h2>";
                HtmlContent += "<H3 BGCOLOR=pink><font color=red>" + WebUtility.HtmlEncode(context.Exception.Message) + "<br><br></font></H3>";
                HtmlContent += "<br><br> <form method =\"POST\" target=\"_blank\" name=\"bugreportform\" action=\"" + ConfigurationManager.AppSettings["BugReportURL"] + "\">";
                Dictionary <string, string> ErrorFields = JsonConvert.DeserializeObject <Dictionary <string, string> >(TechInfoJsonAll);
                foreach (string key in ErrorFields.Keys)
                {
                    HtmlContent += "<input type=\"hidden\" name=\"popz_" + key + "\" id=\"popz_" + key + "\" value=\"" + WebUtility.HtmlEncode(ErrorFields[key]) + "\" />";
                }
                //HtmlContent += "<input type=\"hidden\" name=\"popz_bugreport\" id=\"popz_bugreport\" value=\"" + WebUtility.HtmlEncode(TechInfoJsonAll) + "\" />";
                HtmlContent += "<input id=\"submit\" type=\"submit\" value=\"Click to Report Error\">";
                HtmlContent += "</form>";
                HtmlContent += "<br>Technical info: <br> " + WebUtility.HtmlEncode(TechInfoJson);
                HtmlContent += "</BODY></HTML>";

                HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content      = new StringContent(HtmlContent, tCode, "text/html"),
                    ReasonPhrase = reasonPhrase
                };
                throw new HttpResponseException(resp);
            }
            else // this returns the jason string with the error message, for all formats except html
            {
                HttpResponseMessage resp = new HttpResponseMessage(errorCode)
                {
                    Content      = new StringContent(TechInfoJson, tCode, responseType),
                    ReasonPhrase = reasonPhrase
                };
                throw new HttpResponseException(resp);
            }
        }