Example #1
0
        public void GetValuesTest()
        {
            GetValuesDailyUSGS target = new GetValuesDailyUSGS();

            NwisWOFTest.NwisWOFService_GetValuesUSGSAccessor accessor = new NwisWOFTest.NwisWOFService_GetValuesUSGSAccessor(target);

            locationParam Location = new locationParam("NWIS:10263500");


            VariableParam Variable = new VariableParam("NWIS:00060");

            System.Nullable <WaterOneFlowImpl.W3CDateTime> BeginDateTime
                = new W3CDateTime(DateTime.Parse("2005-08-01"));


            System.Nullable <WaterOneFlowImpl.W3CDateTime> EndDateTime =
                new W3CDateTime(DateTime.Parse("2006-08-01"));


            //TimeSeriesResponseType expected = null;
            TimeSeriesResponseType actual;

            actual = accessor.GetValues(Location, Variable, BeginDateTime, EndDateTime);

            Assert.IsNotNull(actual, "NwisWOFService.GetValuesUSGS.GetValues returned null.");

            // (expected, actual, "NwisWOFService.GetValuesUSGS.GetValues did not return the expected value.");
            // Assert.Inconclusive("Verify the correctness of this test method.");
        }
Example #2
0
        public InitAckChunk(ChunkType type, byte flags, int length, ByteBuffer pkt)
            : base(type, flags, length, pkt)
        {
            if (_body.remaining() >= 16)
            {
                _initiateTag    = _body.GetInt();
                _adRecWinCredit = _body.GetUInt();
                ;
                _numOutStreams = _body.GetUShort();
                _numInStreams  = _body.GetUShort();
                _initialTSN    = _body.GetUInt();
                logger.LogDebug("Init Ack" + this.ToString());
                while (_body.hasRemaining())
                {
                    VariableParam v = readVariable();
                    _varList.Add(v);
                }

                foreach (VariableParam v in _varList)
                {
                    // now look for variables we are expecting...
                    //logger.LogDebug("variable of type: " + v.getName() + " " + v.ToString());
                    if (typeof(StateCookie).IsAssignableFrom(v.GetType()))
                    {
                        _cookie = ((StateCookie)v).getData();
                    }

                    //else
                    //{
                    //    logger.LogDebug("ignored variable of type: " + v.getName());
                    //}
                }
            }
        }
            public override object GetTimeSeries(
                locationParam lp,
                VariableParam vp,
                Nullable <W3CDateTime> startDate,
                Nullable <W3CDateTime> endDate)
            {
                if (lp.isGeometry)
                {
                    throw new WaterOneFlowException("Geometry not supported ");
                }

                TimeSeriesResponseType result = null;

                string[] StationsList = new string[] { lp.SiteCode };

                result = CuahsiBuilder.CreateTimeSeriesObject();

                result.queryInfo.criteria.locationParam = lp.ToString();
                result.queryInfo.criteria.variableParam = vp.ToString();

                result.timeSeries.sourceInfo = DataInfoService.GetSite(lp);

                // not fully correct, but just choose the first one.
                VariableInfoType[] vits = DataInfoService.GetVariableInfoObject(vp);
                result.timeSeries.variable = vits[0];
                string aURL = InstantaneousData(startDate, endDate,
                                                new string[] { vp.Code }, StationsList, USGSCommon.option2AgencyCode(lp));

                try
                {
                    result.timeSeries.values =
                        CreateWQTimeSeriesObject(vp, aURL);
                }
                catch (WaterOneFlowException e)
                {
                    throw;
                }
                catch (WaterOneFlowSourceException e)
                {
                    throw;
                }
                catch (Exception e)
                {
                    log.Error(e.Message + e.StackTrace);
                    throw new WaterOneFlowException("An External resource failed.", e);
                }

                List <NoteType> notes   = new List <NoteType>();
                NoteType        urlNote = new NoteType();

                urlNote.title = "USGS URL";
                urlNote.Value = aURL;
                notes.Add(urlNote);
                result.queryInfo.note = notes.ToArray();

                return(result);
            }
Example #4
0
            private string option2AgencyCode(VariableParam vp)
            {
                string usgsAgencyCode = agencyCodeDefault;

                if (vp.options.ContainsKey("agency"))
                {
                    usgsAgencyCode = vp.options["agency"];
                }
                return(usgsAgencyCode);
            }
Example #5
0
            private static string option2UsgsStatCode(VariableParam vp)
            {
                string usgsStatCode = null;

                if (vp.options.ContainsKey("statistic"))
                {
                    usgsStatCode = vp.options["statistic"];
                }
                else if (vp.options.ContainsKey("datatype"))
                {
                    Hashtable statMap = new Hashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant,
                                                      CaseInsensitiveComparer.DefaultInvariant);
                    statMap.Add("average", "00003");
                    statMap.Add("minimum", "00002");
                    statMap.Add("maximum", "00001");
                    statMap.Add("Cumulative", "00006");
                    statMap.Add("median", "00008");
                    statMap.Add("variance", "00010");
                    statMap.Add("instantaneous", "00011");

                    /* not defined by ODM
                     * statMap.Add("mode",  "00007");
                     * statMap.Add("STD",  "00009");
                     * statMap.Add("SKEWNESS",  "00013");
                     */
                    string stat = vp.options["datatype"];
                    if (statMap.ContainsKey(stat))
                    {
                        usgsStatCode = (string)statMap[stat];
                    }
                    else
                    {
/* unrecognized code...
 * send an ERROR back
 *   build a list of possible values
 * reutrn error
 * */
                        StringBuilder statNames = new StringBuilder();
                        foreach (String key in statMap.Keys)
                        {
                            //   build a list of possible values
                            statNames.AppendFormat(" '{0}'", key);
                        }
                        throw new WaterOneFlowException("Bad datatype option: " +
                                                        "Only Accepted names:" +
                                                        statNames.ToString());
                    }
                }
                else
                {
                    usgsStatCode = statCodeDefault;
                }

                return(usgsStatCode);
            }
Example #6
0
 public ErrorChunk(ChunkType type, byte flags, int length, ByteBuffer pkt) : base(type, flags, length, pkt)
 {
     if (_body.remaining() >= 4)
     {
         //logger.LogDebug("Error" + this.ToString());
         while (_body.hasRemaining())
         {
             VariableParam v = readErrorParam();
             _varList.Add(v);
         }
     }
 }
 public HeartBeatChunk(ChunkType type, byte flags, int length, ByteBuffer pkt)
     : base(type, flags, length, pkt)
 {
     if (_body.remaining() >= 4)
     {
         while (_body.hasRemaining())
         {
             VariableParam v = readVariable();
             _varList.Add(v);
         }
     }
 }
Example #8
0
            private TsValuesSingleVariableType CreateGWTimeSeriesObject(VariableParam vp, string aURL)
            {
                // download the iformation
                String resultFile = USGSCommon.GetHTTPFile(aURL, 10);

                TsValuesSingleVariableType values = new TsValuesSingleVariableType();
                //result.TimeSeries.Values.valueUnits = units; // this needs to be done earlier


                DataTable aTable = NWISDelimitedTextParser.ParseFileIntoDT(resultFile);

                // dwv add code to get the code, and use that to find the correct columns
                int    time = 2; // present location of time column
                String code = vp.Code;
                String stat = null;
                int    aValue;
                int    qualifier;

                //if (result.timeSeries.variable.options != null)
                //{
                //    stat = result.timeSeries.variable.options[0].Value;
                //}
                try
                {
                    aValue    = USGSCommon.getVarColumn(aTable, "lev_va", null); // uses eEndWith... so this should work
                    qualifier = USGSCommon.getVarQualifiersColumn(aTable, "lev_status_cd", null);
                }
                catch (WaterOneFlowException we)
                {
                    // need to insert the URL in the exception
                    if (string.IsNullOrEmpty(stat))
                    {
                        throw new WaterOneFlowException("URL: '" + aURL, we);
                        //+"' variable '"+code+"' not found at site.");
                    }
                    else
                    {
                        throw new WaterOneFlowException("URL: '" + aURL, we);
                        //+ "' variable '"+code+"' statistic '"+stat +"' not found at site. Try not using the statistic", we);
                    }
                }

                List <ValueSingleVariable> tsTypeList = new List <ValueSingleVariable>();

                //TimeSeriesFromRDB(aTable, time, aValue, qualifier, tsTypeList);

                USGSCommon.TimeSeriesFromRDB(aTable, time, aValue, qualifier, tsTypeList, false);

                values.count = tsTypeList.Count;
                values.value = tsTypeList.ToArray();

                return(values);
            }
