本文整理汇总了C#中AdoDataConnection类的典型用法代码示例。如果您正苦于以下问题:C# AdoDataConnection类的具体用法?C# AdoDataConnection怎么用?C# AdoDataConnection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AdoDataConnection类属于命名空间,在下文中一共展示了AdoDataConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Save
/// <summary>
/// Saves measurement back to the configuration database
/// </summary>
/// <param name="database">Database connection for query. Will be created from config if this value is null.</param>
/// <param name="measurement">Measurement to be inserted or updated</param>
public void Save(AdoDataConnection database, PowerMeasurement measurement)
{
var createdConnection = false;
try
{
createdConnection = CreateConnection(ref database);
if (measurement.SignalID == Guid.Empty)
{
database.ExecuteNonQuery("INSERT INTO Measurement (DeviceID, PointTag, SignalTypeID, " +
"SignalReference, Adder, Multiplier, Description, Enabled, UpdatedBy, UpdatedOn, CreatedBy, CreatedOn) VALUES " +
"({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11})", ToNotNull(measurement.DeviceID), measurement.PointTag,
measurement.SignalTypeID, measurement.SignalReference, measurement.Adder, measurement.Multiplier, ToNotNull(measurement.Description),
database.Bool(measurement.Enabled), Thread.CurrentPrincipal.Identity.Name, database.UtcNow, Thread.CurrentPrincipal.Identity.Name, database.UtcNow);
measurement.SignalID = database.ExecuteScalar<Guid>("SELECT SignalID FROM Measurement WHERE PointTag={0}", measurement.PointTag);
}
else
{
database.ExecuteNonQuery("UPDATE Measurement SET DeviceID = {0}, PointTag = {1}, " +
"SignalTypeID = {2}, SignalReference = {3}, Adder = {4}, Multiplier = {5}, Description = {6}, " +
"Enabled = {7}, UpdatedBy = {8}, UpdatedOn = {9} WHERE SignalId = {10}", ToNotNull(measurement.DeviceID), measurement.PointTag,
measurement.SignalTypeID, measurement.SignalReference, measurement.Adder, measurement.Multiplier, ToNotNull(measurement.Description),
database.Bool(measurement.Enabled), Thread.CurrentPrincipal.Identity.Name, database.UtcNow, measurement.SignalID);
}
}
finally
{
if (createdConnection)
database?.Dispose();
}
}
示例2: LoadConnectionParameters
internal static void LoadConnectionParameters()
{
try
{
using (AdoDataConnection connection = new AdoDataConnection("systemSettings"))
{
TableOperations<IaonOutputAdapter> operations = new TableOperations<IaonOutputAdapter>(connection);
IaonOutputAdapter record = operations.QueryRecords(limit: 1, restriction: new RecordRestriction
{
FilterExpression = "TypeName = 'openHistorian.Adapters.LocalOutputAdapter'"
})
.FirstOrDefault();
if ((object)record == null)
throw new NullReferenceException("Primary openHistorian adapter instance not found.");
Dictionary<string, string> settings = record.ConnectionString.ParseKeyValuePairs();
string setting;
if (!settings.TryGetValue("port", out setting) || !int.TryParse(setting, out s_portNumber))
s_portNumber = Connection.DefaultHistorianPort;
if (!settings.TryGetValue("instanceName", out s_defaultInstanceName) || string.IsNullOrWhiteSpace(s_defaultInstanceName))
s_defaultInstanceName = record.AdapterName ?? "PPA";
}
}
catch
{
s_defaultInstanceName = "PPA";
s_portNumber = Connection.DefaultHistorianPort;
}
}
示例3: Load
/// <summary>
/// Loads <see cref="IaonTree"/> information as an <see cref="ObservableCollection{T}"/> style list.
/// </summary>
/// <param name="database"><see cref="AdoDataConnection"/> to connection to database.</param>
/// <returns>Collection of <see cref="IaonTree"/>.</returns>
public static ObservableCollection<IaonTree> Load(AdoDataConnection database)
{
bool createdConnection = false;
try
{
createdConnection = CreateConnection(ref database);
ObservableCollection<IaonTree> iaonTreeList;
DataTable rootNodesTable = new DataTable();
rootNodesTable.Columns.Add(new DataColumn("AdapterType", Type.GetType("System.String")));
DataRow row;
row = rootNodesTable.NewRow();
row["AdapterType"] = "Input Adapters";
rootNodesTable.Rows.Add(row);
row = rootNodesTable.NewRow();
row["AdapterType"] = "Action Adapters";
rootNodesTable.Rows.Add(row);
row = rootNodesTable.NewRow();
row["AdapterType"] = "Output Adapters";
rootNodesTable.Rows.Add(row);
DataSet resultSet = new DataSet();
resultSet.Tables.Add(rootNodesTable);
DataTable iaonTreeTable = database.Connection.RetrieveData(database.AdapterType, database.ParameterizedQueryString("SELECT * FROM IaonTreeView WHERE NodeID = {0}", "nodeID"), database.CurrentNodeID());
resultSet.EnforceConstraints = false;
resultSet.Tables.Add(iaonTreeTable.Copy());
resultSet.Tables[0].TableName = "RootNodesTable";
resultSet.Tables[1].TableName = "AdapterData";
iaonTreeList = new ObservableCollection<IaonTree>(from item in resultSet.Tables["RootNodesTable"].AsEnumerable()
select new IaonTree
{
m_adapterType = item.Field<string>("AdapterType"),
m_adapterList = new ObservableCollection<Adapter>(from obj in resultSet.Tables["AdapterData"].AsEnumerable()
where obj.Field<string>("AdapterType") == item.Field<string>("AdapterType")
select new Adapter
{
NodeID = database.Guid(obj, "NodeID"),
ID = obj.ConvertField<int>("ID"),
AdapterName = obj.Field<string>("AdapterName"),
AssemblyName = obj.Field<string>("AssemblyName"),
TypeName = obj.Field<string>("TypeName"),
ConnectionString = obj.Field<string>("ConnectionString")
})
});
return iaonTreeList;
}
finally
{
if (createdConnection && database != null)
database.Dispose();
}
}
示例4: WebPageControllerResolver
public WebPageControllerResolver(WebServer webServer, string defaultWebPage, object model, Type modelType, AdoDataConnection database)
{
m_webServer = webServer;
m_defaultWebPage = defaultWebPage;
m_model = model;
m_modelType = modelType;
m_database = database;
}
示例5: ValidateDatabaseDefinitions
/// <summary>
/// Validates that data operation and adapter instance exist within database.
/// </summary>
public static void ValidateDatabaseDefinitions()
{
using (AdoDataConnection database = new AdoDataConnection("systemSettings"))
{
if (!DataOperationExists(database))
CreateDataOperation(database);
if (!AdapterInstanceExists(database))
CreateAdapterInstance(database);
}
}
示例6: RazorView
/// <summary>
/// Creates a new <see cref="RazorView"/>.
/// </summary>
/// <param name="razorEngine"><see cref="IRazorEngine"/> instance to use.</param>
/// <param name="templateName">Name of template file, typically a .cshtml or .vbhtml file.</param>
/// <param name="model">Reference to model to use when rendering template.</param>
/// <param name="modelType">Type of <paramref name="model"/>.</param>
/// <param name="pagedViewModelDataType">Type of data class for views based on paged view model, if any.</param>
/// <param name="pagedViewModelHubType">Type of SignalR hub for views based on paged view model, if any.</param>
/// <param name="database"><see cref="AdoDataConnection"/> to use, if any.</param>
/// <param name="exceptionHandler">Delegate to handle exceptions, if any.</param>
public RazorView(IRazorEngine razorEngine, string templateName, object model = null, Type modelType = null, Type pagedViewModelDataType = null, Type pagedViewModelHubType = null, AdoDataConnection database = null, Action<Exception> exceptionHandler = null)
{
m_razorEngine = razorEngine;
TemplateName = templateName;
Model = model;
ModelType = modelType;
PagedViewModelDataType = pagedViewModelDataType;
PagedViewModelHubType = pagedViewModelHubType;
Database = database;
ExceptionHandler = exceptionHandler;
}
示例7: PerformTimeSeriesStartupOperations
/// <summary>
/// Delegates control to the data operations that are to be performed at startup.
/// </summary>
private static void PerformTimeSeriesStartupOperations(AdoDataConnection database, string nodeIDQueryString, ulong trackingVersion, string arguments, Action<string> statusMessage, Action<Exception> processException)
{
// Set up messaging to the service
s_statusMessage = statusMessage;
s_processException = processException;
// Run data operations
ValidateDefaultNode(database, nodeIDQueryString);
ValidateActiveMeasurements(database, nodeIDQueryString);
ValidateAccountsAndGroups(database, nodeIDQueryString);
ValidateDataPublishers(database, nodeIDQueryString, arguments);
ValidateStatistics(database, nodeIDQueryString);
ValidateAlarming(database, nodeIDQueryString);
}
示例8: CreateConnection
private static bool CreateConnection(ref AdoDataConnection database)
{
if ((object)database != null)
return false;
try
{
database = new AdoDataConnection("systemSettings");
return true;
}
catch
{
return false;
}
}
示例9: DataSubscriptionHubClient
/// <summary>
/// Creates a new <see cref="DataSubscriptionHubClient"/> instance.
/// </summary>
public DataSubscriptionHubClient()
{
m_statisticSubscriptionInfo = new UnsynchronizedSubscriptionInfo(false);
m_dataSubscriptionInfo = new UnsynchronizedSubscriptionInfo(false);
m_measurements = new List<MeasurementValue>();
m_statistics = new List<MeasurementValue>();
m_statusLights = new List<StatusLight>();
m_deviceDetails = new List<DeviceDetail>();
m_measurementDetails = new List<MeasurementDetail>();
m_phasorDetails = new List<PhasorDetail>();
m_schemaVersion = new List<SchemaVersion>();
m_measurementLock = new object();
using(AdoDataConnection conn = new AdoDataConnection("securityProvider"))
{
int index = conn.ExecuteScalar<int>("Select ID FROM ValueListGroup WHERE Name = 'ModbusSubscriptions'");
m_connectionString = conn.ExecuteScalar<string>("Select Text FROM ValueList WHERE GroupID = {0} AND IsDefault = 1", index);
}
}
示例10: App
/// <summary>
/// Creates an instance of <see cref="App"/> class.
/// </summary>
public App()
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
m_errorLogger = new ErrorLogger();
m_defaultErrorText = m_errorLogger.ErrorTextMethod;
m_errorLogger.ErrorTextMethod = ErrorText;
m_errorLogger.ExitOnUnhandledException = false;
m_errorLogger.HandleUnhandledException = true;
m_errorLogger.LogToEmail = false;
m_errorLogger.LogToEventLog = true;
m_errorLogger.LogToFile = true;
m_errorLogger.LogToScreenshot = true;
m_errorLogger.LogToUI = true;
m_errorLogger.Initialize();
m_title = AssemblyInfo.EntryAssembly.Title;
// Setup default cache for measurement keys and associated Guid based signal ID's
AdoDataConnection database = null;
try
{
database = new AdoDataConnection(CommonFunctions.DefaultSettingsCategory);
MeasurementKey.EstablishDefaultCache(database.Connection, database.AdapterType);
}
catch (Exception ex)
{
// First attempt to display a modal dialog will fail to block this
// thread -- modal dialog displayed by the error logger will block now
MessageBox.Show(ex.Message);
// Log and display error, then exit application - manager must connect to database to continue
m_errorLogger.Log(new InvalidOperationException(string.Format("{0} cannot connect to database: {1}", m_title, ex.Message), ex), true);
}
finally
{
if (database != null)
database.Dispose();
}
IsolatedStorageManager.WriteToIsolatedStorage("MirrorMode", false);
}
示例11: ValidateDefaultNode
/// <summary>
/// Data operation to validate and ensure there is a node in the database.
/// </summary>
private static void ValidateDefaultNode(AdoDataConnection database, string nodeIDQueryString)
{
// Queries
const string NodeCountFormat = "SELECT COUNT(*) FROM Node";
const string NodeInsertFormat = "INSERT INTO Node(Name, CompanyID, Description, Settings, MenuType, MenuData, Master, LoadOrder, Enabled) " +
"VALUES('Default', NULL, 'Default node', 'RemoteStatusServerConnectionString={server=localhost:8500};datapublisherport=6165;RealTimeStatisticServiceUrl=http://localhost:6052/historian', " +
"'File', 'Menu.xml', 1, 0, 1)";
const string NodeUpdateFormat = "UPDATE Node SET ID = {0}";
// Determine whether the node exists in the database and create it if it doesn't.
int nodeCount = Convert.ToInt32(database.Connection.ExecuteScalar(NodeCountFormat));
if (nodeCount == 0)
{
database.Connection.ExecuteNonQuery(NodeInsertFormat);
database.Connection.ExecuteNonQuery(string.Format(NodeUpdateFormat, nodeIDQueryString));
}
}
示例12: SubscriberUserControl_Loaded
/// <summary>
/// Handles loaded event for <see cref="SubscriberUserControl"/>.
/// </summary>
/// <param name="sender">Source of the event.</param>
/// <param name="e">Event arguments.</param>
private void SubscriberUserControl_Loaded(object sender, RoutedEventArgs e)
{
// Attach to load/before save event so class can load/add crypto keys from/to local keyIV cache
m_dataContext.PropertyChanged += SubscriberUserControl_PropertyChanged;
m_dataContext.BeforeSave += SubscriberUserControl_BeforeSave;
LoadCurrentKeyIV();
try
{
using (AdoDataConnection database = new AdoDataConnection(CommonFunctions.DefaultSettingsCategory))
{
Dictionary<string, string> settings;
string server;
IPAddress[] hostIPs = null;
IEnumerable<IPAddress> localIPs;
settings = database.DataPublisherConnectionString().ToNonNullString().ParseKeyValuePairs();
if (settings.TryGetValue("server", out server))
hostIPs = Dns.GetHostAddresses(server.Split(':')[0]);
localIPs = Dns.GetHostAddresses("localhost").Concat(Dns.GetHostAddresses(Dns.GetHostName()));
// Check to see if entered host name corresponds to a local IP address
if ((object)hostIPs == null)
MessageBox.Show("Failed to find service host address. If using Gateway security, secure key exchange may not succeed." + Environment.NewLine + "Please make sure to run manager application with administrative privileges on the server where service is hosted.", "Authorize Subcriber", MessageBoxButton.OK, MessageBoxImage.Warning);
else if (!hostIPs.Any(ip => localIPs.Contains(ip)))
MessageBox.Show("If using Gateway security, secure key exchange may not succeed." + Environment.NewLine + "Please make sure to run manager application with administrative privileges on the server where service is hosted.", "Authorize Subscriber", MessageBoxButton.OK, MessageBoxImage.Warning);
}
// If the user is not an Administrator, then the following properties for these controls are readonly and not enable
bool isAdmin = CommonFunctions.CurrentPrincipal.IsInRole("Administrator,Editor");
AcronymField.IsReadOnly = !isAdmin;
NameField.IsReadOnly = !isAdmin;
ValidIpAddressesField.IsReadOnly = !isAdmin;
EnablePGConnectionCheckBox.IsEnabled = isAdmin;
ImportSRQButton.IsEnabled = isAdmin;
ImportCERButton.IsEnabled = isAdmin;
FooterControl.IsEnabled = isAdmin;
}
catch
{
MessageBox.Show("Please make sure to run manager application with administrative privileges on the server where service is hosted.", "Authorize Subscriber", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
示例13: GetIDWFunction
private InverseDistanceWeightingFunction GetIDWFunction(ContourQuery contourQuery, List<TrendingDataLocation> locations = null)
{
CoordinateReferenceSystem crs = new EPSG3857();
List<double> xList = new List<double>();
List<double> yList = new List<double>();
List<double> valueList = new List<double>();
if ((object)locations == null)
locations = GetFrameFromDailySummary(contourQuery);
locations
.Select(location =>
{
GeoCoordinate Coordinate = new GeoCoordinate(location.Latitude, location.Longitude);
double? Value =
(contourQuery.DataType == "Average") ? location.Average :
(contourQuery.DataType == "Minimum") ? location.Minimum :
(contourQuery.DataType == "Maximum") ? location.Maximum :
null;
return new { Coordinate, Value };
})
.Where(obj => (object)obj.Value != null)
.ToList()
.ForEach(obj =>
{
xList.Add(obj.Coordinate.Longitude);
yList.Add(obj.Coordinate.Latitude);
valueList.Add(obj.Value.GetValueOrDefault());
});
if (valueList.Count == 0)
{
xList.Add(0.0D);
yList.Add(0.0D);
using (AdoDataConnection connection = new AdoDataConnection(connectionstring, typeof(SqlConnection), typeof(SqlDataAdapter)))
{
valueList.Add(connection.ExecuteScalar<double>("SELECT NominalValue FROM ContourColorScale WHERE Name = {0}", contourQuery.ColorScaleName));
}
}
return new InverseDistanceWeightingFunction()
.SetXCoordinates(xList.ToArray())
.SetYCoordinates(yList.ToArray())
.SetValues(valueList.ToArray())
.SetDistanceFunction((x1, y1, x2, y2) =>
{
GeoCoordinate coordinate1 = new GeoCoordinate(y1, x1);
GeoCoordinate coordinate2 = new GeoCoordinate(y2, x2);
return crs.Distance(coordinate1, coordinate2);
});
}
示例14: GetFramesFromHistorian
private List<List<TrendingDataLocation>> GetFramesFromHistorian(ContourQuery contourQuery)
{
DataTable idTable;
string historianServer;
string historianInstance;
using (AdoDataConnection connection = new AdoDataConnection(connectionstring, typeof(SqlConnection), typeof(SqlDataAdapter)))
{
string query =
"SELECT " +
" Channel.ID AS ChannelID, " +
" Meter.ID AS MeterID, " +
" Meter.Name AS MeterName, " +
" MeterLocation.Latitude, " +
" MeterLocation.Longitude, " +
" Channel.PerUnitValue " +
"FROM " +
" Meter JOIN " +
" MeterLocation ON Meter.MeterLocationID = MeterLocation.ID LEFT OUTER JOIN " +
" Channel ON " +
" Channel.MeterID = Meter.ID AND " +
" Channel.ID IN (SELECT ChannelID FROM ContourChannel WHERE ContourColorScaleName = {1}) " +
"WHERE Meter.ID IN (SELECT * FROM authMeters({0}))";
idTable = connection.RetrieveData(query, contourQuery.UserName, contourQuery.ColorScaleName);
historianServer = connection.ExecuteScalar<string>("SELECT Value FROM Setting WHERE Name = 'Historian.Server'") ?? "127.0.0.1";
historianInstance = connection.ExecuteScalar<string>("SELECT Value FROM Setting WHERE Name = 'Historian.Instance'") ?? "XDA";
}
if (!string.IsNullOrEmpty(contourQuery.Meters))
{
const int byteSize = 8;
// Meter selections are stored as a base-64 string without padding, using '-' instead of '+' and '_' instead of '/'
string padding = "A==".Remove(3 - (contourQuery.Meters.Length + 3) % 4);
string base64 = contourQuery.Meters.Replace('-', '+').Replace('_', '/') + padding;
byte[] meterSelections = Convert.FromBase64String(base64);
// The resulting byte array is a simple set of bitflags ordered by meter ID and packed into the most significant bits.
// In order to properly interpret the bytes, we must first group and order the data by meter ID to determine the location
// of each meter's bitflag. Then we can filter out the unwanted data from the original table of IDs
idTable.Select()
.Select((Row, Index) => new { Row, Index })
.GroupBy(obj => obj.Row.ConvertField<int>("MeterID"))
.OrderBy(grouping => grouping.Key)
.Where((grouping, index) => (meterSelections[index / byteSize] & (0x80 >> (index % byteSize))) == 0)
.SelectMany(grouping => grouping)
.OrderByDescending(obj => obj.Index)
.ToList()
.ForEach(obj => idTable.Rows.RemoveAt(obj.Index));
}
List<DataRow> meterRows = idTable
.Select()
.DistinctBy(row => row.ConvertField<int>("MeterID"))
.ToList();
DateTime startDate = contourQuery.GetStartDate();
DateTime endDate = contourQuery.GetEndDate();
int stepSize = contourQuery.StepSize;
// The frames to be included are those whose timestamps fall
// within the range which is specified by startDate and
// endDate. We start by aligning startDate and endDate with
// the nearest frame timestamps which fall within that range
int startTimeOffset = (int)Math.Ceiling((startDate - startDate.Date).TotalMinutes / stepSize);
startDate = startDate.Date.AddMinutes(startTimeOffset * stepSize);
int endTimeOffset = (int)Math.Floor((endDate - endDate.Date).TotalMinutes / stepSize);
endDate = endDate.Date.AddMinutes(endTimeOffset * stepSize);
// Since each frame includes data from all timestamps between
// the previous frame's timestamp and its own timestamp, we
// must include one additional frame of data before startDate
startDate = startDate.AddMinutes(-stepSize);
int frameCount = (int)((endDate - startDate).TotalMinutes / stepSize);
List<Dictionary<int, TrendingDataLocation>> frames = Enumerable.Repeat(meterRows, frameCount)
.Select(rows => rows.Select(row => new TrendingDataLocation()
{
id = row.ConvertField<int>("MeterID"),
name = row.ConvertField<string>("MeterName"),
Latitude = row.ConvertField<double>("Latitude"),
Longitude = row.ConvertField<double>("Longitude")
}))
.Select(locations => locations.ToDictionary(location => location.id))
.ToList();
Dictionary<int, double?> nominalLookup = idTable
.Select("ChannelID IS NOT NULL")
.ToDictionary(row => row.ConvertField<int>("ChannelID"), row => row.ConvertField<double?>("PerUnitValue"));
Dictionary<int, List<TrendingDataLocation>> lookup = idTable
.Select("ChannelID IS NOT NULL")
.Select(row =>
{
int meterID = row.ConvertField<int>("MeterID");
return new
//.........这里部分代码省略.........
示例15: getContourAnimations
public ContourAnimationInfo getContourAnimations(ContourQuery contourQuery)
{
List<List<TrendingDataLocation>> frames = GetFramesFromHistorian(contourQuery);
PiecewiseLinearFunction colorScale = GetColorScale(contourQuery);
Func<double, double> colorFunc = colorScale;
// The actual startDate is the timestamp of the
// first frame after contourQuery.GetStartDate()
DateTime startDate = contourQuery.GetStartDate();
int stepSize = contourQuery.StepSize;
int startTimeOffset = (int)Math.Ceiling((startDate - startDate.Date).TotalMinutes / stepSize);
startDate = startDate.Date.AddMinutes(startTimeOffset * stepSize);
double minLat = frames.Min(frame => frame.Min(location => location.Latitude)) - GetLatFromMiles(50.0D);
double maxLat = frames.Min(frame => frame.Max(location => location.Latitude)) + GetLatFromMiles(50.0D);
double minLng = frames.Min(frame => frame.Min(location => location.Longitude)) - GetLngFromMiles(50.0D, 0.0D);
double maxLng = frames.Min(frame => frame.Max(location => location.Longitude)) + GetLngFromMiles(50.0D, 0.0D);
GeoCoordinate topLeft = new GeoCoordinate(maxLat, minLng);
GeoCoordinate bottomRight = new GeoCoordinate(minLat, maxLng);
GSF.Drawing.Point topLeftPoint = s_crs.Translate(topLeft, contourQuery.Resolution);
GSF.Drawing.Point bottomRightPoint = s_crs.Translate(bottomRight, contourQuery.Resolution);
topLeftPoint = new GSF.Drawing.Point(Math.Floor(topLeftPoint.X), Math.Floor(topLeftPoint.Y));
bottomRightPoint = new GSF.Drawing.Point(Math.Ceiling(bottomRightPoint.X), Math.Ceiling(bottomRightPoint.Y));
topLeft = s_crs.Translate(topLeftPoint, contourQuery.Resolution);
bottomRight = s_crs.Translate(bottomRightPoint, contourQuery.Resolution);
int width = (int)(bottomRightPoint.X - topLeftPoint.X + 1);
int height = (int)(bottomRightPoint.Y - topLeftPoint.Y + 1);
int animationID;
string timeZoneID = null;
using (AdoDataConnection connection = new AdoDataConnection(connectionstring, typeof(SqlConnection), typeof(SqlDataAdapter)))
{
connection.ExecuteNonQuery("INSERT INTO ContourAnimation(ColorScaleName, StartTime, EndTime, StepSize) VALUES({0}, {1}, {2}, {3})", contourQuery.ColorScaleName, contourQuery.GetStartDate(), contourQuery.GetEndDate(), contourQuery.StepSize);
animationID = connection.ExecuteScalar<int>("SELECT @@IDENTITY");
if (contourQuery.IncludeWeather)
timeZoneID = connection.ExecuteScalar<string>("SELECT Value FROM Setting WHERE Name = 'XDATimeZone'");
}
GSF.Threading.CancellationToken cancellationToken = new GSF.Threading.CancellationToken();
s_cancellationTokens[animationID] = cancellationToken;
ProgressCounter progressCounter = new ProgressCounter(frames.Count);
s_progressCounters[animationID] = progressCounter;
Action<int> createFrame = i =>
{
List<TrendingDataLocation> frame = frames[i];
IDWFunc idwFunction = GetIDWFunction(contourQuery, frame);
uint[] pixelData;
if (contourQuery.IncludeWeather)
{
TimeZoneInfo tzInfo = !string.IsNullOrEmpty(timeZoneID)
? TimeZoneInfo.FindSystemTimeZoneById(timeZoneID)
: TimeZoneInfo.Local;
// Weather data is only available in 5-minute increments
DateTime frameTime = TimeZoneInfo.ConvertTimeToUtc(startDate.AddMinutes(stepSize * i), tzInfo);
double minutes = (frameTime - frameTime.Date).TotalMinutes;
int weatherMinutes = (int)Math.Ceiling(minutes / 5) * 5;
NameValueCollection queryString = HttpUtility.ParseQueryString(string.Empty);
queryString["service"] = "WMS";
queryString["request"] = "GetMap";
queryString["layers"] = "nexrad-n0r-wmst";
queryString["format"] = "image/png";
queryString["transparent"] = "true";
queryString["version"] = "1.1.1";
queryString["time"] = frameTime.Date.AddMinutes(weatherMinutes).ToString("o");
queryString["height"] = height.ToString();
queryString["width"] = width.ToString();
queryString["srs"] = "EPSG:3857";
GSF.Drawing.Point topLeftProjected = s_crs.Projection.Project(topLeft);
GSF.Drawing.Point bottomRightProjected = s_crs.Projection.Project(bottomRight);
queryString["bbox"] = string.Join(",", topLeftProjected.X, bottomRightProjected.Y, bottomRightProjected.X, topLeftProjected.Y);
string weatherURL = "http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r-t.cgi?" + queryString.ToString();
using (WebClient client = new WebClient())
using (MemoryStream stream = new MemoryStream(client.DownloadData(weatherURL)))
using (Bitmap bitmap = new Bitmap(stream))
{
pixelData = bitmap.ToPixelData();
}
}
else
{
pixelData = new uint[width * height];
}
if (cancellationToken.IsCancelled)
return;
for (int x = 0; x < width; x++)
//.........这里部分代码省略.........