//converts a data table to a list of WaterOneFlowServiceInfo objects private IList <DataServiceInfo> TableToWebServiceInfo(DataTable table) { List <DataServiceInfo> resultList = new List <DataServiceInfo>(); foreach (DataRow row in table.Rows) { string endpointURL = row["servURL"].ToString(); endpointURL = endpointURL.ToLower(); if (endpointURL.EndsWith("?wsdl")) { endpointURL = endpointURL.Replace("?wsdl", ""); } string title = row["Title"].ToString(); DataServiceInfo servInfo = new DataServiceInfo(endpointURL, title); servInfo.DescriptionURL = row["ServiceDescriptionURL"].ToString(); servInfo.ContactName = row["organization"].ToString(); servInfo.ContactEmail = row["orgwebsite"].ToString(); servInfo.Citation = row["citation"].ToString(); servInfo.Abstract = (string)row["aabstract"]; servInfo.ValueCount = Convert.ToInt32(row["valuecount"]); servInfo.SiteCount = Convert.ToInt32(row["sitecount"]); servInfo.HISCentralID = Convert.ToInt32(row["ServiceID"]); servInfo.EastLongitude = Convert.ToDouble(row["minx"]); servInfo.SouthLatitude = Convert.ToDouble(row["miny"]); servInfo.WestLongitude = Convert.ToDouble(row["maxx"]); servInfo.NorthLatitude = Convert.ToDouble(row["maxy"]); servInfo.ServiceCode = Convert.ToString(row["NetworkName"]); servInfo.ServiceName = Convert.ToString(row["organization"]); resultList.Add(servInfo); } return(resultList); }
/// <summary> /// Adds single service from the form input /// </summary> private List <DataServiceInfo> GetSingleServiceRow() { List <DataServiceInfo> rows = new List <DataServiceInfo>(); string serviceUrl = txtURL.Text; // Trim the query off of the URL int index = serviceUrl.IndexOf("?"); if (index > -1) { serviceUrl = serviceUrl.Substring(0, index); } DataServiceInfo dataServiceInfo = new DataServiceInfo(); dataServiceInfo.EndpointURL = serviceUrl; dataServiceInfo.ServiceTitle = txtTitle.Text; dataServiceInfo.ServiceCode = txtCode.Text; dataServiceInfo.Citation = txtCitation.Text; dataServiceInfo.Abstract = txtAbstract.Text; dataServiceInfo.DescriptionURL = txtWebsite.Text; dataServiceInfo.ContactName = txtContact.Text; dataServiceInfo.ContactEmail = txtEmail.Text; rows.Add(dataServiceInfo); return(rows); }
public void CanSaveMultipleSeries() { Random random = new Random(); //string url1 = @"http://his02.usu.edu/littlebearriver/cuahsi_1_0.asmx"; //string url2 = @"http://icewater.boisestate.edu/dcew2dataservices/cuahsi_1_0.asmx"; string url3 = @"http://his.crwr.utexas.edu/TXEvap/cuahsi_1_0.asmx"; MetadataCacheManagerSQL manager = TestConfig.MetadataCacheManager; WaterOneFlowClient client = new WaterOneFlowClient(url3); IList <Site> siteList = client.GetSites(); IList <SeriesMetadata> seriesList = new List <SeriesMetadata>(); DataServiceInfo service = GeDatatService(random.Next()); manager.SaveDataService(service); foreach (Site site in siteList) { IList <SeriesMetadata> seriesList1 = client.GetSiteInfo(site.Code); foreach (SeriesMetadata series in seriesList1) { seriesList.Add(series); } } foreach (SeriesMetadata series in seriesList) { manager.SaveSeries(series, service); } }
/// <summary> /// Creates a new instance of a WaterOneFlow web service client /// which communicates with the specified web service. /// </summary> /// <param name="serviceInfo">The object with web service information</param> /// <remarks>Throws an exception if the web service is not a valid /// WaterOneFlow service</remarks> public WaterOneFlowClient(DataServiceInfo serviceInfo) { //check if the web service is a valid web service. //this will throw an exception when the web service URL is invalid. CheckWebService(serviceInfo.EndpointURL); _asmxURL = serviceInfo.EndpointURL; //TODO make this path an optional user setting DownloadDirectory = Path.Combine(Path.GetTempPath(), "HydroDesktop"); //find out the WaterOneFlow version of this web service _serviceInfo = serviceInfo; AssignWaterOneFlowVersion(_serviceInfo); //assign the waterOneFlow parser //the parser is automatically set depending on service version information //in the WaterML file if (ServiceInfo.Version == 1.0) { _parser = new WaterOneFlow10Parser(); } else { _parser = new WaterOneFlow11Parser(); } }
private SeriesDataCart getDataCartFromMetadata(SeriesMetadata series, DataServiceInfo waterOneFlowServiceInfo) { var result = new SeriesDataCart(); Site cSite = series.Site; result.SiteName = cSite.Name; result.SiteCode = cSite.Code; result.Latitude = cSite.Latitude; result.Longitude = cSite.Longitude; Variable v = series.Variable; result.VariableName = v.Name; result.VariableCode = v.Code; result.DataType = v.DataType; result.ValueType = v.ValueType; result.SampleMedium = v.SampleMedium; result.TimeSupport = Convert.ToDouble(v.TimeSupport, CultureInfo.InvariantCulture); result.GeneralCategory = v.GeneralCategory; result.TimeUnit = v.TimeUnit.Name; result.BeginDate = Convert.ToDateTime(series.BeginDateTime, CultureInfo.InvariantCulture); result.EndDate = Convert.ToDateTime(series.EndDateTime, CultureInfo.InvariantCulture); result.ValueCount = series.ValueCount; result.ServURL = waterOneFlowServiceInfo.EndpointURL; result.ServCode = titleTextbox.Text; return(result); }
/// <summary> /// 根据节点添加缩略图 /// </summary> /// <param name="dataServiceGroups"></param> /// <param name="endPoints"></param> /// <param name="node"></param> protected virtual void AddDataServiceByXmlNode(IList <DataServiceGroupInfo> dataServiceGroups, IList <EndPointInfo> endPoints, XmlNode node) { var dsp = new DataServiceGroupInfo { DataServices = new List <DataServiceInfo>() }; if (node != null && node.Attributes != null) { dsp.Path = node.Attributes["Path"] == null ? null : node.Attributes["Path"].Value; dsp.Name = node.Attributes["Name"] == null ? null : node.Attributes["Name"].Value; dsp.IsClose = node.Attributes["IsClose"] != null && Convert.ToBoolean(node.Attributes["IsClose"].Value); dsp.Addresses = node.Attributes["Addresses"] == null ? null : node.Attributes["Addresses"].Value.Split(','); XmlNodeList dsNodes = node.SelectNodes("DataService"); if (dsNodes != null && dsNodes.Count > 0) { foreach (XmlNode dsNode in dsNodes) { var ds = new DataServiceInfo { Type = dsNode.Attributes["Type"] == null ? DataServiceType.Master : (DataServiceType) Enum.Parse(typeof(DataServiceType), dsNode.Attributes["Type"].Value), EndPoint = endPoints.FirstOrDefault(it => it.Name.Equals(dsNode.Attributes["EndPointName"].Value)) }; dsp.DataServices.Add(ds); } } } dataServiceGroups.Add(dsp); }
/// <summary> /// Deletes all entries in the metadata cache database that were /// added by the data service /// </summary> /// <param name="service">The serviceInfo object to be deleted</param> /// <param name="deleteService">Set to true if the record in the DataServices /// table should also be deleted. Set to false if the record in the DataServices /// table should be kept</param> /// <returns>The total number of records deleted</returns> public int DeleteRecordsForService(DataServiceInfo service, bool deleteService) { string serviceID = service.Id.ToString(CultureInfo.InvariantCulture); string sqlDelete = "DELETE FROM DataSeriesCache WHERE ServiceID = " + serviceID + "; " + "DELETE FROM SitesCache WHERE ServiceID = " + serviceID + "; " + "DELETE FROM VariablesCache WHERE ServiceID = " + serviceID + "; " + "DELETE FROM SourcesCache WHERE ServiceID = " + serviceID + "; " + "DELETE FROM MethodsCache WHERE ServiceID = " + serviceID + "; " + "DELETE FROM QualityControlLevelsCache WHERE ServiceID = " + serviceID + ";" + "DELETE FROM ISOMetadataCache WHERE ServiceID = " + serviceID + ";"; if (deleteService) { sqlDelete += "DELETE FROM DataServices WHERE ServiceID = " + serviceID + ";"; } using (var conn = _db.CreateConnection()) { conn.Open(); using (var tran = conn.BeginTransaction()) { using (var cmd01 = conn.CreateCommand()) { cmd01.CommandText = sqlDelete; cmd01.ExecuteNonQuery(); } tran.Commit(); } } return 0; }
/// <summary> /// Searches for WaterOneFlow services registered at a HydroPortal, and adds info about those services to the data grid view /// </summary> /// <param name="portalUtils">Object that contains a pointer to the HydroPortal chosen by the user</param> /// <param name="e">Parameters from the BackgroundWorker</param> /// <returns>Parameters (task type, output message, rows to add to view) to be processed by a BackgroundWorker event handler</returns> private object[] AddServicesFromHydroPortal(HydroPortalUtils portalUtils, DoWorkEventArgs e) { // Build parameters to pass to the background worker object[] parameters = new object[3]; parameters[0] = BackgroundWorkerTasks.AddServicesFromHydroPortal; parameters[1] = "Operation cancelled"; // Get all items registered with the portal bgwMain.ReportProgress(0, "Getting list of registered portal items..."); List <string> itemIds = portalUtils.GetRegisteredItemIds(); // Find items with an element providing the URL to a WaterOneFlow service int totalSteps = itemIds.Count; int currentStep = 0; List <string[]> rowsToAdd = new List <string[]> (); foreach (string itemId in itemIds) { if (bgwMain.CancellationPending) { e.Cancel = true; return(parameters); } currentStep++; bgwMain.ReportProgress(100 * currentStep / totalSteps, "Searching registered items for WaterOneFlow services: " + currentStep + " of " + totalSteps + "..."); DataServiceInfo serviceInfo = portalUtils.ReadWaterOneFlowServiceInfo(itemId); if (serviceInfo != null && serviceInfo.EndpointURL != null && serviceInfo.EndpointURL != String.Empty) { // Create an item to add to the data grid view rowsToAdd.Add(CreateServiceRow(serviceInfo)); } } // Prepare a message to the user string message = ""; int servicesAdded = rowsToAdd.Count; if (servicesAdded == 0) { message = "No services found in portal"; } else if (servicesAdded == 1) { message = "1 service found in portal"; } else { message = servicesAdded.ToString() + " services found in portal"; } parameters[1] = message; parameters[2] = rowsToAdd; return(parameters); }
public void GetParser(double version, Type type) { var wof = new DataServiceInfo { Version = version }; var parser = ParserFactory.GetParser(wof); Assert.AreEqual(type, parser.GetType()); }
public void CanSaveDataService() { Random random = new Random(); DataServiceInfo service = GeDatatService(random.Next()); MetadataCacheManagerSQL manager = TestConfig.MetadataCacheManager; manager.SaveDataService(service); //Assert.Greater(service.Id, 0, "the id of saved service should be > 0"); }
public void TestAddingServiceInfo() { var someStr = "00000111111111111111111111100000"; var countOfByte = someStr.Length / 8; var data = new Data(" ", CorrectionLevel.L, s => s, "0100"); data.DataBit = someStr; var expected = ("0100" + countOfByte.ToString().DigitToBit(8) + someStr); // .SupplementToMultiple() (не верно рабоатет) походу это не делаю в строке 13 а делаю в returne? Assert.AreEqual("0100" + countOfByte.ToString().DigitToBit(8) + someStr, DataServiceInfo.AddServiceInfo(data)); }
/// <summary> /// Retrieves information about CUAHSI WaterOneFlow web services available in the specified region /// (latitude / longitude bounding box). /// </summary> /// <param name="xmin">Minimum x (longitude)</param> /// <param name="xmax">Maximum x (longitude)</param> /// <param name="ymax">Maximum y (latitude)</param> /// <param name="ymin">Minimum y (latitude)</param> /// <returns></returns> public IList <DataServiceInfo> GetServicesInBox(double xmin, double ymin, double xmax, double ymax) { List <DataServiceInfo> serviceList = new List <DataServiceInfo>(); string soapAction = cuahsiSoapAction + "GetServicesInBox2"; StringBuilder soap = new StringBuilder(); soap.Append(soapEnvelopeHeader); soap.Append(@"<GetServicesInBox2 "); soap.Append(cuahsiXmlns); soap.Append(@">"); soap.Append(@"<xmin>"); soap.Append(xmin.ToString(CultureInfo.InvariantCulture)); soap.Append(@"</xmin>"); soap.Append(@"<ymin>"); soap.Append(ymin.ToString(CultureInfo.InvariantCulture)); soap.Append(@"</ymin>"); soap.Append(@"<xmax>"); soap.Append(xmax.ToString(CultureInfo.InvariantCulture)); soap.Append(@"</xmax>"); soap.Append(@"<ymax>"); soap.Append(ymax.ToString(CultureInfo.InvariantCulture)); soap.Append(@"</ymax>"); soap.Append(@"</GetServicesInBox2>"); soap.Append(soapEnvelopeClosing); WebResponse response = SoapHelper.HttpSOAPRequest(soap.ToString(), soapAction); Stream responseStream = response.GetResponseStream(); XmlTextReader reader = new XmlTextReader(responseStream); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { string readerName = reader.Name.ToLower(); if (readerName == "serviceinfo") { //Read the site information DataServiceInfo service = ReadDataServiceInfo(reader); if (service != null) { serviceList.Add(service); } } } } reader.Close(); responseStream.Close(); response.Close(); return(serviceList); }
/// <summary> /// Creates a string array that can be used to add a row to a data grid view, based on properties of a DataServiceInfo object /// </summary> /// <param name="serviceInfo">Details about the WaterOneFlow service</param> /// <returns>String array of properties from the DataServiceInfo object</returns> private string[] CreateServiceRow(DataServiceInfo serviceInfo) { string[] row = { serviceInfo.ServiceTitle, serviceInfo.EndpointURL, serviceInfo.ServiceCode, serviceInfo.Citation, serviceInfo.Abstract, serviceInfo.DescriptionURL, serviceInfo.ContactName, serviceInfo.ContactEmail }; return(row); }
/// <summary> /// Creates a new instance of a WaterOneFlow web service client /// which communicates with the specified web service. /// </summary> /// <param name="serviceInfo">The object with web service information</param> /// <remarks>Throws an exception if the web service is not a valid /// WaterOneFlow service</remarks> public WaterOneFlowClient(DataServiceInfo serviceInfo) { _serviceURL = serviceInfo.EndpointURL; //find out the WaterOneFlow version of this web service _serviceInfo = serviceInfo; _serviceInfo.Version = WebServiceHelper.GetWaterOneFlowVersion(_serviceURL); //assign the waterOneFlow parser _parser = new ParserFactory().GetParser(ServiceInfo); SaveXmlFiles = false; // false on webserver }
/// <summary> /// Creates a new instance of a WaterOneFlow web service client /// which communicates with the specified web service. /// </summary> /// <param name="serviceInfo">The object with web service information</param> /// <param name="reqTimeOut">Request timeout, in seconds</param> /// <param name="valuesPerReq">Number of values per request</param> /// <param name="allInOneRequest">All values in one request</param> /// <remarks>Throws an exception if the web service is not a valid /// WaterOneFlow service</remarks> public WaterOneFlowClient(DataServiceInfo serviceInfo, int reqTimeOut = 100, int valuesPerReq = 10000, bool allInOneRequest = false) { _serviceURL = serviceInfo.EndpointURL; _valuesPerReq = valuesPerReq; _allInOneRequest = allInOneRequest; _serviceInfo = serviceInfo; _reqTimeOut = reqTimeOut; _serviceInfo.Version = WebServiceHelper.GetWaterOneFlowVersion(_serviceURL); _parser = ParserFactory.GetParser(ServiceInfo); SaveXmlFiles = true; // for backward-compatibility }
public IWaterOneFlowParser GetParser(DataServiceInfo dataService) { IWaterOneFlowParser parser; switch (dataService.Version.ToString("F1", CultureInfo.InvariantCulture)) { case "1.0": parser = new WaterOneFlow10Parser(); break; default: parser = new WaterOneFlow11Parser(); break; } return(parser); }
public DataServiceInfo ReadWaterOneFlowServiceInfo(string portalPageId) { DataServiceInfo serviceInfo = null; // Create the URL to the descriptive info about the registered item on the HydroPortal string url = _baseUrl + "/rest/document?id={" + portalPageId + "}"; // Determine if this is registered using the FGDC standard or Dublin Core standard, or neither string response = WebOperations.DownloadASCII(url); int index = response.IndexOf("<ServiceType>CUAHSIService</ServiceType>"); if (index > -1) { // FGDC Standard index = response.IndexOf("<metstdn>FGDC Content Standards for Digital Geospatial</metstdn>"); if (index > -1) { index = response.IndexOf("<WaterOneFlowURL>"); if (index > -1) { serviceInfo = ParseFgdcPage(url); } } } //else //{ // index = response.IndexOf ( "<dc:contributor>The Dublin Core Metadata Initiative</dc:contributor>" ); // if ( index > -1 ) // { // // Dublin Core Standard // string detailsUrl = _baseUrl + "/catalog/search/viewMetadataDetails.page?uuid={" + portalPageId + "}"; // response = WebOperations.DownloadASCII ( detailsUrl ); // index = response.IndexOf ( "<td class=\"parameterLabel\">WaterOneFlow URL</td>" ); // if ( index > -1 ) // { // serviceInfo = ParseDublinCorePage ( url ); // } // } //} return(serviceInfo); }
public void CanSaveOneSeries() { Random random = new Random(); string url = @"http://his.crwr.utexas.edu/TXEvap/cuahsi_1_0.asmx"; MetadataCacheManagerSQL manager = TestConfig.MetadataCacheManager; WaterOneFlowClient client = new WaterOneFlowClient(url); IList <Site> sites = client.GetSites(); IList <SeriesMetadata> seriesList = client.GetSiteInfo(sites[0].Code); SeriesMetadata firstSeries = seriesList[0]; DataServiceInfo service = GeDatatService(random.Next()); manager.SaveDataService(service); firstSeries.DataService = service; manager.SaveSeries(firstSeries, service); }
private DataServiceInfo GeDatatService(int identifier) { string url = @"http://water.sdsc.edu/wateroneflow/NWIS/DailyValues.asmx"; DataServiceInfo service = new DataServiceInfo(url, "nwis daily values"); service.Id = identifier; service.DescriptionURL = url; service.ServiceTitle = "NWIS Daily values"; service.ServiceCode = "NWISDV"; service.ServiceType = "WaterOneFlow service"; service.ServiceName = "WaterOneFlow"; service.Protocol = "SOAP"; service.Version = 1.1; service.NorthLatitude = 90.0; service.SouthLatitude = -90.0; service.EastLongitude = 180.0; service.WestLongitude = -180.0; service.ContactName = "unknown"; service.ContactEmail = "unknown"; service.Abstract = "unknown"; service.Citation = "unknown"; return(service); }
/// <summary> /// This method finds the WaterOneFlow version of the web service and assigns /// this information to the ServiceInfo object /// </summary> /// <param name="serviceInfo">the web service to be checked</param> private void AssignWaterOneFlowVersion(DataServiceInfo serviceInfo) { _serviceInfo.Version = WebServiceHelper.GetWaterOneFlowVersion(_asmxURL); }
/// <summary> /// Saves a new data service object to the database. If an entry with the same /// web service URL already exists in the database, update it. /// </summary> /// <param name="service">the ServiceInfo object to be saved to the DB</param> public void SaveDataService(DataServiceInfo service) { if (!columnExists("SiteCount")) { addColumn("SiteCount"); } if (!columnExists("VariableCount")) { addColumn("VariableCount"); } const string sqlInsert = "INSERT INTO DataServices(" + "ServiceCode, ServiceName, ServiceType, ServiceVersion, ServiceProtocol, " + "ServiceEndpointURL, ServiceDescriptionURL, NorthLatitude, SouthLatitude, EastLongitude, WestLongitude, " + "Abstract, ContactName, ContactEmail, Citation, IsHarvested, HarveDateTime, ServiceTitle, SiteCount, VariableCount) " + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; using (DbConnection conn = _db.CreateConnection()) { conn.Open(); using (DbTransaction tran = conn.BeginTransaction()) { using (DbCommand cmd = conn.CreateCommand()) { cmd.CommandText = sqlInsert; cmd.Parameters.Add(_db.CreateParameter(DbType.String, service.ServiceCode)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, service.ServiceName)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, service.ServiceType)); cmd.Parameters.Add(_db.CreateParameter(DbType.Double, service.Version)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, service.Protocol)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, service.EndpointURL)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, service.DescriptionURL)); cmd.Parameters.Add(_db.CreateParameter(DbType.Double, service.NorthLatitude)); cmd.Parameters.Add(_db.CreateParameter(DbType.Double, service.SouthLatitude)); cmd.Parameters.Add(_db.CreateParameter(DbType.Double, service.EastLongitude)); cmd.Parameters.Add(_db.CreateParameter(DbType.Double, service.WestLongitude)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, service.Abstract)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, service.ContactName)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, service.ContactEmail)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, service.Citation)); cmd.Parameters.Add(_db.CreateParameter(DbType.Boolean, service.IsHarvested)); cmd.Parameters.Add(_db.CreateParameter(DbType.DateTime, service.HarveDateTime)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, service.ServiceTitle)); cmd.Parameters.Add(_db.CreateParameter(DbType.Int32, service.SiteCount)); cmd.Parameters.Add(_db.CreateParameter(DbType.Int32, service.VariableCount)); cmd.ExecuteNonQuery(); } tran.Commit(); } } }
private DataServiceInfo ServiceFromDataRow(System.Data.DataRow row) { DataServiceInfo dsi = new DataServiceInfo(); dsi.Id = DataReader.ReadInteger(row["ServiceID"]); dsi.ServiceCode = DataReader.ReadString(row["ServiceCode"]); dsi.ServiceName = DataReader.ReadString(row["ServiceName"]); dsi.ServiceType = DataReader.ReadString(row["ServiceType"]); dsi.Version = DataReader.ReadDouble(row["ServiceVersion"]); dsi.Protocol = DataReader.ReadString(row["ServiceProtocol"]); dsi.EndpointURL = DataReader.ReadString(row["ServiceEndpointURL"]); dsi.DescriptionURL = DataReader.ReadString(row["ServiceDescriptionURL"]); dsi.NorthLatitude = DataReader.ReadDouble(row["NorthLatitude"]); dsi.SouthLatitude = DataReader.ReadDouble(row["SouthLatitude"]); dsi.EastLongitude = DataReader.ReadDouble(row["EastLongitude"]); dsi.WestLongitude = DataReader.ReadDouble(row["WestLongitude"]); dsi.Abstract = DataReader.ReadString(row["Abstract"]); dsi.ContactEmail = DataReader.ReadString(row["ContactEmail"]); dsi.ContactName = DataReader.ReadString(row["ContactName"]); dsi.Citation = DataReader.ReadString(row["Citation"]); dsi.IsHarvested = DataReader.ReadBoolean(row["IsHarvested"]); dsi.HarveDateTime = DataReader.ReadDateTime(row["HarveDateTime"]); dsi.ServiceTitle = DataReader.ReadString(row["ServiceTitle"]); dsi.ValueCount = DataReader.ReadInteger(row["ValueCount"]); dsi.SiteCount = DataReader.ReadInteger(row["SiteCount"]); dsi.VariableCount = DataReader.ReadInteger(row["VariableCount"]); return dsi; }
private SeriesMetadata SeriesFromDataRow(DataRow row) { Site site = new Site(); site.Name = Convert.ToString(row["SiteName"]); site.Code = Convert.ToString(row["SiteCode"]); site.Latitude = Convert.ToDouble(row["Latitude"]); site.Longitude = Convert.ToDouble(row["Longitude"]); Variable v = new Variable(); v.Name = Convert.ToString(row["VariableName"]); v.Code = Convert.ToString(row["VariableCode"]); v.DataType = Convert.ToString(row["DataType"]); v.ValueType = Convert.ToString(row["ValueType"]); v.Speciation = Convert.ToString(row["Speciation"]); v.SampleMedium = Convert.ToString(row["SampleMedium"]); v.TimeSupport = Convert.ToDouble(row["TimeSupport"]); v.GeneralCategory = Convert.ToString(row["GeneralCategory"]); v.VariableUnit = Unit.Unknown; v.VariableUnit.Name = Convert.ToString(row["VariableUnitsName"]); v.TimeUnit = Unit.UnknownTimeUnit; v.TimeUnit.Name = Convert.ToString(row["TimeUnitsName"]); Method m = Method.Unknown; //m.Description = Convert.ToString(row["MethodDescription"]); Source src = Source.Unknown; //src.Description = Convert.ToString(row["SourceDescription"]); src.Organization = Convert.ToString(row["Organization"]); src.Citation = Convert.ToString(row["Citation"]); QualityControlLevel qc = QualityControlLevel.Unknown; //qc.Code = Convert.ToString(row["QualityControlLevelCode"]); //qc.Definition = Convert.ToString(row["QualityControlLevelDefinition"]); SeriesMetadata newSeries = new SeriesMetadata(site, v, m, qc, src); newSeries.BeginDateTime = Convert.ToDateTime(row["BeginDateTime"]); newSeries.EndDateTime = Convert.ToDateTime(row["EndDateTime"]); newSeries.BeginDateTimeUTC = Convert.ToDateTime(row["BeginDateTimeUTC"]); newSeries.EndDateTimeUTC = Convert.ToDateTime(row["EndDateTimeUTC"]); newSeries.ValueCount = Convert.ToInt32(row["ValueCount"]); DataServiceInfo servInfo = new DataServiceInfo(); servInfo.EndpointURL = Convert.ToString(row["ServiceEndpointURL"]); //servInfo.ServiceCode = Convert.ToString(row["ServiceCode"]); newSeries.DataService = servInfo; return newSeries; }
private void button2_Click(object sender, EventArgs e) { variablesListBox.Enabled = false; urlTextbox.Enabled = false; titleTextbox.Enabled = false; button1.Enabled = false; button2.Enabled = false; button3.Enabled = false; button4.Enabled = false; waterOneFlowClient = new WaterOneFlowClient(urlTextbox.Text); var waterOneFlowServiceInfo = waterOneFlowClient.ServiceInfo; // Trim the query off of the URL if it still exists int index = waterOneFlowServiceInfo.EndpointURL.IndexOf("?"); if (index > -1) { waterOneFlowServiceInfo.EndpointURL = waterOneFlowServiceInfo.EndpointURL.Substring(0, index); } var serviceInfo = new DataServiceInfo(); serviceInfo.IsHarvested = false; serviceInfo.ServiceName = waterOneFlowServiceInfo.ServiceName; serviceInfo.Version = waterOneFlowServiceInfo.Version; serviceInfo.ServiceType = waterOneFlowServiceInfo.ServiceType; serviceInfo.Protocol = waterOneFlowServiceInfo.Protocol; serviceInfo.VariableCount = waterOneFlowServiceInfo.VariableCount; IList <Site> siteList; siteList = waterOneFlowClient.GetSites(); // Default extent for the service. These values are designed to be overwritten as we query sites in the service double east = -180; double west = 360; double north = -90; double south = 90; int valueCount = 0; var totalDataCartSeriesList = new List <SeriesDataCart>(); foreach (var site in siteList) { // Get series for this site IList <SeriesMetadata> currentSeriesList; var dataCartSeriesList = new List <SeriesDataCart>(); try { currentSeriesList = waterOneFlowClient.GetSiteInfo(site.Code); } catch (WebException ex) { continue; } catch (Exception ex) { continue; } // Update service extent if (site.Latitude > north) { north = site.Latitude; } if (site.Latitude < south) { south = site.Latitude; } if (site.Longitude > east) { east = site.Longitude; } if (site.Longitude < west) { west = site.Longitude; } // Save series info to metadata cache database foreach (var series in currentSeriesList) { valueCount += series.ValueCount; try { if (checkedVariables.Count != 0) { if (checkedVariables.Contains(series.Variable.Name)) { var seriesDataCart = getDataCartFromMetadata(series, waterOneFlowServiceInfo); dataCartSeriesList.Add(seriesDataCart); } } else { var seriesDataCart = getDataCartFromMetadata(series, waterOneFlowServiceInfo); dataCartSeriesList.Add(seriesDataCart); } } catch (Exception ex) { continue; } } totalDataCartSeriesList.AddRange(dataCartSeriesList); variablesListBox.Enabled = true; urlTextbox.Enabled = true; titleTextbox.Enabled = true; button1.Enabled = true; button2.Enabled = true; button3.Enabled = true; button4.Enabled = true; } // Update service info serviceInfo.IsHarvested = true; serviceInfo.HarveDateTime = DateTime.Now; serviceInfo.EastLongitude = east; serviceInfo.WestLongitude = west; serviceInfo.NorthLatitude = north; serviceInfo.SouthLatitude = south; serviceInfo.SiteCount = siteList.Count; serviceInfo.ValueCount = valueCount; serviceInfo.VariableCount = waterOneFlowServiceInfo.VariableCount; SearchResult resultFeatureSet = null; if (totalDataCartSeriesList.Count > 0) { resultFeatureSet = SearchHelper.ToFeatureSetsByDataSource(totalDataCartSeriesList); } if (resultFeatureSet != null) { //We need to reproject the Search results from WGS84 to the projection of the map. var wgs84 = KnownCoordinateSystems.Geographic.World.WGS1984; foreach (var item in resultFeatureSet.ResultItems) { item.FeatureSet.Projection = wgs84; } var layers = ShowSearchResults(resultFeatureSet); Debug.WriteLine("ShowSearchResults done."); // Unselect all layers in legend (http://hydrodesktop.codeplex.com/workitem/8559) App.Map.MapFrame.GetAllLayers().ForEach(r => r.IsSelected = false); // Select first search result layer var first = layers.FirstOrDefault().GetParentItem(); if (first != null) { first.IsSelected = true; } // Unselect "Map Layers" legend item (http://hydrodesktop.codeplex.com/workitem/8458) App.Legend.RootNodes .ForEach(delegate(ILegendItem item) { if (item.LegendText == "Map Layers") { item.IsSelected = false; } }); Debug.WriteLine("Finished."); } }
/// <summary> /// Parses a HydroPortal page for a WaterOneFlow service registered using the Dublin Core metadata standard. /// </summary> /// <param name="pageUrl">The URL to the HydroPortal page describing the service</param> /// <returns>If the page describes a WaterOneFlow service, a DataServiceInfo object describing the service is returned</returns> private DataServiceInfo ParseDublinCorePage(string pageUrl) { DataServiceInfo serviceInfo = new DataServiceInfo(); try { using (XmlTextReader reader = new XmlTextReader(pageUrl)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { // Abstract if (reader.Name.ToLower() == "dc:description") { reader.Read(); serviceInfo.Abstract = reader.Value; } // Bounding Box else if (reader.Name == "ows:WGS84BoundingBox") { double west = 0; double east = 0; double north = 0; double south = 0; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "ows:LowerCorner") { reader.Read(); string[] lowerCorner = reader.Value.Split(' '); if (lowerCorner.Length == 2) { double.TryParse(lowerCorner[0], out west); double.TryParse(lowerCorner[1], out south); } } else if (reader.Name == "ows:UpperCorner") { reader.Read(); string[] upperCorner = reader.Value.Split(' '); if (upperCorner.Length == 2) { double.TryParse(upperCorner[0], out east); double.TryParse(upperCorner[1], out north); } } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "ows:WGS84BoundingBox") { break; } } serviceInfo.EastLongitude = east; serviceInfo.WestLongitude = west; serviceInfo.NorthLatitude = north; serviceInfo.SouthLatitude = south; } // Service Code else if (reader.Name.ToLower() == "dc:title") { reader.Read(); serviceInfo.ServiceCode = reader.Value; } // Service Endpoint URL else if (reader.Name.ToLower() == "dc:creator") { reader.Read(); serviceInfo.EndpointURL = WebOperations.GetCanonicalUri(reader.Value, true); } // Service Description URL else if (reader.Name == "dct:references") { reader.Read(); serviceInfo.DescriptionURL = reader.Value; } // Service Title else if (reader.Name.ToLower() == "dct:alternative") { reader.Read(); serviceInfo.ServiceTitle = reader.Value; } } } } } catch (Exception ex) { throw new WebException("Could not read XML response from " + pageUrl + ".\n" + ex.Message); } return(serviceInfo); }
/// <summary> /// Parses a HydroPortal page for a WaterOneFlow service registered using the FGDC metadata standard. /// </summary> /// <param name="pageUrl">The URL to the HydroPortal page describing the service</param> /// <returns>If the page describes a WaterOneFlow service, a DataServiceInfo object describing the service is returned</returns> private DataServiceInfo ParseFgdcPage(string pageUrl) { DataServiceInfo serviceInfo = new DataServiceInfo(); try { using (XmlTextReader reader = new XmlTextReader(pageUrl)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { // Abstract if (reader.Name.ToLower() == "abstract") { reader.Read(); serviceInfo.Abstract = reader.Value; } // Citation else if (reader.Name.ToLower() == "citation") { string origin = "(unknown author)"; string title = "(unknown title)"; string pubplace = "(unknown organization)"; string pubdate = "unknown date"; string link = "(unknown link)"; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name.ToLower() == "origin") { reader.Read(); if (reader.Value.Trim() != String.Empty) { origin = reader.Value; } } else if (reader.Name.ToLower() == "title") { reader.Read(); if (reader.Value.Trim() != String.Empty) { title = reader.Value; } } else if (reader.Name.ToLower() == "pubplace") { reader.Read(); if (reader.Value.Trim() != String.Empty) { pubplace = reader.Value; } } else if (reader.Name.ToLower() == "pubdate") { reader.Read(); if (reader.Value.Trim() != String.Empty) { pubdate = reader.Value; } } else if (reader.Name.ToLower() == "onlink") { reader.Read(); if (reader.Value.Trim() != String.Empty) { link = reader.Value; } } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "citation") { break; } } serviceInfo.Citation = origin + ". " + title + ". " + pubdate + ". " + pubplace + ". <" + link + ">."; } // Contact Name and Email else if (reader.Name.ToLower() == "ptcontac") { string contactName = ""; string contactEmail = ""; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name.ToLower() == "cntper") { reader.Read(); contactName = reader.Value; } else if (reader.Name.ToLower() == "cntemail") { reader.Read(); contactEmail = reader.Value; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "ptcontac") { break; } } serviceInfo.ContactEmail = contactEmail; serviceInfo.ContactName = contactName; } // Bounding Box else if (reader.Name == "bounding") { double west = 0; double east = 0; double north = 0; double south = 0; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name.ToLower() == "westbc") { reader.Read(); double.TryParse(reader.Value, out west); } else if (reader.Name.ToLower() == "eastbc") { reader.Read(); double.TryParse(reader.Value, out east); } else if (reader.Name.ToLower() == "northbc") { reader.Read(); double.TryParse(reader.Value, out north); } else if (reader.Name.ToLower() == "southbc") { reader.Read(); double.TryParse(reader.Value, out south); } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "bounding") { break; } } serviceInfo.EastLongitude = east; serviceInfo.WestLongitude = west; serviceInfo.NorthLatitude = north; serviceInfo.SouthLatitude = south; } // Service Code else if (reader.Name == "ServiceCode") { reader.Read(); serviceInfo.ServiceCode = reader.Value; } // Service Endpoint URL else if (reader.Name == "WaterOneFlowURL") { reader.Read(); serviceInfo.EndpointURL = WebOperations.GetCanonicalUri(reader.Value, true); } // Service Description URL else if (reader.Name == "MapServiceURL") { reader.Read(); serviceInfo.DescriptionURL = reader.Value; } // Service Title else if (reader.Name == "ServiceName") { reader.Read(); serviceInfo.ServiceTitle = reader.Value; } } } } } catch (Exception ex) { throw new WebException("Could not read XML response from " + pageUrl + ".\n" + ex.Message); } return(serviceInfo); }
/// <summary> /// Adds Multiple Services from the DataGrid input of this form /// </summary> private List <DataServiceInfo> GetMultipleServiceRows() { // Build a list of URLs to check List <DataServiceInfo> rows = new List <DataServiceInfo>(); foreach (DataGridViewRow serviceRow in dgvAddServices.Rows) { if (serviceRow.IsNewRow == false) { object cellValue = serviceRow.Cells[1].Value; if (cellValue != null) { string serviceUrl = cellValue.ToString().Trim(); // Trim the query off of the URL int index = serviceUrl.IndexOf("?"); if (index > -1) { serviceUrl = serviceUrl.Substring(0, index); } DataServiceInfo dataServiceInfo = new DataServiceInfo(); dataServiceInfo.EndpointURL = serviceUrl; dataServiceInfo.ServiceTitle = serviceRow.Cells[0].Value.ToString().Trim(); if (serviceRow.Cells[2].Value != null) { dataServiceInfo.ServiceCode = serviceRow.Cells[2].Value.ToString().Trim(); } if (serviceRow.Cells[3].Value != null) { dataServiceInfo.Citation = serviceRow.Cells[3].Value.ToString().Trim(); } if (serviceRow.Cells[4].Value != null) { dataServiceInfo.Abstract = serviceRow.Cells[4].Value.ToString().Trim(); } if (serviceRow.Cells[5].Value != null) { dataServiceInfo.DescriptionURL = serviceRow.Cells[5].Value.ToString().Trim(); } if (serviceRow.Cells[6].Value != null) { dataServiceInfo.ContactName = serviceRow.Cells[6].Value.ToString().Trim(); } if (serviceRow.Cells[7].Value != null) { dataServiceInfo.ContactEmail = serviceRow.Cells[7].Value.ToString().Trim(); } rows.Add(dataServiceInfo); } } } return(rows); }
/// <summary> /// For each service described in the data grid view, adds records to the metadata cache database to describe the service /// </summary> /// <param name="servicesToAdd">List of services to add to the metadata cache database</param> /// <param name="e">Parameters from the BackgroundWorker</param> /// <returns>Parameters (task type, output message, rows that were successfully added) to be processed by a BackgroundWorker event handler</returns> private object[] AddServicesToDatabase(List <DataServiceInfo> servicesToAdd, DoWorkEventArgs e) { // Build parameters to pass to the background worker object[] parameters = new object[3]; parameters[0] = BackgroundWorkerTasks.UpdateDatabase; parameters[1] = "Operation cancelled"; List <int> rowsToSelect = new List <int> (); bgwMain.ReportProgress(0, "Getting list of existing WaterOneFlow services from database..."); // Get a list of existing URLs from the metadata cache databsae List <string> existingUrls = DatabaseOperations.GetCacheServiceUrls(true); // Add service records to the database int totalSteps = servicesToAdd.Count; int currentStep = 0; int countAlreadyExists = 0; int countInvalidService = 0; IEqualityComparer <string> comparer = new CaseInsensitiveEqualityComparer(); MetadataCacheManagerSQL cacheManager = DatabaseOperations.GetCacheManager(); for (int i = 0; i < servicesToAdd.Count; i++) { if (bgwMain.CancellationPending) { e.Cancel = true; return(parameters); } currentStep++; bgwMain.ReportProgress(100 * currentStep / totalSteps, "Checking service " + currentStep + " of " + totalSteps + "..."); DataServiceInfo serviceInfo = servicesToAdd[i]; // Check if the service already exists in the database if (existingUrls.Contains(serviceInfo.EndpointURL, comparer) == true) { countAlreadyExists += 1; continue; } // Check that the URL is for a live service if (this.mnuCheckForValidService.Checked == true) { // Attempt to create a WaterOneFlowServiceClient from the URL. If the URL is not for a WaterOneFlow service, an error is thrown in the constructor. try { WaterOneFlowClient waterOneFlowClient = new WaterOneFlowClient(serviceInfo.EndpointURL); DataServiceInfo clientServiceInfo = waterOneFlowClient.ServiceInfo; serviceInfo.ServiceName = clientServiceInfo.ServiceName; serviceInfo.Protocol = clientServiceInfo.Protocol; serviceInfo.ServiceType = clientServiceInfo.ServiceType; serviceInfo.Version = clientServiceInfo.Version; } catch { countInvalidService += 1; continue; } } // Save the service cacheManager.SaveDataService(serviceInfo); existingUrls.Add(serviceInfo.EndpointURL); rowsToSelect.Add(i); } // Prepare a message to the user string message = ""; int serviceCount = rowsToSelect.Count; if (serviceCount == 0) { message += "No new services added to metadata cache database.\n\n "; } else if (serviceCount == 1) { message += "1 new service added to metadata cache database.\n\n"; } else { message += serviceCount.ToString() + " new services added to metadata cache database.\n\n"; } if (countAlreadyExists == 1) { message += "1 service was not added because it already exists in the database.\n\n"; } else if (countAlreadyExists > 1) { message += countAlreadyExists.ToString() + " services were not added because they already exist in the database.\n\n"; } if (countInvalidService == 1) { message += "1 service was not added because it does not point to a valid WaterOneFlow service.\n\n"; } else if (countInvalidService > 1) { message += countInvalidService.ToString() + " services were not added because they do not point to a valid WaterOneFlow service.\n\n"; } if (serviceCount == 1) { message += "Remember to download metadata for this service in the Metadata Fetcher window."; } else if (serviceCount > 1) { message += "Remember to download metadata for these services in the Metadata Fetcher window."; } parameters[1] = message; parameters[2] = rowsToSelect; return(parameters); }
/// <summary> /// Finds rows for services in the view for which a record already exists in the metadata cache database with the same URL /// </summary> /// <param name="rows">List of DataServiceInfo objects whose URLs we want to check (the service URL is assumed to have come from a row in an object such as a data grid view)</param> /// <param name="e">Parameters from the BackgroundWorker</param> /// <returns>Parameters (task type, output message, rows for which a record already exists in the metadata cache database with the same URL) to be processed by a BackgroundWorker event handler</returns> private object[] CheckForServicesInCache(List <DataServiceInfo> rows, DoWorkEventArgs e) { // Build parameters to pass to the background worker object[] parameters = new object[3]; parameters[0] = BackgroundWorkerTasks.CheckForExisingServices; parameters[1] = "Operation cancelled"; List <int> rowsToSelect = new List <int> (); // Get a list of existing URLs from the metadata cache databsae if (e != null) { bgwMain.ReportProgress(0, "Getting list of existing WaterOneFlow services from database..."); } List <string> existingUrls = DatabaseOperations.GetCacheServiceUrls(true); // Check all items in the view int totalSteps = rows.Count; int currentStep = 0; IEqualityComparer <string> comparer = new CaseInsensitiveEqualityComparer(); for (int i = 0, len = rows.Count; i < len; i++) { DataServiceInfo row = rows[i]; if (e != null) { if (bgwMain.CancellationPending) { e.Cancel = true; return(parameters); } currentStep++; bgwMain.ReportProgress(100 * currentStep / totalSteps, "Checking service " + currentStep + " of " + totalSteps + "..."); } string serviceUrl = row.EndpointURL; if (existingUrls.Contains(serviceUrl, comparer) == true) { rowsToSelect.Add(i); } } // Prepare a message to the user // TODO: This message should be created outside of this service, and instead should be done in the display logic string message = ""; int existingCount = rowsToSelect.Count; if (existingCount == 0) { message = "No services with the same URL were found in the metadata cache database"; } else if (existingCount == 1) { message = "1 service has a URL that already exists in the metadata cache database. This service has been selected."; } else { message = existingCount.ToString() + " services have URLs that already exist in the metadata cache database. These services have been selected."; } parameters[1] = message; parameters[2] = rowsToSelect; return(parameters); }
/// <summary> /// Parse the response from a GetWaterOneFlowServices request to HIS Server. The response should be a string formatted as XML /// </summary> /// <param name="xmlResponse">Response from the web service</param> /// <returns>List of DataServiceInfo objects for each WaterOneFlow web service found</returns> private IList <DataServiceInfo> ParseGetWaterOneFlowServicesResponse(string xmlResponse) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlResponse); XmlNodeList records = xmlDoc.SelectNodes("//Record"); List <DataServiceInfo> resultList = new List <DataServiceInfo> (); foreach (XmlNode record in records) { // WaterOneFlow Service URL XmlNode node = record.SelectSingleNode("WaterOneFlowWSDL"); string asmxUrl = String.Empty; if (node != null) { asmxUrl = node.InnerText; } int index = asmxUrl.IndexOf("?"); if (index > -1) { asmxUrl = asmxUrl.Substring(0, index); } if (asmxUrl == String.Empty) { continue; } // Title node = record.SelectSingleNode("Title"); string title = "(title)"; if (node != null && node.InnerText != String.Empty) { title = node.InnerText; } // Abstract node = record.SelectSingleNode("Abstract"); string serviceAbstract = String.Empty; if (node != null) { serviceAbstract = node.InnerText; } // Citation node = record.SelectSingleNode("Citation"); string citation = String.Empty; if (node != null) { citation = node.InnerText; } // Contact Email node = record.SelectSingleNode("DatasetContact/EmailAddress"); string contactEmail = String.Empty; if (node != null) { contactEmail = node.InnerText; } // Contact Name node = record.SelectSingleNode("DatasetContact/FirstName"); string contactName = String.Empty; if (node != null) { contactName = node.InnerText; } node = record.SelectSingleNode("DatasetContact/LastName"); if (node != null) { if (contactName != String.Empty) { contactName += " " + node.InnerText; } else { contactName = node.InnerText; } } // North node = record.SelectSingleNode("NorthExtent"); double north = 90; if (node != null) { if (Double.TryParse(node.InnerText, out north) == false) { north = 90; } } // South node = record.SelectSingleNode("SouthExtent"); double south = -90; if (node != null) { if (Double.TryParse(node.InnerText, out south) == false) { south = -90; } } // East node = record.SelectSingleNode("EastExtent"); double east = 180; if (node != null) { if (Double.TryParse(node.InnerText, out east) == false) { east = 180; } } // West node = record.SelectSingleNode("WestExtent"); double west = -180; if (node != null) { if (Double.TryParse(node.InnerText, out west) == false) { west = -180; } } // Add the service info to the list DataServiceInfo serviceInfo = new DataServiceInfo(asmxUrl, title); serviceInfo.Abstract = serviceAbstract; serviceInfo.Citation = citation; serviceInfo.ContactEmail = contactEmail; serviceInfo.ContactName = contactName; serviceInfo.EastLongitude = east; serviceInfo.WestLongitude = west; serviceInfo.NorthLatitude = north; serviceInfo.SouthLatitude = south; resultList.Add(serviceInfo); } return(resultList); }
/// <summary> /// build HD data model to store time-series data /// </summary> /// <param name="link">the link that was added to the composition</param> public void CreateSeries(ILink link) { #region Create DataModel Objects [HACK] //---- create variable unit HydroDesktop.Interfaces.ObjectModel.Unit VarUnit = new HydroDesktop.Interfaces.ObjectModel.Unit(); VarUnit.Name = link.SourceQuantity.Unit.Description; //defined by link VarUnit.Abbreviation = link.SourceQuantity.Unit.ID; //defined by link VarUnit.UnitsType = link.SourceQuantity.ID; //defined by link //---- create time unit HydroDesktop.Interfaces.ObjectModel.Unit TimeUnit = new HydroDesktop.Interfaces.ObjectModel.Unit(); TimeUnit.Name = "second"; //default value (cannot be changed) TimeUnit.Abbreviation = "s"; //default value (cannot be changed) TimeUnit.UnitsType = "Time"; //default value (cannot be changed) //create unit //HydroDesktop.Interfaces.ObjectModel.Unit unit = new HydroDesktop.Interfaces.ObjectModel.Unit(); //unit.Abbreviation = link.SourceQuantity.Unit.ID; //---- create method HydroDesktop.Interfaces.ObjectModel.Method method = new Method(); method.Link = link.SourceComponent.ModelID; method.Link = "none"; //*default value method.Description = link.SourceComponent.ModelDescription; //*default value if (link.SourceComponent.ComponentDescription == null) { method.Description = "none"; } //---- define data service info DataServiceInfo dataservice = new DataServiceInfo(); dataservice.Abstract = "none"; //*default value dataservice.Citation = "none"; //*default value dataservice.ContactEmail = "none"; //*default value dataservice.ContactName = "none"; //*default value dataservice.EastLongitude = -999; //*default value dataservice.HarveDateTime = DateTime.Now; //*default value dataservice.Id = -999; //*default value dataservice.NorthLatitude = -999; //*default value dataservice.HISCentralID = -999; //*default value dataservice.ServiceCode = "none"; //*default value dataservice.DescriptionURL = "none"; //*default value dataservice.EndpointURL = "none"; //*default value dataservice.ServiceName = "none"; //*default value dataservice.Protocol = "none"; //*default value dataservice.ServiceTitle = "none"; //*default value dataservice.ServiceType = "none"; //*default value dataservice.Version = -999; //*default value dataservice.SiteCount = link.SourceElementSet.ElementCount; //defined by link //---- create metadata ISOMetadata meta = new ISOMetadata(); meta.Abstract = "none"; //*default value meta.Id = -999; //*default value meta.ProfileVersion = "none"; //*default value meta.Title = "none"; //*default value meta.TopicCategory = "none"; //*default value meta.MetadataLink = "none"; //*default value //---- create source Source source = new Source(); source.Organization = "University of South Carolina"; //*default value source.Address = "300 Main St."; //*default value source.Citation = "none"; //*default value source.City = "Columbia"; //*default value source.ContactName = "none"; //*default value source.Description = "none"; //*default value source.Email = "none"; //*default value source.Id = -999; //*default value source.Link = "none"; //*default value source.OriginId = -999; //*default value source.Phone = "none"; //*default value source.State = "SC"; //*default value source.ZipCode = 29206; //*default value source.ISOMetadata = meta; //---- create variable Variable variable = new Variable(); variable.Code = link.SourceQuantity.Description; //defined by link variable.Name = link.SourceQuantity.ID; //defined by link variable.VariableUnit = VarUnit; //defined by link variable.TimeUnit = TimeUnit; //defined by link variable.Speciation = "H20"; //*default value variable.GeneralCategory = "Hydrology"; //*default value variable.NoDataValue = -999; //*default value variable.SampleMedium = "Surface Water"; //*default value variable.TimeSupport = 1; //TODO: determine in finish variable.VocabularyPrefix = "none"; //*default value variable.ValueType = "Model Simulation Result"; //*default value variable.DataType = "Incremental"; //*default value //---- create qualControl QualityControlLevel qualControl = new QualityControlLevel(); qualControl.Code = "qual1"; //*default value qualControl.Definition = "Quality control level 1"; //*default value qualControl.Id = 1; //*default value qualControl.Explanation = "unknown"; //*default value qualControl.OriginId = -999; //*default value #endregion #region Build Sites //RepositoryManagerSQL db = null; //check to see if the database path is overridden if (conn != null) { // db = new RepositoryManagerSQL(DatabaseTypes.SQLite, conn); } else { //db = new RepositoryManagerSQL(DatabaseTypes.SQLite, Settings.Instance.DataRepositoryConnectionString); //conn = Settings.Instance.DataRepositoryConnectionString; } //---- override default db info with those provided by omi //-- standard omi args if (dbargs.ContainsKey("Method.Description")) { method.Description = dbargs["Method.Description"]; } if (dbargs.ContainsKey("Source.Organization")) { source.Organization = dbargs["Source.Organization"]; } if (dbargs.ContainsKey("Source.Address")) { source.Address = dbargs["Source.Address"]; } if (dbargs.ContainsKey("Source.City")) { source.City = dbargs["Source.City"]; } if (dbargs.ContainsKey("Source.State")) { source.State = dbargs["Source.State"]; } if (dbargs.ContainsKey("Source.Zip")) { source.ZipCode = Convert.ToInt32(dbargs["Source.Zip"]); } if (dbargs.ContainsKey("Source.Contact")) { source.ContactName = dbargs["Source.Contact"]; } if (dbargs.ContainsKey("Variable.Category")) { variable.GeneralCategory = dbargs["Variable.Category"]; } if (dbargs.ContainsKey("Variable.SampleMedium")) { variable.SampleMedium = dbargs["Variable.SampleMedium"]; } //-extra omi args if (dbargs.ContainsKey("Method.Link")) { method.Link = dbargs["Method.Link"]; } if (dbargs.ContainsKey("DataService.Abstract")) { dataservice.Abstract = dbargs["DataService.Abstract"]; } if (dbargs.ContainsKey("DataService.Citation")) { dataservice.Citation = dbargs["DataService.Citation"]; } if (dbargs.ContainsKey("DataService.ContactEmail")) { dataservice.ContactEmail = dbargs["DataService.ContactEmail"]; } if (dbargs.ContainsKey("DataService.ContactName")) { dataservice.ContactName = dbargs["DataService.ContactName"]; } if (dbargs.ContainsKey("DataService.EastLongitude")) { dataservice.EastLongitude = Convert.ToDouble(dbargs["DataService.EastLongitude"]); } if (dbargs.ContainsKey("DataService.HarveDateTime")) { dataservice.HarveDateTime = Convert.ToDateTime(dbargs["DataService.HarveDateTime"]); } if (dbargs.ContainsKey("DataService.ID")) { dataservice.Id = Convert.ToInt64(dbargs["DataService.ID"]); } if (dbargs.ContainsKey("DataService.NorthLatitude")) { dataservice.NorthLatitude = Convert.ToDouble(dbargs["DataService.NorthLatitude"]); } if (dbargs.ContainsKey("DataService.HISCentralID")) { dataservice.HISCentralID = Convert.ToInt32(dbargs["DataService.HISCentralID"]); } if (dbargs.ContainsKey("DataService.ServiceCode")) { dataservice.ServiceCode = dbargs["DataService.ServiceCode"]; } if (dbargs.ContainsKey("DataService.DescriptionURL")) { dataservice.DescriptionURL = dbargs["DataService.DescriptionURL"]; } if (dbargs.ContainsKey("DataService.EndpointURL")) { dataservice.EndpointURL = dbargs["DataService.EndpointURL"]; } if (dbargs.ContainsKey("DataService.ServiceName")) { dataservice.ServiceName = dbargs["DataService.ServiceName"]; } if (dbargs.ContainsKey("DataService.Protocol")) { dataservice.Protocol = dbargs["DataService.Protocol"]; } if (dbargs.ContainsKey("DataService.ServiceTitle")) { dataservice.ServiceTitle = dbargs["DataService.ServiceTitle"]; } if (dbargs.ContainsKey("DataService.ServiceType")) { dataservice.ServiceType = dbargs["DataService.ServiceType"]; } if (dbargs.ContainsKey("DataService.Version")) { dataservice.Version = Convert.ToDouble(dbargs["DataService.Version"]); } if (dbargs.ContainsKey("ISOMetadata.Abstract")) { meta.Abstract = dbargs["ISOMetadata.Abstract"]; } if (dbargs.ContainsKey("ISOMetadata.ID")) { meta.Id = Convert.ToInt64(dbargs["ISOMetadata.ID"]); } if (dbargs.ContainsKey("ISOMetadata.ProfileVersion")) { meta.ProfileVersion = dbargs["ISOMetadata.ProfileVersion"]; } if (dbargs.ContainsKey("ISOMetadata.Title")) { meta.Title = dbargs["ISOMetadata.Title"]; } if (dbargs.ContainsKey("ISOMetadata.TopicCategory")) { meta.TopicCategory = dbargs["ISOMetadata.TopicCategory"]; } if (dbargs.ContainsKey("ISOMetadata.MetadataLink")) { meta.MetadataLink = dbargs["ISOMetadata.MetadataLink"]; } if (dbargs.ContainsKey("Source.Citation")) { source.Citation = dbargs["Source.Citation"]; } if (dbargs.ContainsKey("Source.Description")) { source.Description = dbargs["Source.Description"]; } if (dbargs.ContainsKey("Source.Email")) { source.Email = dbargs["Source.Email"]; } if (dbargs.ContainsKey("Source.ID")) { source.Id = Convert.ToInt64(dbargs["Source.ID"]); } if (dbargs.ContainsKey("Source.Link")) { source.Link = dbargs["Source.Link"]; } if (dbargs.ContainsKey("Source.OrginID")) { source.OriginId = Convert.ToInt32(dbargs["Source.OrginID"]); } if (dbargs.ContainsKey("Source.Phone")) { source.Phone = dbargs["Source.Phone"]; } if (dbargs.ContainsKey("Variable.Code")) { variable.Code = dbargs["Variable.Code"]; } if (dbargs.ContainsKey("Variable.Name")) { variable.Name = dbargs["Variable.Name"]; } if (dbargs.ContainsKey("Variable.Speciation")) { variable.Speciation = dbargs["Variable.Speciation"]; } if (dbargs.ContainsKey("Variable.NoDataValue")) { variable.NoDataValue = Convert.ToDouble(dbargs["Variable.NoDataValue"]); } if (dbargs.ContainsKey("Variable.VocabPrefix")) { variable.VocabularyPrefix = dbargs["Variable.VocabPrefix"]; } if (dbargs.ContainsKey("Variable.ValueType")) { variable.ValueType = dbargs["Variable.ValueType"]; } if (dbargs.ContainsKey("Variable.DataValue")) { variable.DataType = dbargs["Variable.DataValue"]; } if (dbargs.ContainsKey("QualityControl.Code")) { qualControl.Code = dbargs["QualityControl.Code"]; } if (dbargs.ContainsKey("QualityControl.Definition")) { qualControl.Definition = dbargs["QualityControl.Definition"]; } if (dbargs.ContainsKey("QualityControl.ID")) { qualControl.Id = Convert.ToInt64(dbargs["QualityControl.ID"]); } if (dbargs.ContainsKey("QualityControl.Explanation")) { qualControl.Explanation = dbargs["QualityControl.Explanation"]; } if (dbargs.ContainsKey("QualityControl.OriginId")) { qualControl.OriginId = Convert.ToInt32(dbargs["QualityControl.OriginId"]); } #region create sites Dictionary <long, Site> sites = new Dictionary <long, Site>(); //loop through all elements in the source components element set for (int i = 0; i < link.SourceElementSet.ElementCount; ++i) { //TODO: Get spatial reference from elementset //---- define spatial reference HydroDesktop.Interfaces.ObjectModel.SpatialReference spatial = new HydroDesktop.Interfaces.ObjectModel.SpatialReference(); spatial.Id = 18; //* spatial.Notes = "NAD27-UTM zone 17N projected coordinate"; //* spatial.SRSID = 26717; //* spatial.SRSName = "NAD27 / UTM zone 17N"; //* //--- create site --- Site site = new Site(); //create a unique site name [variable_model_location] site.Name = (link.SourceElementSet.ID + "_" + link.SourceComponent.ModelID + "_loc" + i.ToString()).Replace(' ', '_'); //check if a sitename already exists in the repository string sql = "SELECT s.SiteCode, s.SiteID " + "FROM Sites s " + "WHERE s.SiteName= '" + site.Name + "' "; DbOperations _db = new DbOperations(conn, DatabaseTypes.SQLite); System.Data.DataTable tbl = _db.LoadTable("values", sql); if (tbl.Rows.Count > 0) { site.Code = tbl.Rows[0].ItemArray[0].ToString(); site.Id = Convert.ToInt32(tbl.Rows[0].ItemArray[1]); } else { //create a new site sql = "SELECT s.SiteCode, s.SiteID FROM Sites s "; _db = new DbOperations(conn, DatabaseTypes.SQLite); tbl = _db.LoadTable("values", sql); int last_row = tbl.Rows.Count - 1; site.Code = site.Name; //-- if the database is not blank if (last_row >= 0) { site.Id = Convert.ToInt32(tbl.Rows[last_row].ItemArray[1]) + 2 + new_series_count; } else { site.Id = new_series_count++; } //add 1 to new series count so that the same site code isn't selected twice new_series_count++; } site.SpatialReference = spatial; site.Comments = "none"; site.County = "none"; site.Elevation_m = -999; site.Latitude = -999; site.LocalProjection = spatial; site.LocalX = -999; site.LocalY = -999; site.Longitude = -999; //--- Attempt to spatially define elements 7-15-2010 --- try { //save site latitude and longitude if (link.SourceElementSet.ElementType == ElementType.XYPoint) { site.Latitude = link.SourceElementSet.GetYCoordinate(i, 0); site.Longitude = link.SourceElementSet.GetXCoordinate(i, 0); site.LocalX = 0; site.LocalY = 0; } else { ////List<Point> points = new List<Point>(); ////for(int p=0; p<= link.SourceElementSet.GetVertexCount(i)-1; p++) ////{ //// Point point = new Point(link.SourceElementSet.GetXCoordinate(i, p), //// link.SourceElementSet.GetYCoordinate(i, p)); //// points.Add(point); ////} //////create polyline ////LineString ls = new LineString(points); ////new SharpMap.CoordinateSystems.ProjectedCoordinateSystem() ////ls.SpatialReference = site.Latitude = link.SourceElementSet.GetYCoordinate(i, 0); site.Longitude = link.SourceElementSet.GetXCoordinate(i, 0); //link.SourceElementSet.SpatialReference.ID; site.LocalX = 0; site.LocalY = 0; } } catch (Exception) { } site.NetworkPrefix = "none"; site.PosAccuracy_m = -999; site.State = "SC"; //* //site.TimeZone = new TimeZoneInfo.TransitionTime(); site.VerticalDatum = "unknown"; //* if (!sites.ContainsKey(site.Id)) { //add site and series to dictionary if they don't already exist sites.Add(site.Id, site); Series series = new Series(site, variable, method, qualControl, source); series.Id = i; if (!serieses.ContainsKey(site.Name)) { serieses.Add(site.Name, series); } //else{serieses.Add(site.Name, series);} } } #endregion #endregion }
/// <summary> /// Saves the series metadata to the metadata cache database. /// This method also automatically saves the site, variable, /// method, source and quality control level of the series. /// </summary> /// <param name="series">The series to be saved</param> /// <param name="dataService">The web service containing the series</param> public void SaveSeries(SeriesMetadata series, DataServiceInfo dataService) { string sqlSite = "SELECT SiteID FROM SitesCache WHERE SiteCode = ?"; string sqlVariable = "SELECT VariableID FROM VariablesCache WHERE VariableCode = ?"; string sqlMethod = "SELECT MethodID FROM MethodsCache WHERE MethodDescription = ?"; string sqlSource = "SELECT SourceID FROM SourcesCache WHERE Organization = ?"; string sqlQuality = "SELECT QualityControlLevelID FROM QualityControlLevelsCache WHERE Definition = ?"; string sqlRowID = "; SELECT LAST_INSERT_ROWID();"; string sqlSaveSite = "INSERT INTO SitesCache(SiteCode, SiteName, Latitude, Longitude, LatLongDatumSRSID, LatLongDatumName, " + "Elevation_m, VerticalDatum, LocalX, LocalY, LocalProjectionSRSID, LocalProjectionName, " + "PosAccuracy_m, State, County, Comments, ServiceID) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + sqlRowID; string sqlSaveVariable = "INSERT INTO variablesCache(VariableCode, VariableName, Speciation, " + "SampleMedium, ValueType, DataType, GeneralCategory, NoDataValue, VariableUnitsName, VariableUnitsType, VariableUnitsAbbreviation, " + "IsRegular, TimeSupport, TimeUnitsName, TimeUnitsType, TimeUnitsAbbreviation, ServiceID) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + sqlRowID; string sqlSaveMethod = "INSERT INTO MethodsCache(OriginMethodID, MethodDescription, MethodLink, ServiceID) VALUES(?, ?, ?, ?)" + sqlRowID; string sqlSaveQualityControl = "INSERT INTO QualityControlLevelsCache(OriginQualityControlLevelID, QualityControlLevelCode, Definition, Explanation) " + "VALUES(?,?,?,?)" + sqlRowID; string sqlSaveSource = "INSERT INTO SourcesCache(OriginSourceID, Organization, SourceDescription, SourceLink, ContactName, Phone, " + "Email, Address, City, State, ZipCode, Citation, MetadataID) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + sqlRowID; string sqlSaveISOMetadata = "INSERT INTO ISOMetadataCache(TopicCategory, Title, Abstract, ProfileVersion, MetadataLink) " + "VALUES(?, ?, ?, ?, ?)" + sqlRowID; string sqlSaveSeries = "INSERT INTO DataSeriesCache(SiteID, VariableID, MethodID, SourceID, QualityControlLevelID, " + "BeginDateTime, EndDateTime, BeginDateTimeUTC, EndDateTimeUTC, ValueCount, ServiceID) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + sqlRowID; int siteID = 0; int variableID = 0; int methodID = 0; int qualityControlLevelID = 0; int sourceID = 0; int isoMetadataID = 0; int seriesID = 0; //check the ServiceID (must be already set) if (dataService.Id <= 0) { throw new ArgumentException("The DataServiceID must be set."); } //Step 1 Begin Transaction using (DbConnection conn = _db.CreateConnection()) { conn.Open(); using (DbTransaction tran = conn.BeginTransaction()) { //**************************************************************** //*** Step 2 Site //**************************************************************** object siteIDResult = null; using (DbCommand cmd01 = conn.CreateCommand()) { cmd01.CommandText = sqlSite; cmd01.Parameters.Add(_db.CreateParameter(DbType.String, series.Site.Code)); siteIDResult = cmd01.ExecuteScalar(); if (siteIDResult != null) { siteID = Convert.ToInt32(siteIDResult); } } if (siteID == 0) //New Site needs to be created { //Insert the site to the database using (DbCommand cmd04 = conn.CreateCommand()) { Site site = series.Site; cmd04.CommandText = sqlSaveSite; cmd04.Parameters.Add(_db.CreateParameter(DbType.String, site.Code)); cmd04.Parameters.Add(_db.CreateParameter(DbType.String, site.Name)); cmd04.Parameters.Add(_db.CreateParameter(DbType.Double, site.Latitude)); cmd04.Parameters.Add(_db.CreateParameter(DbType.Double, site.Longitude)); cmd04.Parameters.Add(_db.CreateParameter(DbType.Int32, site.SpatialReference.SRSID)); cmd04.Parameters.Add(_db.CreateParameter(DbType.String, site.SpatialReference.SRSName)); cmd04.Parameters.Add(_db.CreateParameter(DbType.Double, site.Elevation_m)); cmd04.Parameters.Add(_db.CreateParameter(DbType.String, site.VerticalDatum)); cmd04.Parameters.Add(_db.CreateParameter(DbType.Double, site.LocalX)); cmd04.Parameters.Add(_db.CreateParameter(DbType.Double, site.LocalY)); if (site.LocalProjection != null) { cmd04.Parameters.Add(_db.CreateParameter(DbType.Int32, site.LocalProjection.SRSID)); cmd04.Parameters.Add(_db.CreateParameter(DbType.String, site.LocalProjection.SRSName)); } else { cmd04.Parameters.Add(_db.CreateParameter(DbType.Int32, 0)); cmd04.Parameters.Add(_db.CreateParameter(DbType.String, "unknown")); } cmd04.Parameters.Add(_db.CreateParameter(DbType.Double, site.PosAccuracy_m)); cmd04.Parameters.Add(_db.CreateParameter(DbType.String, site.State)); cmd04.Parameters.Add(_db.CreateParameter(DbType.String, site.County)); cmd04.Parameters.Add(_db.CreateParameter(DbType.String, site.Comments)); cmd04.Parameters.Add(_db.CreateParameter(DbType.Int32, dataService.Id)); siteIDResult = cmd04.ExecuteScalar(); siteID = Convert.ToInt32(siteIDResult); } } //**************************************************************** //*** Step 3 Variable //**************************************************************** Variable variable = series.Variable; object variableIDResult = null; using (DbCommand cmd05 = conn.CreateCommand()) { cmd05.CommandText = sqlVariable; cmd05.Parameters.Add(_db.CreateParameter(DbType.String, variable.Code)); cmd05.Parameters[0].Value = variable.Code; variableIDResult = cmd05.ExecuteScalar(); if (variableIDResult != null) { variableID = Convert.ToInt32(variableIDResult); } } if (variableID == 0) //New variable needs to be created { //Insert the variable to the database using (DbCommand cmd09 = conn.CreateCommand()) { cmd09.CommandText = sqlSaveVariable; cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.Code)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.Name)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.Speciation)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.SampleMedium)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.ValueType)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.DataType)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.GeneralCategory)); cmd09.Parameters.Add(_db.CreateParameter(DbType.Double, variable.NoDataValue)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.VariableUnit.Name)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.VariableUnit.UnitsType)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.VariableUnit.Abbreviation)); cmd09.Parameters.Add(_db.CreateParameter(DbType.Boolean, variable.IsRegular)); cmd09.Parameters.Add(_db.CreateParameter(DbType.Double, variable.TimeSupport)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.TimeUnit.Name)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.TimeUnit.UnitsType)); cmd09.Parameters.Add(_db.CreateParameter(DbType.String, variable.TimeUnit.Abbreviation)); cmd09.Parameters.Add(_db.CreateParameter(DbType.Int32, dataService.Id)); variableIDResult = cmd09.ExecuteScalar(); variableID = Convert.ToInt32(variableIDResult); } } //**************************************************************** //*** Step 4 Method //**************************************************************** Method method = series.Method; object methodIDResult = null; using (DbCommand cmd10 = conn.CreateCommand()) { cmd10.CommandText = sqlMethod; cmd10.Parameters.Add(_db.CreateParameter(DbType.String, method.Description)); methodIDResult = cmd10.ExecuteScalar(); if (methodIDResult != null) { methodID = Convert.ToInt32(methodIDResult); } } if (methodID == 0) { using (DbCommand cmd11 = conn.CreateCommand()) { cmd11.CommandText = sqlSaveMethod; cmd11.Parameters.Add(_db.CreateParameter(DbType.Int32, method.Code)); cmd11.Parameters.Add(_db.CreateParameter(DbType.String, method.Description)); cmd11.Parameters.Add(_db.CreateParameter(DbType.String, method.Link)); cmd11.Parameters.Add(_db.CreateParameter(DbType.Int32, dataService.Id)); methodIDResult = cmd11.ExecuteScalar(); methodID = Convert.ToInt32(methodIDResult); } } //**************************************************************** //*** Step 5 Quality Control Level //**************************************************************** QualityControlLevel qc = series.QualityControlLevel; object qualityControlLevelIDResult = null; using (DbCommand cmd12 = conn.CreateCommand()) { cmd12.CommandText = sqlQuality; cmd12.Parameters.Add(_db.CreateParameter(DbType.String, qc.Definition)); qualityControlLevelIDResult = cmd12.ExecuteScalar(); if (qualityControlLevelIDResult != null) { qualityControlLevelID = Convert.ToInt32(qualityControlLevelIDResult); } } if (qualityControlLevelID == 0) { //to set the code int qcCode = 0; int.TryParse(qc.Code, out qcCode); using (DbCommand cmd13 = conn.CreateCommand()) { cmd13.CommandText = sqlSaveQualityControl; cmd13.Parameters.Add(_db.CreateParameter(DbType.Int32, qcCode)); cmd13.Parameters.Add(_db.CreateParameter(DbType.String, qc.Code)); cmd13.Parameters.Add(_db.CreateParameter(DbType.String, qc.Definition)); cmd13.Parameters.Add(_db.CreateParameter(DbType.String, qc.Explanation)); cmd13.Parameters.Add(_db.CreateParameter(DbType.Int32, dataService.Id)); qualityControlLevelIDResult = cmd13.ExecuteScalar(); qualityControlLevelID = Convert.ToInt32(qualityControlLevelIDResult); } } //**************************************************************** //*** Step 6 Source //**************************************************************** Source source = series.Source; object sourceIDResult = null; using (DbCommand cmd14 = conn.CreateCommand()) { cmd14.CommandText = sqlSource; cmd14.Parameters.Add(_db.CreateParameter(DbType.String, source.Organization)); sourceIDResult = cmd14.ExecuteScalar(); if (sourceIDResult != null) { sourceID = Convert.ToInt32(sourceIDResult); } } if (sourceID == 0) { using (DbCommand cmd17 = conn.CreateCommand()) { cmd17.CommandText = sqlSaveSource; cmd17.Parameters.Add(_db.CreateParameter(DbType.Int32, source.OriginId)); cmd17.Parameters.Add(_db.CreateParameter(DbType.String, source.Organization)); cmd17.Parameters.Add(_db.CreateParameter(DbType.String, source.Description)); cmd17.Parameters.Add(_db.CreateParameter(DbType.String, source.Link)); cmd17.Parameters.Add(_db.CreateParameter(DbType.String, source.ContactName)); cmd17.Parameters.Add(_db.CreateParameter(DbType.String, source.Phone)); cmd17.Parameters.Add(_db.CreateParameter(DbType.String, source.Email)); cmd17.Parameters.Add(_db.CreateParameter(DbType.String, source.Address)); cmd17.Parameters.Add(_db.CreateParameter(DbType.String, source.City)); cmd17.Parameters.Add(_db.CreateParameter(DbType.String, source.State)); cmd17.Parameters.Add(_db.CreateParameter(DbType.Int32, source.ZipCode)); cmd17.Parameters.Add(_db.CreateParameter(DbType.String, source.Citation)); cmd17.Parameters.Add(_db.CreateParameter(DbType.String, isoMetadataID)); cmd17.Parameters.Add(_db.CreateParameter(DbType.Int32, dataService.Id)); sourceIDResult = cmd17.ExecuteScalar(); sourceID = Convert.ToInt32(sourceIDResult); } } //**************************************************************** //*** Step 7 Series //**************************************************************** using (DbCommand cmd18 = conn.CreateCommand()) { cmd18.CommandText = sqlSaveSeries; cmd18.Parameters.Add(_db.CreateParameter(DbType.Int32, siteID)); cmd18.Parameters.Add(_db.CreateParameter(DbType.Int32, variableID)); cmd18.Parameters.Add(_db.CreateParameter(DbType.Int32, methodID)); cmd18.Parameters.Add(_db.CreateParameter(DbType.Int32, sourceID)); cmd18.Parameters.Add(_db.CreateParameter(DbType.Int32, qualityControlLevelID)); cmd18.Parameters.Add(_db.CreateParameter(DbType.DateTime, series.BeginDateTime)); cmd18.Parameters.Add(_db.CreateParameter(DbType.DateTime, series.EndDateTime)); cmd18.Parameters.Add(_db.CreateParameter(DbType.DateTime, series.BeginDateTimeUTC)); cmd18.Parameters.Add(_db.CreateParameter(DbType.DateTime, series.EndDateTimeUTC)); cmd18.Parameters.Add(_db.CreateParameter(DbType.Int32, series.ValueCount)); cmd18.Parameters.Add(_db.CreateParameter(DbType.Int32, dataService.Id)); object seriesIDResult = cmd18.ExecuteScalar(); seriesID = Convert.ToInt32(seriesIDResult); } //Commit Transaction tran.Commit(); } conn.Close(); } }
/// <summary> /// updates the data row corresponding to the serviceInfo object /// The following parameters are updated: /// IsHarvested /// HarveDateTime /// ServiceName /// ServiceVersion /// ServiceType /// ServiceProtocol /// EastLongitude /// WestLongitude /// EastLatitude /// WestLatitude /// </summary> /// <param name="serviceInfo">the corresponding ServiceInfo</param> public void UpdateDataRow(DataServiceInfo serviceInfo) { if (!columnExists("SiteCount")) { addColumn("SiteCount"); } if (!columnExists("VariableCount")) { addColumn("VariableCount"); } string sql = "UPDATE DataServices SET " + "IsHarvested=?,HarveDateTime=?,ServiceName=?,ServiceVersion=?,ServiceType=?,ServiceProtocol=?," + "EastLongitude=?,WestLongitude=?,NorthLatitude=?,SouthLatitude=?,SiteCount=?, VariableCount=?, ValueCount=? WHERE ServiceID = ?"; using (DbConnection conn = _db.CreateConnection()) { conn.Open(); using (DbTransaction tran = conn.BeginTransaction()) { using (DbCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.Add(_db.CreateParameter(DbType.Boolean, serviceInfo.IsHarvested)); cmd.Parameters.Add(_db.CreateParameter(DbType.DateTime, serviceInfo.HarveDateTime)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, serviceInfo.ServiceName)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, serviceInfo.Version)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, serviceInfo.ServiceType)); cmd.Parameters.Add(_db.CreateParameter(DbType.String, serviceInfo.Protocol)); cmd.Parameters.Add(_db.CreateParameter(DbType.Double, serviceInfo.EastLongitude)); cmd.Parameters.Add(_db.CreateParameter(DbType.Double, serviceInfo.WestLongitude)); cmd.Parameters.Add(_db.CreateParameter(DbType.Double, serviceInfo.NorthLatitude)); cmd.Parameters.Add(_db.CreateParameter(DbType.Double, serviceInfo.SouthLatitude)); cmd.Parameters.Add(_db.CreateParameter(DbType.Int32, serviceInfo.SiteCount)); cmd.Parameters.Add(_db.CreateParameter(DbType.Int32, serviceInfo.VariableCount)); cmd.Parameters.Add(_db.CreateParameter(DbType.Int32, serviceInfo.ValueCount)); cmd.Parameters.Add(_db.CreateParameter(DbType.Int32, serviceInfo.Id)); cmd.ExecuteNonQuery(); } tran.Commit(); } } }
private DataServiceInfo ReadDataServiceInfo(XmlTextReader r) { DataServiceInfo serviceInfo = new DataServiceInfo(); while (r.Read()) { string nodeName = r.Name.ToLower(); if (r.NodeType == XmlNodeType.Element) { if (nodeName == "servurl") { r.Read(); serviceInfo.EndpointURL = r.Value; } else if (nodeName == "title") { r.Read(); serviceInfo.ServiceTitle = r.Value; } else if (nodeName == "servicedescriptionurl") { r.Read(); serviceInfo.DescriptionURL = r.Value; } else if (nodeName == "email") { r.Read(); serviceInfo.ContactEmail = r.Value; } else if (nodeName == "organization") { r.Read(); serviceInfo.Citation = r.Value; } else if (nodeName == "citation") { r.Read(); serviceInfo.Citation = r.Value; } else if (nodeName == "aabstract") { r.Read(); serviceInfo.Abstract = r.Value; } else if (nodeName == "valuecount") { r.Read(); if (!String.IsNullOrEmpty(r.Value)) { serviceInfo.ValueCount = Convert.ToInt32(r.Value); } } else if (nodeName == "sitecount") { r.Read(); if (!String.IsNullOrEmpty(r.Value)) { serviceInfo.SiteCount = Convert.ToInt32(r.Value); } } else if (nodeName == "serviceid") { r.Read(); serviceInfo.HISCentralID = Convert.ToInt32(r.Value); } else if (nodeName == "minx") { } else if (nodeName == "miny") { } else if (nodeName == "maxx") { } else if (nodeName == "maxy") { } } else if (r.NodeType == XmlNodeType.EndElement && nodeName == "serviceinfo") { return(serviceInfo); } } return(null); }