Example #9
0
            public override TimeSeriesResponseTypeGeneric GetValuesObject(string location, string variable, string startDate, string endDate, String authToken)
            {
                if (!useODForValues)
                {
                    throw new SoapException("GetValues implemented external to this service. Call GetSiteInfo, and SeriesCatalog includes the service Wsdl for GetValues. Attribute:serviceWsdl on Element:seriesCatalog XPath://seriesCatalog/[@serviceWsdl]", new XmlQualifiedName("ServiceException"));
                }

                Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();

                queryLog2.LogValuesStart(Logging.Methods.GetValues, // method
                                         location,                  //location
                                         variable,                  //variable
                                         startDate,                 // startdate
                                         startDate,                 //enddate
                                         Context.Request.UserHostName);

                try
                {
                    WaterOneFlowImpl.locationParam lParam = new locationParam(location);
                    VariableParam vparam  = new VariableParam(variable);
                    W3CDateTime?  startDt = null;
                    W3CDateTime?  endDt   = null;
                    if (!String.IsNullOrEmpty(startDate))
                    {
                        startDt = new W3CDateTime(DateTime.Parse(startDate));
                    }
                    if (!String.IsNullOrEmpty(endDate))
                    {
                        endDt = new W3CDateTime(DateTime.Parse(endDate));
                    }


                    TimeSeriesResponseTypeObject res = (TimeSeriesResponseTypeObject)dvSvc.GetTimeSeries(lParam, vparam, startDt, endDt);

                    return(new xsd.TimeSeriesResponse(res));

                    //throw new NotImplementedException("Reimplement 1.1");
                }
                catch (Exception we)
                {
                    log.Warn(we.Message);
                    queryLog2.LogValuesEnd(Logging.Methods.GetValues,
                                           location,                  //locaiton
                                           variable,                  //variable
                                           startDate,                 // startdate
                                           startDate,                 //enddate
                                           timer.ElapsedMilliseconds, // processing time
                                           -9999,                     // count
                                           Context.Request.UserHostName
                                           );
                    throw SoapExceptionGenerator.WOFExceptionToSoapException(we);
                }
            }
            public VariablesResponseType GetVariableInfoObject(string Variable, String authToken)
            {
                Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();

                queryLog2.LogStart(Logging.Methods.GetVariables, Variable,
                                   Context.Request.UserHostName);

                try
                {
                    VariableParam[] vars = null;
                    if (!String.IsNullOrEmpty(Variable))
                    {
                        vars = new VariableParam[1];

                        VariableParam vp = new VariableParam(Variable);
                        vars[0] = vp;
                    }
                    VariablesResponseType res = ODws.GetVariables(vars);

                    // don't always have variables
                    if (res.variables != null)
                    {
                        queryLog2.LogEnd(Logging.Methods.GetVariables,
                                         Variable,
                                         timer.ElapsedMilliseconds.ToString(),
                                         res.variables.Length.ToString(),
                                         Context.Request.UserHostName);
                    }
                    else
                    {
                        queryLog2.LogEnd(Logging.Methods.GetVariables,
                                         Variable,
                                         timer.ElapsedMilliseconds.ToString(),
                                         "0",
                                         Context.Request.UserHostName);
                    }


                    return(res);
                }
                catch (Exception we)
                {
                    log.Warn(we.Message);
                    queryLog2.LogEnd(Logging.Methods.GetVariables,
                                     Variable,
                                     timer.ElapsedMilliseconds.ToString(),
                                     "-9999",
                                     Context.Request.UserHostName);

                    throw SoapExceptionGenerator.WOFExceptionToSoapException(we);
                }
            }
Example #11
0
            /// <summary>
            /// Returns the statistic code for the USGS daily values
            /// Assumes that all daily
            /// </summary>
            /// <param name="vp"></param>
            /// <returns></returns>
            private static string option2UsgsStatCode(VariableParam vp)
            {
                string usgsStatCode = null;

                if (vp.options.ContainsKey("statistic"))
                {
                    usgsStatCode = vp.options["statistic"];
                }
                else if (vp.options.ContainsKey("datatype"))
                {
                    //Hashtable statMap = new Hashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant,
                    //    CaseInsensitiveComparer.DefaultInvariant);
                    //statMap.Add("average", "00003");
                    //statMap.Add("minimum", "00002");
                    //statMap.Add("maximum", "00001");
                    //statMap.Add("Cumulative", "00006");
                    //statMap.Add("median", "00008");
                    //statMap.Add("variance", "00010");
                    //statMap.Add("instantaneous", "00011");
                    ///* not defined by ODM
                    //statMap.Add("mode",  "00007");
                    //statMap.Add("STD",  "00009");
                    //statMap.Add("SKEWNESS",  "00013");
                    // */

                    string stat = vp.options["datatype"];
                    // if (statMap.ContainsKey(stat))
                    if (UsgsStatistic.Code.ContainsKey(stat))
                    {
                        usgsStatCode = UsgsStatistic.Code[stat];
                    }
                    else
                    {
                        // for daily values... we need to send a stat code
                        // usgsStatCode = defaultStatCode;
                        StringBuilder statNames = new StringBuilder();
                        foreach (String key in UsgsStatistic.Code.Keys)
                        {
                            statNames.AppendFormat(" '{0}'", key);
                        }
                        throw new WaterOneFlowException("Bad datatype option: " +
                                                        "Only Accepted names:" +
                                                        statNames.ToString());
                    }
                }
                else
                {
                    usgsStatCode = statCodeDefault;
                }

                return(usgsStatCode);
            }
Example #12
0
 public AbortChunk(CType type, byte flags, int length, ByteBuffer pkt)
     : base(type, flags, length, pkt)
 {
     if (_body.remaining() >= 4)
     {
         Logger.Trace("Abort" + this.ToString());
         while (_body.hasRemaining())
         {
             VariableParam v = readErrorParam();
             _varList.Add(v);
         }
     }
 }
 public ReConfigChunk(ChunkType type, byte flags, int length, ByteBuffer pkt)
     : base(type, flags, length, pkt)
 {
     //logger.LogDebug("ReConfig chunk" + this.ToString());
     if (_body.remaining() >= 4)
     {
         while (_body.hasRemaining())
         {
             VariableParam v = this.readVariable();
             _varList.Add(v);
             //logger.LogDebug("\tParam :" + v.ToString());
         }
     }
 }
Example #14
0
        private string VariableOptions2WhereClause(VariableParam vp)
        {
            /*
             * Use Caution, not SQL inject sade.
             * But safe, since it is used to generate a where clause
             * for an unattached ADO.NET dataset.
             *
             */

            /* this allows for renaming of the option values,
             * case insensetive comparison
             * multiple data types in where
             * */
            Dictionary <string, string> stringConstraints = new Dictionary <string, string>(StringComparer.CurrentCultureIgnoreCase);

            stringConstraints.Add("statistic", "stat_cd");
            stringConstraints.Add("datatype", "DataType");
            stringConstraints.Add("samplemedium", "SampleMedium");

            Dictionary <string, string> numericConstraints = new Dictionary <string, string>(StringComparer.CurrentCultureIgnoreCase);

            numericConstraints.Add("variableID", "VariableID");

            StringBuilder where = new StringBuilder();
            int constraintCount = 0;

            foreach (string opt in vp.options.Keys)
            {
                if (stringConstraints.ContainsKey(opt))
                {
                    if (constraintCount > 0)
                    {
                        where.Append(" AND ");
                    }
                    where.AppendFormat(" {0} = '{1}' ", stringConstraints[opt], vp.options[opt]);
                    constraintCount++;
                }
                if (numericConstraints.ContainsKey(opt))
                {
                    if (constraintCount > 0)
                    {
                        where.Append(" AND ");
                    }
                    where.AppendFormat(" {0} = {1} ", numericConstraints[opt], vp.options[opt]);
                    constraintCount++;
                }
            }
            return(where.ToString());
        }
Example #15
0
        public void option2UsgsStatCodeTest5()
        {
            VariableParam vp = new VariableParam("NWIS:00060/ValueType=Maximum");


            string expected = "00001";
            string actual;

            actual = NwisWOFTest.NwisWOFService_GetValuesUSGSAccessor.option2UsgsStatCode(vp);

            Assert.AreEqual(expected, actual,
                            "NwisWOFService.GetValuesUSGS.option2UsgsStatCode did not return the expected valu" +
                            "e.");
            // Assert.Inconclusive("Verify the correctness of this test method.");
        }
Example #16
0
        public InitChunk(ChunkType type, byte flags, int length, ByteBuffer pkt)
            : base(type, flags, length, pkt)
        {
            if (_body.remaining() >= 16)
            {
                _initiateTag    = _body.GetInt();
                _adRecWinCredit = _body.GetUInt();
                _numOutStreams  = _body.GetUShort();
                _numInStreams   = _body.GetUShort();
                _initialTSN     = _body.GetUInt();
                //logger.LogDebug("Init " + this.ToString());
                while (_body.hasRemaining())
                {
                    VariableParam v = readVariable();
                    _varList.Add(v);
                }

                foreach (VariableParam v in _varList)
                {
                    // now look for variables we are expecting...
                    //logger.LogDebug("variable of type: " + v.getName() + " " + v.ToString());
                    if (typeof(SupportedExtensions).IsAssignableFrom(v.GetType()))
                    {
                        _farSupportedExtensions = ((SupportedExtensions)v).getData();
                    }
                    else if (typeof(RandomParam).IsAssignableFrom(v.GetType()))
                    {
                        _farRandom = ((RandomParam)v).getData();
                    }
                    else if (typeof(ForwardTSNsupported).IsAssignableFrom(v.GetType()))
                    {
                        _farForwardTSNsupported = true;
                    }
                    else if (typeof(RequestedHMACAlgorithmParameter).IsAssignableFrom(v.GetType()))
                    {
                        _farHmacs = ((RequestedHMACAlgorithmParameter)v).getData();
                    }
                    else if (typeof(ChunkListParam).IsAssignableFrom(v.GetType()))
                    {
                        _farChunks = ((ChunkListParam)v).getData();
                    }
                    else
                    {
                        //logger.LogDebug("unexpected variable of type: " + v.getName());
                    }
                }
            }
        }
