/// Upload table
        public HttpResponseMessage uploadTest(ApiController api, string queryType, string positionType, string casjobsMessage)
        {
            try
            {
                IEnumerable <string> values;
                if (api.ControllerContext.Request.Headers.TryGetValues(KeyWords.XAuthToken, out values))
                {
                    // Keystone authentication
                    string token      = values.First();
                    var    userAccess = Keystone.Authenticate(token);

                    Dictionary <String, String> dictionary = api.Request.GetQueryNameValuePairs().ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase);
                    String query = "";

                    string radiusDefault = "1";// in arcminutes
                    try { radiusDefault = float.Parse(dictionary["radiusDefault"]).ToString(); }
                    catch { }

                    if (dictionary["radecTextarea"] != null)
                    {
                        UploadDataReader up = new UploadDataReader(radiusDefault);
                        query += up.UploadTo(dictionary["radecTextarea"], queryType, dictionary["nearBy"]);
                    }
                    else
                    {
                        var task = api.Request.Content.ReadAsStreamAsync();
                        task.Wait();
                        Stream stream = task.Result;

                        using (UploadDataReader up = new UploadDataReader(new StreamReader(stream), radiusDefault))
                        {
                            query += up.UploadTo(queryType, dictionary["nearBy"]);
                        }
                    }

                    HttpResponseMessage resp = new HttpResponseMessage();
                    query += QueryTools.BuildQuery.buildQuery(queryType, dictionary, positionType);
                    //RunCasjobs run = new RunCasjobs();
                    //resp.Content = new StringContent(run.postCasjobs(query, token, casjobsMessage).Content.ReadAsStringAsync().Result);
                    return(resp);
                }
                else
                {
                    // No authentication (anonymous) // Logg
                    throw new UnauthorizedAccessException("Check the token you are using.");
                }
            }
            catch (Exception exp) {
                throw new Exception("Exception while uploading data to create temp table." + exp.Message);
            }
        }
        /// <summary>
        /// Runs the query for the proximity kind of search.
        /// </summary>
        /// <param name="api">The API.</param>
        /// <param name="queryType">Type of the query.</param>
        /// <param name="positionType">Type of the position.</param>
        /// <param name="Message">The message.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">
        /// Check input parameters properly.\n + e.Message
        /// or
        /// Neither upload file nor list specified for Proximity search.
        /// </exception>
        /// <exception cref="System.Exception">Error while uploading coordinates to create a temporary table.  + exp.Message</exception>
        public IHttpActionResult proximityQuery(ApiController api, string queryType, string positionType, string Message)
        {
            // This dict stores extra info needed for running and rendering the query results.

/*
 *          Dictionary<string, string> ExtraInfo = new Dictionary<string, string>();
 *          ExtraInfo.Add("fp", "");
 *          ExtraInfo.Add("syntax", "");
 *          ExtraInfo.Add("QueryForUserDisplay", "");
 */

            try
            {
                //string datarelease = HttpContext.Current.Request.RequestContext.RouteData.Values["anything"] as string; /// which SDSS Data release is to be accessed

                ///
                HttpResponseMessage resp = new HttpResponseMessage();
                Logger log   = (HttpContext.Current.ApplicationInstance as MvcApplication).Log;
                String query = "";

                /*
                 * try
                 * {
                 *  if (dictionary == null)
                 *      dictionary = api.Request.GetQueryNameValuePairs().ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase);
                 * }
                 * catch (Exception e)
                 * {
                 *  throw new ArgumentException("Check input parameters properly.\n" + e.Message);
                 * }
                 *
                 *
                 * if (string.IsNullOrEmpty(this.ClientIP))
                 *  this.ClientIP = rm.GetClientIP(dictionary);//GetClientIP sets the value of IsDirectUserConnection as well.
                 * if (string.IsNullOrEmpty(this.TaskName))
                 *  this.TaskName = rm.GetTaskName(dictionary, Message);// must be executed right after GetClientIP(ref dictionary);
                 * if (string.IsNullOrEmpty(this.server_name))
                 *  try { server_name = HttpContext.Current.Request.ServerVariables["SERVER_NAME"]; }
                 *  catch { }
                 * if (string.IsNullOrEmpty(this.windows_name))
                 *  try { windows_name = System.Environment.MachineName; }
                 *  catch { };
                 *
                 * dictionary.Add("server_name", server_name);
                 * dictionary.Add("windows_name", windows_name);
                 *
                 *
                 * // get data release number
                 * string drnumber = datarelease.ToUpper().Replace("DR", "");
                 *
                 * dictionary.Add("datarelease", drnumber);
                 */
                var task = api.Request.Content.ReadAsStreamAsync();
                task.Wait();
                Stream stream = task.Result;

                bool HasFile      = false;
                bool HasRaDecText = false;

                string radiusDefault = "1";// in arcminutes
                try { radiusDefault = float.Parse(dictionary["radiusDefault"]).ToString(); }
                catch { }

                try
                {
                    using (UploadDataReader up = new UploadDataReader(new StreamReader(stream), radiusDefault))
                    {
                        if (stream.Length > 0)
                        {
                            try
                            {
                                query  += up.UploadTo(queryType, dictionary["searchNearBy"]);
                                HasFile = true;
                            }
                            catch { }
                        }
                        else
                        {
                            try
                            {
                                query += up.UploadTo(dictionary["radecTextarea"], queryType, dictionary["searchNearBy"]);
                                if (dictionary["radecTextarea"].Length > 0)
                                {
                                    HasRaDecText = true;
                                }
                            }
                            catch { }
                        }
                        if (!HasRaDecText && !HasFile)
                        {
                            //query = "SELECT 'ERROR: Neither upload file nor list specified for Proximity search.'--";
                            throw new ArgumentException("Neither upload file nor list specified for Proximity search.");
                        }
                    }
                }
                catch { throw; }

                //query += QueryTools.BuildQuery.buildQuery(queryType, dictionary, positionType);

                QueryTools.BuildQuery.buildQueryMaster(queryType, dictionary, positionType);
                ExtraInfo["QueryForUserDisplay"] = query + QueryTools.BuildQuery.QueryForUserDisplay;
                query += QueryTools.BuildQuery.query;
                query  = query.Replace("'", "''");
                query  = "EXEC spExecuteSQL '" + query + "', @webserver='" + this.server_name + "', @winname='" + this.windows_name + "', @clientIP='" + this.ClientIP + "', @access='" + this.TaskName + "', @filter=0, @log=1";

                //RunCasjobs run = new RunCasjobs();
                //resp.Content = new StringContent(run.postCasjobs(query, token, casjobsMessage).Content.ReadAsStringAsync().Result);
                //return resp;
                String format = "";
                try
                {
                    if (format.Equals(""))
                    {
                        format = dictionary["format"].ToLower();
                    }

                    switch (format)
                    {
                    case "csv": format = KeyWords.contentCSV; ExtraInfo.Add("FormatFromUser", format); break;

                    case "xml": format = KeyWords.contentXML; ExtraInfo.Add("FormatFromUser", format); break;

                    case "votable": format = KeyWords.contentVOTable; ExtraInfo.Add("FormatFromUser", format); break;

                    case "json": format = KeyWords.contentJson; ExtraInfo.Add("FormatFromUser", format); break;

                    case "fits": format = KeyWords.contentFITS; ExtraInfo.Add("FormatFromUser", format); break;

                    case "dataset": format = KeyWords.contentDataset; ExtraInfo.Add("FormatFromUser", format); break;

                    case "html": format = KeyWords.contentDataset; ExtraInfo.Add("FormatFromUser", "html"); break;

                    case "mydb":
                        ExtraInfo.Add("FormatFromUser", format); format = "mydb"; break;

                    default: format = KeyWords.contentJson; ExtraInfo.Add("FormatFromUser", format); break;
                    }
                }
                catch (Exception exp)
                {
                    format = KeyWords.contentCSV;
                    ExtraInfo.Add("FormatFromUser", KeyWords.contentCSV);
                }


                //logging -----------------------------------------------------------------------------------------------------------------------
                if (ActivityInfo == null)
                {
                    ActivityInfo          = new LoggedInfo();
                    ActivityInfo.ClientIP = ClientIP;
                    ActivityInfo.TaskName = TaskName;
                    ActivityInfo.Headers  = api.ControllerContext.Request.Headers;
                }

                //creating the message that is being logged
                ActivityInfo.Message = rm.GetLoggedMessage(ExtraInfo["QueryForUserDisplay"]);   //request.ToString();

                //return new RunCasjobs(query, token, casjobsMessage, format, datarelease);
                //return new RunDBquery(query, format, this.TaskName, ExtraInfo);return new RunCasjobs(query, token, this.TaskName, format, datarelease, ExtraInfo, this.ClientIP);
                return(new RunDBquery(query, format, this.TaskName, ExtraInfo, ActivityInfo, queryType, positionType));
            }
            catch (Exception exp)
            {
                throw new Exception("Error while uploading coordinates to create a temporary table. " + exp.Message);
            }
        }