Пример #1
0
        public async void runSDSSFields(double ra, double dec, double sr)
        {
            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(KeyWords.casjobsREST + "contexts/" + datarelease + "/query");
            NewSDSSFields newsdss = new NewSDSSFields(ra, dec, sr);
            String        query   = newsdss.getFieldsArrayQuery();
            StringContent content = new StringContent(this.getJsonContent(query, casjobstaskname));

            content.Headers.ContentType = new MediaTypeHeaderValue(KeyWords.contentJson);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(KeyWords.contentDataset));
            System.IO.Stream stream = await client.PostAsync(client.BaseAddress, content).Result.Content.ReadAsStreamAsync();

            BinaryFormatter formatter = new BinaryFormatter();
            DataSet         ds;

            try
            {
                ds = (DataSet)formatter.Deserialize(stream);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            fieldArray = newsdss.FieldArray(ds);
        }
Пример #2
0
        public HttpContent GetContent(DataSet ds)
        {
            var    response   = new HttpResponseMessage();
            string SaveResult = "";

            ExtraInfo.TryGetValue("SaveResult", out SaveResult);


            if (this.IsSuccess)
            {
                if (this.ExtraInfo["FormatFromUser"] != "html")
                {
                    NewSDSSFields sf = new NewSDSSFields();
                    switch (positionType)
                    {
                    case "cone":
                        DefaultCone cstest = new DefaultCone();
                        vot = cstest.ConeSearch(ds);
                        response.Content = new StringContent(ToXML(vot), Encoding.UTF8, KeyWords.contentXML);
                        if (SaveResult == "true")
                        {
                            response.Content.Headers.Add("Content-Disposition", "attachment;filename=\"result.xml\"");
                        }
                        break;

                    case "FieldArray":

                        response.Content = new StringContent(ToXML(sf.FieldArray(ds)), Encoding.UTF8, KeyWords.contentXML);
                        if (SaveResult == "true")
                        {
                            response.Content.Headers.Add("Content-Disposition", "attachment;filename=\"result.xml\"");
                        }

                        break;

                    case "FieldArrayRect":

                        response.Content = new StringContent(ToXML(sf.FieldArrayRect(ds)), Encoding.UTF8, KeyWords.contentXML);
                        if (SaveResult == "true")
                        {
                            response.Content.Headers.Add("Content-Disposition", "attachment;filename=\"result.xml\"");
                        }

                        break;

                    case "ListOfFields":

                        response.Content = new StringContent(ToXML(sf.ListOfFields(ds)), Encoding.UTF8, KeyWords.contentXML);
                        if (SaveResult == "true")
                        {
                            response.Content.Headers.Add("Content-Disposition", "attachment;filename=\"result.xml\"");
                        }

                        break;

                    case "UrlsOfFields":

                        response.Content = new StringContent(ToXML(sf.UrlOfFields(ds)), Encoding.UTF8, KeyWords.contentXML);
                        if (SaveResult == "true")
                        {
                            response.Content.Headers.Add("Content-Disposition", "attachment;filename=\"result.xml\"");
                        }

                        break;

                    default:
                        Action <Stream, HttpContent, TransportContext> WriteToStream = null;
                        BinaryFormatter fmt;
                        ds.RemotingFormat = SerializationFormat.Binary;
                        fmt              = new BinaryFormatter();
                        WriteToStream    = (stream, foo, bar) => { fmt.Serialize(stream, ds); stream.Close(); };
                        response.Content = new PushStreamContent(WriteToStream, new MediaTypeHeaderValue((KeyWords.contentDataset)));
                        break;
                    }
                }
                else
                {
                    response.Content = new StringContent(getHtmlContent(ds));
                }
            }
            else // not IsSuccess
            {
                if (ExtraInfo["DoReturnHtml"].ToLower() == "true")
                {
                    response.Content = new StringContent(getHtmlError(ErrorMessage));
                }
                else
                {
                    if (String.IsNullOrEmpty(TechnicalErrorInfo))
                    {
                        response.Content = new StringContent(ErrorMessage);
                    }
                    else
                    {
                        response.Content = new StringContent(ErrorMessage + " \nTechnical Info:" + TechnicalErrorInfo);
                    }
                }
            }
            return(response.Content);
        }