Example #17
0
            public override object GetTimeSeries(locationParam location, VariableParam variable, W3CDateTime?startDate, W3CDateTime?endDate)
            {
                if (DataInfoService == null)
                {
                    throw new Exception("You Must set the DataInfoService");
                }

                /* get SiteID and VariableID from dataInfoService
                 * Setup Query
                 * If boths dates valid use one query
                 * Else use second
                 *
                 */
                using (sqlConn)
                {
                    throw new System.NotImplementedException();
                }
            }
        public VariablesResponseType GetVariableInfo(string Variable)
        {
            VariableInfoType[] variableList;
            if (String.IsNullOrEmpty(Variable))
            {
                variableList = ODvariables.getVariables(new VariableParam[0], Variables);
            }
            else
            {
                VariableParam vp;
                vp           = new VariableParam(Variable);
                variableList = ODvariables.getVariable(vp, Variables);
            }

            if (variableList == null)
            {
                throw new WaterOneFlowException("Variable Not Found");
            }
            VariablesResponseType Response = new VariablesResponseType();

            Response.variables = variableList;

            if (Response.queryInfo == null)
            {
                Response.queryInfo          = new QueryInfoType();
                Response.queryInfo.criteria = new QueryInfoTypeCriteria();
            }
            Response.queryInfo.creationTime          = DateTime.UtcNow;
            Response.queryInfo.creationTimeSpecified = true;
            if (String.IsNullOrEmpty(Variable))
            {
                Response.queryInfo.criteria.variableParam = "NULL (Request for all variables";
            }
            else
            {
                Response.queryInfo.criteria.variableParam = Variable;
            }

            NoteType sourceNote = CuahsiBuilder.createNote("OD Web Service");

            Response.queryInfo.note = CuahsiBuilder.addNote(Response.queryInfo.note,
                                                            sourceNote);
            return(Response);
        }
            public VariablesResponseType GetVariableInfo(string Variable)
            {
                VariableInfoType[] variableList;
                if (String.IsNullOrEmpty(Variable))
                {
                    variableList = ODvariables.getVariables(new VariableParam[0], Variables);
                }
                else
                {
                    VariableParam vp;
                    vp           = new VariableParam(Variable);
                    variableList = ODvariables.getVariable(vp, Variables);
                }

                if (variableList == null)
                {
                    throw new WaterOneFlowException("Variable Not Found");
                }
                VariablesResponseType Response = new VariablesResponseType();

                Response.variables = variableList;

                Response.queryInfo = CuahsiBuilder.CreateQueryInfoType("GetVariableInfo", null, null,
                                                                       new string[] { Variable }, null, null);

                if (String.IsNullOrEmpty(Variable))
                {
                    CuahsiBuilder.addNote(Response.queryInfo.note,
                                          CuahsiBuilder.createNote("(Request for all variables"));
                }
                else
                {
                    Response.queryInfo.criteria.variableParam = Variable;
                }
                NoteType sourceNote = CuahsiBuilder.createNote("OD Web Service");

                Response.queryInfo.note = CuahsiBuilder.addNote(Response.queryInfo.note,
                                                                sourceNote);

                return(Response);
            }
            public VariablesResponseType GetVariableInfo(string Variable)
            {
                VariableInfoType[] variableList;
                if (String.IsNullOrEmpty(Variable))
                {
                    variableList = ODvariables.getVariables(new VariableParam[0], Variables);

                }
                else
                {
                    VariableParam vp;
                    vp = new VariableParam(Variable);
                    variableList = ODvariables.getVariable(vp, Variables);
                }

                if (variableList == null)
                {
                    throw new WaterOneFlowException("Variable Not Found");
                }
                VariablesResponseType Response = new VariablesResponseType();
                Response.variables = variableList;

                Response.queryInfo = CuahsiBuilder.CreateQueryInfoType("GetVariableInfo", null, null,
                                                                       new string[] {Variable}, null, null);

                if (String.IsNullOrEmpty(Variable))
                {
                  CuahsiBuilder.addNote(Response.queryInfo.note,
                      CuahsiBuilder.createNote("(Request for all variables")) ;
                }
                else
                {
                    Response.queryInfo.criteria.variableParam = Variable;
                }
                NoteType sourceNote = CuahsiBuilder.createNote("OD Web Service");
                Response.queryInfo.note = CuahsiBuilder.addNote(Response.queryInfo.note,
                                                                sourceNote);

                return Response;
            }
Example #21
0
            public object GetValuesObject(string location, string variable, string startDate, string endDate, String authToken)
            {
                if (!useODForValues)
                {
                    throw new SoapException("GetValues implemented external to this service. Call GetSiteInfo, and SeriesCatalog includes the service Wsdl for GetValues. Attribute:serviceWsdl on Element:seriesCatalog XPath://seriesCatalog/[@serviceWsdl]", new XmlQualifiedName("ServiceException"));
                }

                Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();

                queryLog2.LogValuesStart(Logging.Methods.GetValues, // method
                                         location,                  //location
                                         variable,                  //variable
                                         startDate,                 // startdate
                                         startDate,                 //enddate
                                         Context.Request.UserHostName);

                try
                {
                    WaterOneFlowImpl.locationParam lParam = new locationParam(location);
                    VariableParam vparam  = new VariableParam(variable);
                    W3CDateTime?  startDt = null;
                    W3CDateTime?  endDt   = null;
                    if (!String.IsNullOrEmpty(startDate))
                    {
                        startDt = new W3CDateTime(DateTime.Parse(startDate));
                    }
                    if (!String.IsNullOrEmpty(endDate))
                    {
                        endDt = new W3CDateTime(DateTime.Parse(endDate));
                    }

                    // see using statement above for full namespace
                    USGSwebService.TimeSeriesResponseType res = (NwisWOFService.gov.usgs.nwis.dailyValues.TimeSeriesResponseType)dvSvc.GetTimeSeries(lParam, vparam, startDt, endDt);

                    // minor editing, add network codes.
                    foreach (USGSwebService.TimeSeriesType ts in res.timeSeries)
                    {
                        if (ts.sourceInfo.GetType().Name.Contains("SiteInfoType"))
                        {
                            USGSwebService.SiteInfoType sit = (USGSwebService.SiteInfoType)ts.sourceInfo;
                            foreach (USGSwebService.SiteInfoTypeSiteCode sCode in sit.siteCode)
                            {
                                if (sCode.network == null && string.IsNullOrEmpty(sCode.network))
                                {
                                    sCode.network = ODws.SiteVocabulary;
                                }
                            }
                        }
                    }
                    // need to check is sourceInfo is of siteInfoType... but no siteInfoType
                    //NwisWOFService.gov.usgs.nwis.dailyValues.TimeSeriesType[] tst = res.timeSeries;
                    //if (tst[0].sourceInfo.GetType().IsInstanceOfType(NwisWOFService.gov.usgs.nwis.dailyValues.)
                    string count = "0";
                    if (res != null &&
                        res.timeSeries[0] != null &&
                        res.timeSeries[0].values[0].value != null)
                    {
                        count = res.timeSeries[0].values[0].value.Length.ToString();
                    }

                    queryLog2.LogEnd(Logging.Methods.GetValues,
                                     location,
                                     timer.ElapsedMilliseconds.ToString(),
                                     count,
                                     Context.Request.UserHostName);

                    return(new NWISTimeSeriesResponse(res));
                    //if (res != null && res.timeSeries != null &&
                    //    res.timeSeries.values != null &&
                    //    res.timeSeries.values.value != null)
                    //{
                    //    queryLog2.LogValuesEnd(Logging.Methods.GetValues,
                    //          location, //locaiton
                    //        variable, //variable
                    //        startDate, // startdate
                    //        startDate, //enddate
                    //        timer.ElapsedMilliseconds, // processing time
                    //        res.timeSeries.values.value.Length, // count
                    //         Context.Request.UserHostName
                    //         );
                    //}
                    //else
                    //{
                    //    queryLog2.LogValuesEnd(Logging.Methods.GetValues,
                    //             location, //locaiton
                    //             variable, //variable
                    //             startDate, // startdate
                    //             startDate, //enddate
                    //             timer.ElapsedMilliseconds, // processing time
                    //             0, // count
                    //             Context.Request.UserHostName
                    //             );
                    //}

                    //// add query info
                    //if (res.queryInfo == null) res.queryInfo = new QueryInfoType();
                    //res.queryInfo.creationTime = DateTime.Now.ToLocalTime();
                    //res.queryInfo.creationTimeSpecified = true;
                    //QueryInfoTypeCriteria crit = new QueryInfoTypeCriteria();
                    //if (String.IsNullOrEmpty(location))
                    //{
                    //    crit.locationParam = "none";
                    //}
                    //else
                    //{
                    //    crit.locationParam = location;
                    //}

                    //if (String.IsNullOrEmpty(variable))
                    //{
                    //    crit.locationParam = "none";
                    //}
                    //else
                    //{
                    //    crit.variableParam = variable;
                    //}
                    //crit.timeParam =
                    //    CuahsiBuilder.createQueryInfoTimeCriteria(startDate, endDate);

                    //res.queryInfo.criteria = crit;


                    //return res;
                }
                catch (Exception we)
                {
                    log.Warn(we.Message);
                    queryLog2.LogValuesEnd(Logging.Methods.GetValues,
                                           location,                  //locaiton
                                           variable,                  //variable
                                           startDate,                 // startdate
                                           startDate,                 //enddate
                                           timer.ElapsedMilliseconds, // processing time
                                           -9999,                     // count
                                           Context.Request.UserHostName
                                           );
                    throw SoapExceptionGenerator.WOFExceptionToSoapException(we);
                }
            }
 public void addParam(VariableParam rep)
 {
     //logger.LogDebug("adding " + rep + " to " + this);
     _varList.Add(rep);
     validate();
 }
        /*
         *         1.   Outgoing SSN Reset Request Parameter.
         *
         * 2.   Incoming SSN Reset Request Parameter.
         *
         * 3.   Outgoing SSN Reset Request Parameter, Incoming SSN Reset Request
         *              Parameter.
         *
         * 4.   SSN/TSN Reset Request Parameter.
         *
         * 5.   Add Outgoing Streams Request Parameter.
         *
         * 6.   Add Incoming Streams Request Parameter.
         *
         * 7.   Add Outgoing Streams Request Parameter, Add Incoming Streams
         *              Request Parameter.
         *
         * 8.   Re-configuration Response Parameter.
         *
         * 9.   Re-configuration Response Parameter, Outgoing SSN Reset Request
         *              Parameter.
         *
         * 10.  Re-configuration Response Parameter, Re-configuration Response
         *              Parameter.
         */
        public override void validate()
        {
            if (_varList.Count < 1)
            {
                throw new Exception("[IllegalArgumentException] Too few params " + _varList.Count);
            }
            if (_varList.Count > 2)
            {
                throw new Exception("[IllegalArgumentException] Too many params " + _varList.Count);
            }
            // now check for invalid combos
            if ((_varList.Count == 2))
            {
                if (this.hasOutgoingReset())
                {
                    VariableParam remain = null;
                    foreach (var v in _varList)
                    {
                        if (!typeof(OutgoingSSNResetRequestParameter).IsAssignableFrom(v.GetType()))
                        {
                            remain = v;
                            break;
                        }
                    }
                    if (remain == null)
                    {
                        throw new Exception("[IllegalArgumentException] 2 OutgoingSSNResetRequestParameter in one Chunk not allowed ");
                    }
                    if (!typeof(IncomingSSNResetRequestParameter).IsAssignableFrom(remain.GetType()) && //3
                        !typeof(ReconfigurationResponseParameter).IsAssignableFrom(remain.GetType()))    //9
                    {
                        throw new Exception("[IllegalArgumentException] OutgoingSSNResetRequestParameter and " + remain.GetType().Name + " in same Chunk not allowed ");
                    }
                }
                else if (this.hasOutgoingAdd())
                {
                    VariableParam remain = null;

                    foreach (var v in _varList)
                    {
                        if (!typeof(AddOutgoingStreamsRequestParameter).IsAssignableFrom(v.GetType()))
                        {
                            remain = v;
                            break;
                        }
                    }
                    if (remain == null)
                    {
                        throw new Exception("[IllegalArgumentException] 2 AddOutgoingStreamsRequestParameter in one Chunk not allowed ");
                    }
                    if (!typeof(AddIncomingStreamsRequestParameter).IsAssignableFrom(remain.GetType())) //7
                    {
                        throw new Exception("[IllegalArgumentException] OutgoingSSNResetRequestParameter and " + remain.GetType().Name + " in same Chunk not allowed ");
                    }
                }
                else if (this.hasResponse())
                {
                    VariableParam remain = null;

                    foreach (var v in _varList)
                    {
                        if (!typeof(ReconfigurationResponseParameter).IsAssignableFrom(v.GetType()))
                        {
                            remain = v;
                            break;
                        }
                    }

                    if (remain != null)
                    {
                        throw new Exception("[IllegalArgumentException] ReconfigurationResponseParameter and " + remain.GetType().Name + " in same Chunk not allowed ");
                    }
                }
            } // implicitly just one - which is ok 1,2,4,5,6,8
        }
Example #24
0
            public override object GetValuesObject(string location, string variable, string startDate, string endDate, String authToken)
            {
                if (!useODForValues)
                {
                    throw new SoapException("GetValues implemented external to this service. Call GetSiteInfo, and SeriesCatalog includes the service Wsdl for GetValues. Attribute:serviceWsdl on Element:seriesCatalog XPath://seriesCatalog/[@serviceWsdl]", new XmlQualifiedName("ServiceException"));
                }

                Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();

                queryLog2.LogValuesStart(Logging.Methods.GetValues, // method
                                         location,                  //location
                                         variable,                  //variable
                                         startDate,                 // startdate
                                         startDate,                 //enddate
                                         Context.Request.UserHostName);

                try
                {
                    WaterOneFlowImpl.locationParam lParam = new locationParam(location);
                    VariableParam vparam  = new VariableParam(variable);
                    W3CDateTime?  startDt = null;
                    W3CDateTime?  endDt   = null;
                    if (!String.IsNullOrEmpty(startDate))
                    {
                        startDt = new W3CDateTime(DateTime.Parse(startDate));
                    }
                    if (!String.IsNullOrEmpty(endDate))
                    {
                        endDt = new W3CDateTime(DateTime.Parse(endDate));
                    }


                    TimeSeriesResponseTypeObject res = (TimeSeriesResponseTypeObject)dvSvc.GetTimeSeries(lParam, vparam, startDt, endDt);

                    //if (res != null && res.timeSeries != null &&
                    //    res.timeSeries.values != null &&
                    //    res.timeSeries.values.value != null)
                    //{
                    //    queryLog2.LogValuesEnd(Logging.Methods.GetValues,
                    //          location, //locaiton
                    //        variable, //variable
                    //        startDate, // startdate
                    //        startDate, //enddate
                    //        timer.ElapsedMilliseconds, // processing time
                    //        res.timeSeries.values.value.Length, // count
                    //         Context.Request.UserHostName
                    //         );
                    //}
                    //else
                    //{
                    //    queryLog2.LogValuesEnd(Logging.Methods.GetValues,
                    //             location, //locaiton
                    //             variable, //variable
                    //             startDate, // startdate
                    //             startDate, //enddate
                    //             timer.ElapsedMilliseconds, // processing time
                    //             0, // count
                    //             Context.Request.UserHostName
                    //             );
                    //}

                    //// add query info
                    //if (res.queryInfo == null) res.queryInfo = new QueryInfoType();
                    //res.queryInfo.creationTime = DateTime.Now.ToLocalTime();
                    //res.queryInfo.creationTimeSpecified = true;
                    //QueryInfoTypeCriteria crit = new QueryInfoTypeCriteria();
                    //if (String.IsNullOrEmpty(location))
                    //{
                    //    crit.locationParam = "none";
                    //}
                    //else
                    //{
                    //    crit.locationParam = location;
                    //}

                    //if (String.IsNullOrEmpty(variable))
                    //{
                    //    crit.locationParam = "none";
                    //}
                    //else
                    //{
                    //    crit.variableParam = variable;
                    //}
                    //crit.timeParam =
                    //    CuahsiBuilder.createQueryInfoTimeCriteria(startDate, endDate);

                    //res.queryInfo.criteria = crit;


                    //return res;
                    return(new WaterOneFlow.Service.v1_0.xsd.TimeSeriesResponse(res));
                }
                catch (Exception we)
                {
                    log.Warn(we.Message);
                    queryLog2.LogValuesEnd(Logging.Methods.GetValues,
                                           location,                  //locaiton
                                           variable,                  //variable
                                           startDate,                 // startdate
                                           startDate,                 //enddate
                                           timer.ElapsedMilliseconds, // processing time
                                           -9999,                     // count
                                           Context.Request.UserHostName
                                           );
                    throw SoapExceptionGenerator.WOFExceptionToSoapException(we);
                }
            }
Example #25
0
            public override object GetVariableInfoObject(string variable, String authToken)
            {
                Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();

                queryLog2.LogStart(Logging.Methods.GetVariables, variable,
                                   Context.Request.UserHostName);

                try
                {
                    VariableParam[] vars = null;
                    if (!String.IsNullOrEmpty(variable))
                    {
                        vars = new VariableParam[1];

                        VariableParam vp = new VariableParam(variable);
                        vars[0] = vp;
                    }
                    VariablesResponseType res = ODws.GetVariables(vars);

                    // don't always have variables
                    if (res.variables != null)
                    {
                        queryLog2.LogEnd(Logging.Methods.GetVariables,
                                         variable,
                                         timer.ElapsedMilliseconds.ToString(),
                                         res.variables.Length.ToString(),
                                         Context.Request.UserHostName);
                    }
                    else
                    {
                        queryLog2.LogEnd(Logging.Methods.GetVariables,
                                         variable,
                                         timer.ElapsedMilliseconds.ToString(),
                                         "0",
                                         Context.Request.UserHostName);
                    }
                    WaterOneFlow.Service.v1_0.xsd.VariablesResponse obj =
                        new WaterOneFlow.Service.v1_0.xsd.VariablesResponse(res);
                    // if (DEBUG) {
                    // XmlSerializer xs = new XmlSerializer(
                    //     typeof (WaterOneFlow.Service.v1_0.xsd.VariablesResponse));
                    // StringBuilder sb = new StringBuilder();
                    // XmlWriterSettings settings = new XmlWriterSettings();

                    // settings.OmitXmlDeclaration = true;
                    //// settings.ConformanceLevel = ConformanceLevel.Fragment;
                    // XmlWriter writer = XmlWriter.Create(sb, settings);
                    // xs.Serialize(writer, obj);
                    //}
                    //return res;
                    return(new WaterOneFlow.Service.v1_0.xsd.VariablesResponse(res));
                }
                catch (Exception we)
                {
                    log.Warn(we.Message);
                    queryLog2.LogEnd(Logging.Methods.GetVariables,
                                     variable,
                                     timer.ElapsedMilliseconds.ToString(),
                                     "-9999",
                                     Context.Request.UserHostName);

                    throw SoapExceptionGenerator.WOFExceptionToSoapException(we);
                }
            }