Пример #3
0
        /// <summary>
        /// Executes the query for most kinds of searches (except proximity)
        /// </summary>
        /// <param name="api">The API controller.</param>
        /// <param name="queryType">Type of the query</param>
        /// <param name="positionType">Type of the position.</param>
        /// <param name="Task">The TaskName, that uniquely identifies the search (or web service entry point).</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">Check input parameters properly.\n+e.Message</exception>
        public IHttpActionResult runquery(ApiController api, string queryType, string positionType, string Task)
        {
            //api.Request.Headers.Add("TaskName", Task);
            //api.Request.Headers.Add("EntryPoint", Task);


            DataSet ResultsDataSet = new DataSet();

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

/*
 *          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);
 *          }
 */
            String format = "";
            String query  = "";

            /*
             * 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, Task);// must be executed right after GetClientIP(ref dictionary);
             * if (string.IsNullOrEmpty(this.server_name))
             *  try { this.server_name = HttpContext.Current.Request.ServerVariables["SERVER_NAME"]; }
             *  catch { }
             * if (string.IsNullOrEmpty(this.windows_name))
             *  try { this.windows_name = System.Environment.MachineName; }
             *  catch { };
             */


            switch (queryType)
            {
            case "UserHistory":
                UserHistory history = new UserHistory(dictionary, ExtraInfo, HttpContext.Current.Request);
                ResultsDataSet = history.ResultDataSet;
                ExtraInfo["QueryForUserDisplay"] = history.query;
                ExtraInfo["query"] = history.query;
                //DataTable dt = new DataTable();
                //dt.Columns.Add("query", typeof(string));
                //dt.Rows.Add(new object[] { history.query });
                //ResultsDataSet.Merge(dt);
                break;

            case "SqlSearch":
                SqlSearch sqlsearch = new SqlSearch(dictionary, ExtraInfo);
                query = sqlsearch.query;     // here the query is wrapped inside SpExecuteSQL, both logging and security checking
                ExtraInfo["syntax"] = sqlsearch.syntax;
                ExtraInfo["QueryForUserDisplay"] = sqlsearch.QueryForUserDisplay;
                ExtraInfo["query"] = query;
                break;

            case "CrossIdSearch":
                CrossIdSearch crossId = new CrossIdSearch(dictionary, ExtraInfo, HttpContext.Current.Request, api.Request.Content);
                query = crossId.query;     // // here the query is wrapped inside SpExecuteSQL, both logging and security checking of the user query part.
                //Format = crossId.Format;
                ExtraInfo["QueryForUserDisplay"] = crossId.QueryForUserDisplay;
                ExtraInfo["query"] = query;
                break;

            case "ObjectSearch":    // here, multiple queries might be run in order to resolve the object. That's why we have to run them here and get the dataset immediately (no routing to RunDBquery but to SendTables);
                ObjectSearch objectSearch = new ObjectSearch(dictionary, ExtraInfo, HttpContext.Current.Request);
                ResultsDataSet = objectSearch.ResultDataSet;
                //Format = objectSearch.Format;
                break;

            case "RectangularSearch":
                RectangularSearch rectangular = new RectangularSearch(dictionary, ExtraInfo);
                query = rectangular.query;
                ExtraInfo["QueryForUserDisplay"] = rectangular.QueryForUserDisplay;
                ExtraInfo["query"] = query;
                break;

            case "RadialSearch":
                RadialSearch radial = new RadialSearch(dictionary, ExtraInfo);
                query           = radial.query;
                ExtraInfo["fp"] = radial.fp;
                ExtraInfo["QueryForUserDisplay"] = radial.QueryForUserDisplay;
                ExtraInfo["query"] = query;
                break;

            case "ConeSearch":
                try
                {
                    format = dictionary["format"].ToLower();
                    if (format.Equals("votable"))
                    {
                        format = "dataset";
                    }
                }
                catch (Exception e)
                {
                    format = "dataset";     // or votable
                }
                ConeSearch.ConeSearch cs = new ConeSearch.ConeSearch(dictionary);
                query = cs.getConeSearchQuery();
                ExtraInfo["QueryForUserDisplay"] = query;
                ExtraInfo["query"] = query;
                break;

            case "SDSSFields":
                try
                {
                    format = dictionary["format"].ToLower();
                    if (format.Equals("votable"))
                    {
                        format = "dataset";
                    }
                }
                catch (Exception e)
                {
                    format = "dataset";
                }
                NewSDSSFields sf = new NewSDSSFields(dictionary, positionType);
                query = sf.sqlQuery;
                ExtraInfo["QueryForUserDisplay"] = query;
                ExtraInfo["query"] = query;
                break;

            case "SIAP":
                ActivityInfo.Message = rm.GetLoggedMessage(ExtraInfo["QueryForUserDisplay"]);                  //request.ToString();
                return(new ReturnSIAPresults(positionType, "VOTable", datarelease, dictionary, ActivityInfo)); // this is tricky code

                break;

            default:    // runs all the Imaging, Spectro and SpectroIR queries in SkyServer
                QueryTools.BuildQuery.buildQueryMaster(queryType, dictionary, positionType);
                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";
                ExtraInfo["QueryForUserDisplay"] = QueryTools.BuildQuery.QueryForUserDisplay;
                ExtraInfo["query"] = query;
                break;
            }

            query = Regex.Replace(query, @"\/\*(.*\n)*\*\/", "");                                       // remove all multi-line comments
            query = Regex.Replace(query, @"^[ \t\f\v]*--.*\r\n", "", RegexOptions.Multiline);           // remove all isolated single-line comments
            query = Regex.Replace(query, @"--[^\r^\n]*", "");                                           // remove all embedded single-line comments
            query = Regex.Replace(query, @"[ \t\f\v]+", " ");                                           // replace multiple whitespace with single space
            query = Regex.Replace(query, @"^[ \t\f\v]*\r\n", "", RegexOptions.Multiline);               // remove empty lines
            try
            {
                if (format.Equals(""))
                {
                    format = dictionary["format"].ToLower();
                }

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

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

                case "votable":
                case "application/x-votable+xml":
                    ExtraInfo.Add("FormatFromUser", format); format = KeyWords.contentVOTable; break;

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

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

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

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

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

                default:
                    ExtraInfo.Add("FormatFromUser", format); format = KeyWords.contentJson; break;
                }
            }
            catch (Exception exp)
            {
                if (IsDirectUserConnection)//in case the user did not specify a format
                {
                    format = KeyWords.contentJson;
                    string val;
                    if (!ExtraInfo.TryGetValue("FormatFromUser", out val))
                    {
                        ExtraInfo.Add("FormatFromUser", "json");
                    }
                }
                else
                {
                    format = KeyWords.contentDataset;//which is a dataset
                    string val;
                    if (!ExtraInfo.TryGetValue("FormatFromUser", out val))
                    {
                        ExtraInfo.Add("FormatFromUser", "dataset");
                    }
                }
            }


            //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();

            switch (queryType)
            {
            case "SqlSearch":
                return(new RunDBquery(query, format, TaskName, ExtraInfo, ActivityInfo, queryType, positionType));   // queries are sent through direct database connection.

            case "ObjectSearch":
            case "UserHistory":
                return(new SendTables(ResultsDataSet, format, ActivityInfo, ExtraInfo));

            default:
                return(new RunDBquery(query, format, TaskName, ExtraInfo, ActivityInfo, queryType, positionType));
            }
        }