Example #26
0
 public abstract object GetTimeSeries(
     locationParam location,
     VariableParam variable,
     W3CDateTime?startDate,
     W3CDateTime?endDate);
Example #27
0
            public static VariableInfoType[] getVariable(VariableParam vParam, VariablesDataset ds)
            {
                List<VariableInfoType> vars = new List<VariableInfoType>();
                if (vParam != null)
                {
                    /* need to use a data view, so the we can set a filter that does not effect the whole dataset
                   DataView has a ToTable method that is uses to create a new DS, and fill
                     * a new VariablesDataset. Typed Datasets are useful ;)
                     */

                    DataView view = new DataView();
                    view.Table = ds.Tables["Variables"];

                    if (vParam.IsId)
                    {
                        view.RowFilter = "VariableID = " + vParam.Code + " ";
                    }
                    else
                    {
                        view.RowFilter = "VariableCode = '" + vParam.Code + "' ";
                        // list of possible options. Allowing any will break the query (aka QualityControlLevelID, etc)
                        String[] options = {"samplemedium", "datatype", "valuetype"};

                        foreach (string opt in options)
                        {
                            if (vParam.options.ContainsKey(opt))
                            {
                                if (!String.IsNullOrEmpty(vParam.options[opt]))
                                {
                                    String rowFilter = view.RowFilter + " AND "
                                                       + opt + "='" + vParam.options[opt] + "'";
                                    view.RowFilter = rowFilter;
                                }
                            }
                        }
                    }

                    DataTable v = view.ToTable();

                    if (v.Rows.Count > 0)
                    {
                        VariablesDataset vtemp = new VariablesDataset();

                        vtemp.Variables.Merge(v);

                        foreach (VariablesDataset.VariablesRow row in vtemp.Variables.Rows)
                        {
                            VariableInfoType result = rowToVariableInfoType(row,
                                                                            ds
                                );
                            vars.Add(result);
                        }

                        return vars.ToArray();
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
Example #28
0
            public override object GetTimeSeries(
                locationParam Location,
                VariableParam Variable,
                W3CDateTime?BeginDateTime, W3CDateTime?EndDateTime)
            {
                string siteNum;

                string   parameterCode;
                string   statisticCode;
                string   agencyCode;
                DateTime startDateTime;
                DateTime endDateTime;

                if (Location.isGeometry)
                {
                    throw new WaterOneFlowException("Geometry not supported ");
                }

                if (Location != null)
                {
                    siteNum = Location.SiteCode;
                }
                else
                {
                    throw new WaterOneFlowException("Missing SiteCode ");
                }

                if (Variable != null)
                {
                    parameterCode = Variable.Code;
                    statisticCode = option2UsgsStatCode(Variable);
                    agencyCode    = option2AgencyCode(Variable);
                }
                else
                {
                    throw new WaterOneFlowException("Missing Parameter ");
                }

                DateTime startMinDate = DateTime.Now.AddDays(-maxRequestDays);

                startDateTime = startMinDate;
                if (BeginDateTime.HasValue)
                {
                    startDateTime = BeginDateTime.Value.DateTime;
                    if (startDateTime <= startMinDate)
                    {
                        startDateTime = startMinDate;
                    }
                }



                DateTime endDateMax = DateTime.Now;

                endDateTime = endDateMax;
                if (EndDateTime.HasValue)
                {
                    endDateTime = EndDateTime.Value.DateTime;
                    if (endDateTime >= endDateMax)
                    {
                        endDateTime = endDateMax;
                    }
                }
                if (endDateTime < DateTime.Now.AddDays(-maxRequestDays))
                {
                    throw new WaterOneFlowException("Only Properties.Settings.Default.UVDaysAvailable days back is supported in the NWIS UV service");
                }
                if (endDateTime < startDateTime)
                {
                    endDateTime = DateTime.Now;
                }

                //TimeSpan span = endDateTime - startDateTime;
                //if (span.Days > 31 )
                //{
                //    span = new TimeSpan(31, 0, 0);
                //}
                try
                {
                    //http://waterservices.usgs.gov/WOF/InstantaneousValues?location=06869950&variable=00065&period=P1D
                    //string urlFormat = "http://{0}/{1}?location={2}&variable={3}&period=P{4}D";
                    //string url = string.Format(urlFormat, "waterservices.usgs.gov",
                    //                           "WOF/InstantaneousValues",
                    //                           siteNum,
                    //                           parameterCode,
                    //                           span.Days);
                    //   string urlFormat = "{0}?location={1}&variable={2}&startDate={3}&endDate={4}";
                    string urlFormat = "{0}?sites={1}&parameterCd={2}&startDT={3}&endDT={4}";
                    string url       = string.Format(urlFormat, USGSUVBaseUrl,
                                                     siteNum,
                                                     parameterCode,
                                                     startDateTime.ToString("yyyy-MM-dd"),
                                                     endDateTime.ToString("yyyy-MM-dd"));
                    Uri uri = new Uri(url);
                    using (WebClient web = new WebClient())
                    {
                        XmlReader    reader       = new XmlTextReader(web.OpenRead(url));
                        MemoryStream memoryStream = new MemoryStream();
                        XmlWriter    writer       = XmlWriter.Create(memoryStream);
                        xslt.Transform(reader, writer);
                        memoryStream.Position = 0;
                        reader = XmlReader.Create(memoryStream);
                        TimeSeriesResponseType response
                            = (TimeSeriesResponseType)serializer.Deserialize(reader);

                        //TimeSeriesResponseType response
                        //    = new Passthrough(web.OpenRead(url));
                        return(response);
                    }
                }


                catch (Exception ex)
                {
                    log.Info("USGS  Connection Error " + ex.Message);
                    throw new WaterOneFlowSourceException("Error connecting to USGS");
                }
            }
Example #29
0
            public static TsValuesSingleVariableType[] getValues(ValuesDataSet ValuesDs, VariableParam variableParam, int? variableId)
            {
                // TimeSeriesResponseType response = CuahsiBuilder.CreateTimeSeriesObjectSingleValue(1);

                TsValuesSingleVariableType[] valuesList = new TsValuesSingleVariableType[1];

                TsValuesSingleVariableType values = new TsValuesSingleVariableType();

                valuesList[0] = values;

                // get siteInfo
                // get variable Info
                // get Values

                string valuesWhereClause = OdValuesCommon.CreateValuesWhereClause(variableParam, variableId);

                // reformats values dataset into a TimeSeriesResponseType
                IEnumerable<ValueSingleVariable> valueE = ODValues.dataset2ValuesList(ValuesDs, variableParam, variableId, variableDs);

                // do this by keeping a list of ID's then generating in after the values list is done
                values.value = new List<ValueSingleVariable>(valueE).ToArray();
                //values.count = values.value.Length;

                if (values.value.Length > 0)
                {
                    // add qualifiers
                    List<QualifierType> qualifers = ODValues.datasetQualifiers(ValuesDs, valuesWhereClause);
                    if (qualifers != null && qualifers.Count > 0)
                    {
                        values.qualifier = qualifers.ToArray();
                    }
                    // add methods
                    List<MethodType> methods = ODValues.datasetMethods(ValuesDs, valuesWhereClause);
                    if (methods != null && methods.Count > 0)
                    {
                        values.method = methods.ToArray();
                    }
                    List<SourceType> sources = ODValues.datasetSources(ValuesDs, valuesWhereClause);
                    if (sources != null && sources.Count > 0)
                    {
                        values.source = sources.ToArray();
                    }
                    List<OffsetType> offsets = ODValues.datasetOffsetTypes(ValuesDs, valuesWhereClause);
                    if (offsets != null && offsets.Count > 0)
                    {
                        values.offset = offsets.ToArray();
                    }

                    List<QualityControlLevelType> qcLevels = ODValues.DatasetQCLevels(ValuesDs, valuesWhereClause);
                    if (qcLevels != null && qcLevels.Count > 0)
                    {
                        values.qualityControlLevel = qcLevels.ToArray();
                    }
                    List<SampleType> samples = ODValues.datasetSamples(ValuesDs, valuesWhereClause);
                    if (samples != null && samples.Count > 0)
                    {
                        values.sample = samples.ToArray();
                    }

                    IEnumerable<CensorCodeType> codeTypes = ODValues.datasetCensorCodes(ValuesDs, valuesWhereClause);
                    values.censorCode = new List<CensorCodeType>(codeTypes).ToArray();
                }

                return valuesList;
            }
            //public virtual string GetValues(string locationParam, string VariableCode, string StartDate, string EndDate, String authToken)
            //{
            //    TimeSeriesResponseType aSite = GetValuesObject(locationParam, VariableCode, StartDate, EndDate, null);
            //    return WSUtils.ConvertToXml(aSite, typeof(TimeSeriesResponseType));
            //}

            public virtual TimeSeriesResponseType GetValuesObject(string LP, string VariableCode, string StartDate, string EndDate, String authToken)
            {
                if (!useODForValues)
                {
                    throw new SoapException("GetValues implemented external to this service. Call GetSiteInfo, and SeriesCatalog includes the service Wsdl for GetValues. Attribute:serviceWsdl on Element:seriesCatalog XPath://seriesCatalog/[@serviceWsdl]", new XmlQualifiedName("ServiceException"));
                }

                Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();

                queryLog2.LogValuesStart(Logging.Methods.GetValues, // method
                                         LP,                        //location
                                         VariableCode,              //variable
                                         StartDate,                 // startdate
                                         StartDate,                 //enddate
                                         Context.Request.UserHostName);

                try
                {
                    WaterOneFlowImpl.locationParam lParam = new locationParam(LP);
                    VariableParam vparam  = new VariableParam(VariableCode);
                    W3CDateTime?  startDt = null;
                    W3CDateTime?  endDt   = null;
                    if (!String.IsNullOrEmpty(StartDate))
                    {
                        startDt = new W3CDateTime(DateTime.Parse(StartDate));
                    }
                    if (!String.IsNullOrEmpty(EndDate))
                    {
                        endDt = new W3CDateTime(DateTime.Parse(EndDate));
                    }


                    TimeSeriesResponseType res = (TimeSeriesResponseType)dvSvc.GetTimeSeries(lParam, vparam, startDt, endDt);

                    if (res != null && res.timeSeries != null &&
                        res.timeSeries.values != null &&
                        res.timeSeries.values.value != null)
                    {
                        queryLog2.LogValuesEnd(Logging.Methods.GetValues,
                                               LP,                                 //locaiton
                                               VariableCode,                       //variable
                                               StartDate,                          // startdate
                                               StartDate,                          //enddate
                                               timer.ElapsedMilliseconds,          // processing time
                                               res.timeSeries.values.value.Length, // count
                                               Context.Request.UserHostName
                                               );
                    }
                    else
                    {
                        queryLog2.LogValuesEnd(Logging.Methods.GetValues,
                                               LP,                        //locaiton
                                               VariableCode,              //variable
                                               StartDate,                 // startdate
                                               StartDate,                 //enddate
                                               timer.ElapsedMilliseconds, // processing time
                                               0,                         // count
                                               Context.Request.UserHostName
                                               );
                    }

                    return(res);
                }
                catch (Exception we)
                {
                    log.Warn(we.Message);
                    queryLog2.LogValuesEnd(Logging.Methods.GetValues,
                                           LP,                        //locaiton
                                           VariableCode,              //variable
                                           StartDate,                 // startdate
                                           StartDate,                 //enddate
                                           timer.ElapsedMilliseconds, // processing time
                                           -9999,                     // count
                                           Context.Request.UserHostName
                                           );
                    throw SoapExceptionGenerator.WOFExceptionToSoapException(we);
                }
            }
Example #31
0
            public override object GetValuesObject(string location, string variable, string startDate, string endDate, String authToken)
            {
                if (!useODForValues)
                {
                    throw new SoapException("GetValues implemented external to this service. Call GetSiteInfo, and SeriesCatalog includes the service Wsdl for GetValues. Attribute:serviceWsdl on Element:seriesCatalog XPath://seriesCatalog/[@serviceWsdl]", new XmlQualifiedName("ServiceException"));
                }

                Stopwatch timer = System.Diagnostics.Stopwatch.StartNew();

                queryLog2.LogValuesStart(Logging.Methods.GetValues, // method
                                         location,                  //location
                                         variable,                  //variable
                                         startDate,                 // startdate
                                         startDate,                 //enddate
                                         Context.Request.UserHostName);

                try
                {
                    WaterOneFlowImpl.locationParam lParam = new locationParam(location);
                    VariableParam vparam = new VariableParam(variable);

                    /* Look to see if siates exist.
                     * NCDC sends back 200k for thier rest service.
                     * aka no errors, except as a string
                     * */
                    SiteInfoType site;
                    try
                    {
                        site = ODws.GetSiteInfoObject(lParam);

                        if (site == null)
                        {
                            throw new WaterOneFlowException("Unknown Site Code: '" + location + "'");
                        }
                    } catch (WaterOneFlowException wex)
                    {
                        throw new WaterOneFlowException("Unknown Site Code: '" + location + "'");
                    } catch (WaterOneFlowServerException wex)
                    {
                        log.Fatal("Database Error");
                        throw wex;
                    } catch (Exception ex)
                    {
                        log.Error("Unhandled Exception ", ex);
                        throw new WaterOneFlowServerException("Unhandled Error.");
                    }

                    VariableInfoType[] vars;
                    try
                    {
                        vars = ODws.GetVariableInfoObject(vparam);

                        if (vars.Length == 0)
                        {
                            throw new WaterOneFlowException("Unknown Variable Code: '" + variable + "'");
                        }
                    }
                    catch (WaterOneFlowException wex)
                    {
                        throw new WaterOneFlowException("Unknown Variable Code: '" + variable + "'");
                    }
                    catch (WaterOneFlowServerException wex)
                    {
                        log.Fatal("Database Error");
                        throw wex;
                    }
                    catch (Exception ex)
                    {
                        log.Error("Unhandled Exception ", ex);
                        throw new WaterOneFlowServerException("Unhandled Error.");
                    }

                    // moved date check after site and variable check
                    W3CDateTime?startDt = null;
                    W3CDateTime?endDt   = null;
                    if (!String.IsNullOrEmpty(startDate))
                    {
                        startDt = new W3CDateTime(DateTime.Parse(startDate));
                    }
                    if (!String.IsNullOrEmpty(endDate))
                    {
                        endDt = new W3CDateTime(DateTime.Parse(endDate));
                        int endDateMin = int.Parse(ConfigurationManager.AppSettings.Get("NCDCISD_EndDateMinYear"));
                        if (endDt.Value.DateTime.Year < endDateMin)
                        {
                            throw new WaterOneFlowException("NCDC ISD and ISH No Data is available before: " + endDateMin);
                        }
                    }

                    /***********************
                     * GET NCDC RESPONSE
                     * *********************
                     */
                    TimeSeriesResponseTypeObject res = (TimeSeriesResponseTypeObject)dvSvc.GetTimeSeries(lParam, vparam, startDt, endDt);


                    /***********************
                     * Add missing information from sites and variables db
                     * *********************
                     */
                    if (vars.Length > 0)
                    {
                        res.timeSeries.variable = vars[0];
                    }
                    if (site != null)
                    {
                        res.timeSeries.sourceInfo = site;
                    }


                    return(new WaterOneFlow.Service.v1_0.xsd.TimeSeriesResponse(res));
                }
                catch (Exception we)
                {
                    log.Warn(we.Message);
                    queryLog2.LogValuesEnd(Logging.Methods.GetValues,
                                           location,                  //locaiton
                                           variable,                  //variable
                                           startDate,                 // startdate
                                           startDate,                 //enddate
                                           timer.ElapsedMilliseconds, // processing time
                                           -9999,                     // count
                                           Context.Request.UserHostName
                                           );
                    throw SoapExceptionGenerator.WOFExceptionToSoapException(we);
                }
            }
Example #32
0
            public override object GetTimeSeries(
                locationParam lp,
                VariableParam vp,
                Nullable <W3CDateTime> startDate,
                Nullable <W3CDateTime> endDate)
            {
                if (lp.isGeometry)
                {
                    throw new WaterOneFlowException("Geometry not supported ");
                }

                TimeSeriesResponseType result = null;

                //string Network;
                //string SiteCode;
                ////WSUtils.ParseSiteId(siteId, out Network, out SiteCode);
                //try
                //{
                //    locationParam sq = new locationParam(siteNumber);
                //    Network = sq.Network;
                //    SiteCode = sq.SiteCode;
                //    if (sq.isGeometry)
                //    {
                //        throw new WaterOneFlowException("Location by Geometry not accepted: " + siteNumber);
                //    }
                //}
                //catch (WaterOneFlowException we)
                //{
                //    log.Info("Bad SiteID:" + siteNumber);
                //    throw;
                //}
                //catch (Exception e)
                //{
                //    log.Error("Uncaught exception:" + e.Message);
                //    throw new WaterOneFlowException("Sorry. Your submitted site ID for this getSiteInfo request caused an problem that we failed to catch programmatically: " + e.Message);
                //}

                //// string WaterQualityList = "&parameter_cd=" + variable;
                //string[] StationsList = new string[] { SiteCode };
                string[] StationsList = new string[] { lp.SiteCode };

                //VariableParam vp;
                //try
                //{
                //    vp = new VariableParam(variable);

                //}
                //catch (WaterOneFlowException we)
                //{
                //    log.Info("Bad Variable Request '" + variable + "'");
                //    throw;
                //}
                //catch (Exception e)
                //{
                //    log.Error("uncaught exception duing Variable Request '" + variable + "'");
                //    throw new WaterOneFlowException("Sorry. Your variable parameter caused an exception that we failed to catch:" + e.Message);

                //}

                result = CuahsiBuilder.CreateTimeSeriesObject();

                //// all data are provisional
                //List<note> notes = new List<note>();
                //note urlNote = new note();
                //urlNote.title = "USGS Data Provisional";
                //urlNote.href = "http://waterdata.usgs.gov/nwis/help/?provisional";
                //urlNote.Value = "All data are provisional, and subject to revision";
                //notes.Add(urlNote);
                //result.queryInfo.note = notes.ToArray();

                result.queryInfo.criteria.locationParam = lp.ToString();
                result.queryInfo.criteria.variableParam = vp.ToString();


                // result.queryInfo.criteria.timeParam  = CuahsiBuilder.createQueryInfoTimeCriteria(startDate, endDate);

                // look for siteInfoType in cache, and use if it is there

                /* SiteInfoType sit = (SiteInfoType)appCache[sitCache + SiteCode];
                 * if (sit == null)
                 * {
                 *   // just use the values for now.
                 *   ((SiteInfoType)result.timeSeries.sourceInfo).siteCode[0].Value = SiteCode;
                 *   ((SiteInfoType)result.timeSeries.sourceInfo).siteCode[0].network = "NWIS";
                 *
                 * }
                 * else
                 * {
                 *   // in the cache, use it
                 *   result.timeSeries.sourceInfo = sit;
                 * }
                 * */
                result.timeSeries.sourceInfo = DataInfoService.GetSite(lp);


                // vaiable info
                // result.timeSeries.variable = vp.getVariableSchemaType();
                //result.timeSeries.variable = NwisVariableCatalog.getVariable(vp.Code, variableDataSet);
                //result.timeSeries.variable = ODvariables.getVariable(vp.Code, variableDataSet)[0];

                // not fully correct, but just choose the first one.
                VariableInfoType[] vits = DataInfoService.GetVariableInfoObject(vp);
                result.timeSeries.variable = vits[0];
                string aURL = GroundWater(startDate, endDate,
                                          StationsList, USGSCommon.option2AgencyCode(lp));

                try
                {
                    // refactor too much abstraction
                    //CreateRealTimeSeriesObject(result, RealTime(StationsList));
                    result.timeSeries.values =
                        CreateGWTimeSeriesObject(vp, aURL);
                }
                catch (WaterOneFlowException e)
                {
                    //log.Error(e.Message + e.StackTrace);
                    throw;
                }
                catch (WaterOneFlowSourceException e)
                {
                    //log.Error(e.Message + e.StackTrace);
                    throw;
                }
                catch (WebException e)
                {
                    log.Error(e.Message + e.StackTrace);
                    throw new WaterOneFlowException("Connecting to External resource failed.", e);
                }
                catch (Exception e)
                {
                    log.Error(e.Message + e.StackTrace);
                    throw new WaterOneFlowException("An External resource failed.", e);
                }

                result.timeSeries.sourceInfo = DataInfoService.GetSite(lp);

                List <NoteType> notes   = new List <NoteType>();
                NoteType        urlNote = new NoteType();

                urlNote.title = "USGS URL";
                urlNote.Value = aURL;
                notes.Add(urlNote);
                result.queryInfo.note = notes.ToArray();

                return(result);
            }
Example #33
0
            public static IEnumerable<ValueSingleVariable> dataset2ValuesList(ValuesDataSet ds, VariableParam variable, int? VariableId, VariablesDataset variablesDs)
            {
                Boolean variableIsCategorical = false;
                VariableInfoType variableInfoType = ODvariables.GetVariableByID(VariableId, variablesDs);
                if (variableInfoType != null && variableInfoType.dataType.Equals("Categorical"))
                {
                    variableIsCategorical = true;
                }

                /* logic
                 * if there is a variable that has options, then get a set of datarows
                 * using a select clause
                 * use an enumerator, since it is generic
                 * */

                IEnumerator dataValuesEnumerator; // = ds.DataValues.GetEnumerator();

                ValuesDataSet.DataValuesRow[] dvRows; // if we find options, we need to use this.

                String select = OdValuesCommon.CreateValuesWhereClause(variable, VariableId);

                if (select.Length > 0)
                {
                    dvRows = (ValuesDataSet.DataValuesRow[]) ds.DataValues.Select(select.ToString());

                    dataValuesEnumerator = dvRows.GetEnumerator();
                }
                else
                {
                    dataValuesEnumerator = ds.DataValues.GetEnumerator();
                }

                while (dataValuesEnumerator.MoveNext())
                {
                    ValuesDataSet.DataValuesRow aRow = (ValuesDataSet.DataValuesRow) dataValuesEnumerator.Current;
                    ValueSingleVariable tsTypeValue = new ValueSingleVariable();
                    Boolean goodValue = false;
                    try
                    {
                        tsTypeValue.dateTime = Convert.ToDateTime(aRow.DateTime);

                        DateTime temprealdate;

                        TimeSpan zone = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
                        Double offset = Convert.ToDouble(aRow.UTCOffset);
                        if (zone.TotalHours.Equals(offset))
                        {
                            temprealdate = DateTime.SpecifyKind(Convert.ToDateTime(aRow.DateTime),
                                                                DateTimeKind.Local);
                        }
                        else
                        {
                            temprealdate = DateTime.SpecifyKind(Convert.ToDateTime(aRow.DateTime), DateTimeKind.Utc);

                            temprealdate = temprealdate.AddHours(offset);
                        }
                        temprealdate = Convert.ToDateTime(aRow.DateTime);
                        tsTypeValue.dateTime = temprealdate;

                        tsTypeValue.dateTimeUTC = aRow.DateTimeUTC;
                        tsTypeValue.dateTimeUTCSpecified = true;
                        tsTypeValue.timeOffset = OffsetDoubleToHoursMinutesString(aRow.UTCOffset);

                        //tsTypeValue.dateTime = new DateTimeOffset(temprealdate);
                        //tsTypeValue.dateTimeSpecified = true;

                        if (string.IsNullOrEmpty(aRow.Value.ToString()))
                            continue;
                        else
                            tsTypeValue.Value = Convert.ToDecimal(aRow.Value);

                        try
                        {
                            tsTypeValue.censorCode =
                                aRow.CensorCode;
                            if (!aRow.IsOffsetTypeIDNull())
                            {
                                //tsTypeValue.offsetTypeID = aRow.OffsetTypeID.ToString();
                               tsTypeValue.offsetTypeCode = aRow.OffsetTypeID.ToString();

                                // HIS-97 moved to OffsetUnitsType
                            //      ValuesDataSet.OffsetTypesRow off =
                            //        ds.OffsetTypes.FindByOffsetTypeID(aRow.OffsetTypeID);
                            //    ValuesDataSet.UnitsRow offUnit = ds.Units.FindByUnitsID(off.OffsetUnitsID);
                            //    tsTypeValue.offsetUnitsCode = offUnit.UnitsID.ToString();
                            //    tsTypeValue.offsetUnitsAbbreviation = offUnit.UnitsAbbreviation;
                            }

                            // offset value may be separate from the units... anticpating changes for USGS
                            if (!aRow.IsOffsetValueNull())
                            {
                                tsTypeValue.offsetValue = aRow.OffsetValue;
                                tsTypeValue.offsetValueSpecified = true;
                            }

                            ValuesDataSet.MethodsRow meth = ds.Methods.FindByMethodID(aRow.MethodID);
                           // tsTypeValue.methodID = aRow.MethodID.ToString();
                            tsTypeValue.methodCode = aRow.MethodID.ToString();

                            // qualifiers
                            if (!aRow.IsQualifierIDNull())
                            {
                                ValuesDataSet.QualifiersRow qual = ds.Qualifiers.FindByQualifierID(aRow.QualifierID);
                                if (qual != null)
                                {
                                    tsTypeValue.qualifiers = qual.QualifierCode;
                                }
                            }

                            //  quality control level

                            ValuesDataSet.QualityControlLevelsRow qcl =
                                ds.QualityControlLevels.FindByQualityControlLevelID(aRow.QualityControlLevelID);
                            string qlName = qcl.Definition.Replace(" ", "");
                            tsTypeValue.qualityControlLevelCode = qcl.QualityControlLevelCode;
                            //if (!String.IsNullOrEmpty(qlName))
                            //{
                            //    tsTypeValue.qualityControlLevel = qlName;
                            //}

                           // tsTypeValue.sourceID = aRow.SourceID.ToString();
                             tsTypeValue.sourceCode = aRow.SourceID.ToString();

                            if (!aRow.IsSampleIDNull())
                            {
                                //tsTypeValue.sampleID = aRow.SampleID.ToString();
                                ValuesDataSet.SamplesRow lsc = ds.Samples.FindBySampleID(aRow.SampleID);
                                tsTypeValue.labSampleCode = lsc.LabSampleCode;
                            }

                            // categorical
                            if (variableIsCategorical && VariableId.HasValue)
                            {
                                  tsTypeValue.codedVocabularyTerm = ODvariables.GetCategoryTerm(VariableId.Value, tsTypeValue.Value, variablesDs);
                                  if (!String.IsNullOrEmpty(tsTypeValue.codedVocabularyTerm) )
                                  {
                                      tsTypeValue.codedVocabulary = true;
                                  }
                                tsTypeValue.codedVocabularySpecified = true;

                            }
                        }
                        catch (Exception e)
                        {
                            log.Debug("Error generating a value " + e.Message);
                            // non fatal exceptions
                        }
                        goodValue = true;

                    }
                    catch (Exception e)
                    {
                        goodValue = false;
                        // If there is an error, we do not add it.
                    }

                    if (goodValue)
                    {
                        yield return tsTypeValue;
                    }
                }
            }
Example #34
0
            public static VariableInfoType[] getVariables(VariableParam[] vParams, VariablesDataset ds)
            {
                List<VariableInfoType> vit = new List<VariableInfoType>();

                // if there are no variableParameters, return all varaibles
                if (vParams == null || vParams.Length == 0)
                {
                    foreach (VariablesDataset.VariablesRow row in ds.Variables.Rows)
                    {
                        VariableInfoType result = rowToVariableInfoType(row,
                                                                        ds
                            );
                        vit.Add(result);
                    }
                    return vit.ToArray();
                }
                else
                {
                    foreach (VariableParam vParam in vParams)
                    {
                        VariableInfoType[] vars = getVariable(vParam, ds);
                        if (vars != null) vit.AddRange(vars);
                    }
                    return vit.ToArray();
                }
            }
Example #35
0
        /// <summary>
        /// DataValue creation. Converts a ValuesDataSet to the XML schema ValueSingleVariable
        /// If variable is null, it will return all
        /// If variable has extra options (variable:code/Value=Key/Value=Key)
        ///
        /// </summary>
        /// <param name="ds">Dataset that you want converted</param>
        /// <param name="variable">Variable that you want to use to place limits on the returned data</param>
        /// <returns></returns>
        public static List <ValueSingleVariable> dataset2ValuesList(ValuesDataSet ds, VariableParam variable)
        {
            List <ValueSingleVariable> tsTypeList = new List <ValueSingleVariable>();


            /* logic
             * if there is a variable that has options, then get a set of datarows
             * using a select clause
             * use an enumerator, since it is generic
             * */
            IEnumerator dataValuesEnumerator;

            ValuesDataSet.DataValuesRow[] dvRows; // if we find options, we need to use this.

            String select = OdValuesCommon.CreateValuesWhereClause(variable, null);

            if (select.Length > 0)
            {
                dvRows = (ValuesDataSet.DataValuesRow[])ds.DataValues.Select(select.ToString());

                dataValuesEnumerator = dvRows.GetEnumerator();
            }
            else
            {
                dataValuesEnumerator = ds.DataValues.GetEnumerator();
            }

            //  foreach (ValuesDataSet.DataValuesRow aRow in ds.DataValues){
            while (dataValuesEnumerator.MoveNext())
            {
                ValuesDataSet.DataValuesRow aRow = (ValuesDataSet.DataValuesRow)dataValuesEnumerator.Current;
                try
                {
                    ValueSingleVariable tsTypeValue = new ValueSingleVariable();

                    #region DateTime Standard
                    tsTypeValue.dateTime = Convert.ToDateTime(aRow.DateTime);
                    //tsTypeValue.dateTimeSpecified = true;
                    DateTime temprealdate;



                    //<add key="returnUndefinedUTCorLocal" value="Undefined"/>
                    if (ConfigurationManager.AppSettings["returnUndefinedUTCorLocal"].Equals("Undefined"))
                    {
                        temprealdate = Convert.ToDateTime(aRow.DateTime); // not time zone shift
                    }
                    else if (ConfigurationManager.AppSettings["returnUndefinedUTCorLocal"].Equals("Local"))
                    {
                        TimeSpan zone   = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
                        Double   offset = Convert.ToDouble(aRow.UTCOffset);

                        if (zone.TotalHours.Equals(offset))
                        {
                            // zone is the same as server. Shift
                            temprealdate = DateTime.SpecifyKind(Convert.ToDateTime(aRow.DateTime), DateTimeKind.Local);
                        }
                        else
                        {
                            //// zone is not the same. Output in UTC.
                            //temprealdate = DateTime.SpecifyKind(Convert.ToDateTime(aRow.DateTime), DateTimeKind.Utc);
                            //// correct time with shift.
                            //temprealdate = temprealdate.AddHours(offset);

                            // just use the DateTime UTC
                            temprealdate = DateTime.SpecifyKind(Convert.ToDateTime(aRow.DateTimeUTC), DateTimeKind.Utc);
                        }
                    }
                    else if (ConfigurationManager.AppSettings["returnUndefinedUTCorLocal"].Equals("UTC"))
                    {
                        temprealdate = DateTime.SpecifyKind(Convert.ToDateTime(aRow.DateTimeUTC), DateTimeKind.Utc);
                    }
                    else
                    {
                        temprealdate = Convert.ToDateTime(aRow.DateTime); // not time zone shift
                    }

                    temprealdate = Convert.ToDateTime(aRow.DateTime); // not time zone shift
                    #endregion
                    #region DateTimeOffset Failed
                    /// using XML overrides
                    // Attemp to use DateTimeOffset in xml Schema
                    //TimeSpan zone = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
                    //Double offset = Convert.ToDouble(aRow.UTCOffset);

                    //DateTimeOffset temprealdate;
                    //temprealdate = new DateTimeOffset(Convert.ToDateTime(aRow.DateTime),
                    //    new TimeSpan(Convert.ToInt32(offset),0,0));
                    //DateTimeOffset temprealdate;
                    //temprealdate = new DateTimeOffset(Convert.ToDateTime(aRow.DateTime),
                    //    new TimeSpan(Convert.ToInt32(offset), 0, 0));

                    //tsTypeValue.dateTime = temprealdate;
                    //tsTypeValue.dateTimeSpecified = true;
                    #endregion

                    //tsTypeValue.censored = string.Empty;
                    if (string.IsNullOrEmpty(aRow.Value.ToString()))
                    {
                        continue;
                    }
                    else
                    {
                        tsTypeValue.Value = Convert.ToDecimal(aRow.Value);
                    }

                    try
                    {
                        tsTypeValue.censorCode          = (CensorCodeEnum)Enum.Parse(typeof(CensorCodeEnum), aRow.CensorCode, true);
                        tsTypeValue.censorCodeSpecified = true;

                        if (!aRow.IsOffsetTypeIDNull())
                        {
                            tsTypeValue.offsetTypeID          = aRow.OffsetTypeID;
                            tsTypeValue.offsetTypeIDSpecified = true;

                            // enabled to fix issue with hydroobjects
                            ValuesDataSet.OffsetTypesRow off = ds.OffsetTypes.FindByOffsetTypeID(aRow.OffsetTypeID);


                            ValuesDataSet.UnitsRow offUnit = ds.Units.FindByUnitsID(off.OffsetUnitsID);
                            tsTypeValue.offsetUnitsCode         = offUnit.UnitsID.ToString();
                            tsTypeValue.offsetUnitsAbbreviation = offUnit.UnitsAbbreviation;
                        }

                        // offset value may be separate from the units... anticpating changes for USGS
                        if (!aRow.IsOffsetValueNull())
                        {
                            tsTypeValue.offsetValue          = aRow.OffsetValue;
                            tsTypeValue.offsetValueSpecified = true;
                        }


                        ValuesDataSet.MethodsRow meth = ds.Methods.FindByMethodID(aRow.MethodID);
                        tsTypeValue.methodID          = aRow.MethodID;
                        tsTypeValue.methodIDSpecified = true;


                        if (!aRow.IsQualifierIDNull())
                        {
                            ValuesDataSet.QualifiersRow qual = ds.Qualifiers.FindByQualifierID(aRow.QualifierID);
                            if (qual != null)
                            {
                                tsTypeValue.qualifiers = qual.QualifierCode;
                            }
                        }


                        ValuesDataSet.QualityControlLevelsRow qcl =
                            ds.QualityControlLevels.FindByQualityControlLevelID(aRow.QualityControlLevelID);
                        string qlName = qcl.Definition.Replace(" ", "");

                        if (Enum.IsDefined(typeof(QualityControlLevelEnum), qlName))
                        {
                            tsTypeValue.qualityControlLevel = (QualityControlLevelEnum)
                                                              Enum.Parse(
                                typeof(QualityControlLevelEnum), qlName, true);
                            if (tsTypeValue.qualityControlLevel != QualityControlLevelEnum.Unknown)
                            {
                                tsTypeValue.qualityControlLevelSpecified = true;
                            }
                        }
                        //}
                        tsTypeValue.sourceID          = aRow.SourceID;
                        tsTypeValue.sourceIDSpecified = true;

                        if (!aRow.IsSampleIDNull())
                        {
                            tsTypeValue.sampleID          = aRow.SampleID;
                            tsTypeValue.sampleIDSpecified = true;
                        }
                    }
                    catch (Exception e)
                    {
                        log.Debug("Error generating a value " + e.Message);
                        // non fatal exceptions
                    }

                    tsTypeList.Add(tsTypeValue);
                }
                catch (Exception e)
                {
                    //  ignore any value errors
                }
            }
            return(tsTypeList);
        }
Example #36
0
            private VariableParam GetVariableParameter(string Variable, ref int? variableId, ref VariableInfoType varInfoType)
            {
                VariableParam vp = null;
                if (Variable != null)
                {

                    vp = new VariableParam(Variable);
                    VariableInfoType[] v = ODvariables.getVariable(vp, variableDs);
                    if (v != null && v.Length > 0)
                    {
                        variableId = Convert.ToInt16(v[0].variableCode[0].variableID);
                        varInfoType = v[0];
                    }
                    else
                    {
                        throw new WaterOneFlowException("Variable parameter not found: " + Variable);

                    }
                }
                return vp;
            }