PageRenderTime 26ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/Releases/v1.4sp2/Synchrophasor/Current Version/Source/Libraries/openPDC.UI.WPF/ViewModels/RealTimeStatistics.cs

#
C# | 245 lines | 182 code | 30 blank | 33 comment | 24 complexity | cd692b8cdfdb059d07dcb9686effbd00 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, EPL-1.0
  1. //******************************************************************************************************
  2. // RealTimeStatistics.cs - Gbtc
  3. //
  4. // Copyright © 2010, Grid Protection Alliance. All Rights Reserved.
  5. //
  6. // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
  7. // the NOTICE file distributed with this work for additional information regarding copyright ownership.
  8. // The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
  9. // not use this file except in compliance with the License. You may obtain a copy of the License at:
  10. //
  11. // http://www.opensource.org/licenses/eclipse-1.0.php
  12. //
  13. // Unless agreed to in writing, the subject software distributed under the License is distributed on an
  14. // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
  15. // License for the specific language governing permissions and limitations.
  16. //
  17. // Code Modification History:
  18. // ----------------------------------------------------------------------------------------------------
  19. // 09/29/2011 - Mehulbhai P Thakkar
  20. // Generated original version of source code.
  21. //
  22. //******************************************************************************************************
  23. using System;
  24. using System.Collections.Generic;
  25. using System.IO;
  26. using System.Net;
  27. using System.Windows;
  28. using System.Windows.Threading;
  29. using System.Xml.Linq;
  30. using openPDC.UI.DataModels;
  31. using TimeSeriesFramework.UI;
  32. using TVA;
  33. using TVA.Data;
  34. namespace openPDC.UI.ViewModels
  35. {
  36. internal class RealTimeStatistics : PagedViewModelBase<RealTimeStatistic, int>
  37. {
  38. #region [ Members ]
  39. private int m_statisticDataRefreshInterval = 10;
  40. private DispatcherTimer m_refreshTimer;
  41. private string m_lastRefresh;
  42. private string m_url;
  43. #endregion
  44. #region [ Properties ]
  45. /// <summary>
  46. /// Gets flag that determines if <see cref="PagedViewModelBase{T1, T2}.CurrentItem"/> is a new record.
  47. /// </summary>
  48. public override bool IsNewRecord
  49. {
  50. get
  51. {
  52. return false;
  53. }
  54. }
  55. public string LastRefresh
  56. {
  57. get
  58. {
  59. return m_lastRefresh;
  60. }
  61. set
  62. {
  63. m_lastRefresh = value;
  64. OnPropertyChanged("LastRefresh");
  65. }
  66. }
  67. #endregion
  68. #region [ Constructors ]
  69. public RealTimeStatistics(int itemsPerPage, int refreshInterval, bool autoSave = false)
  70. : base(0, autoSave)
  71. {
  72. m_statisticDataRefreshInterval = refreshInterval;
  73. m_refreshTimer = new DispatcherTimer();
  74. m_refreshTimer.Interval = TimeSpan.FromSeconds(m_statisticDataRefreshInterval);
  75. m_refreshTimer.Tick += new EventHandler(m_refreshTimer_Tick);
  76. Load();
  77. }
  78. #endregion
  79. #region [ Methods ]
  80. /// <summary>
  81. /// Gets the primary key value of the <see cref="PagedViewModelBase{T1, T2}.CurrentItem"/>.
  82. /// </summary>
  83. /// <returns>The primary key value of the <see cref="PagedViewModelBase{T1, T2}.CurrentItem"/>.</returns>
  84. public override int GetCurrentItemKey()
  85. {
  86. return 0;
  87. }
  88. /// <summary>
  89. /// Gets the string based named identifier of the <see cref="PagedViewModelBase{T1, T2}.CurrentItem"/>.
  90. /// </summary>
  91. /// <returns>The string based named identifier of the <see cref="PagedViewModelBase{T1, T2}.CurrentItem"/>.</returns>
  92. public override string GetCurrentItemName()
  93. {
  94. return "";
  95. }
  96. public override void Load()
  97. {
  98. try
  99. {
  100. base.Load();
  101. using (AdoDataConnection database = new AdoDataConnection(CommonFunctions.DefaultSettingsCategory))
  102. {
  103. m_url = database.RealTimeStatisticServiceUrl();
  104. if (!m_url.EndsWith("/"))
  105. m_url = m_url + "/";
  106. m_url = m_url + "timeseriesdata/read/current/" + RealTimeStatistic.MinPointID.ToString() + "-" + RealTimeStatistic.MaxPointID.ToString() + "/XML";
  107. }
  108. m_refreshTimer.Start();
  109. GetStatisticData();
  110. }
  111. catch (Exception ex)
  112. {
  113. if (ex.InnerException != null)
  114. {
  115. Popup(ex.Message + Environment.NewLine + "Inner Exception: " + ex.InnerException.Message, "Load " + DataModelName + " Exception:", MessageBoxImage.Error);
  116. CommonFunctions.LogException(null, "Load " + DataModelName, ex.InnerException);
  117. }
  118. else
  119. {
  120. Popup(ex.Message, "Load " + DataModelName + " Exception:", MessageBoxImage.Error);
  121. CommonFunctions.LogException(null, "Load " + DataModelName, ex);
  122. }
  123. }
  124. }
  125. private void m_refreshTimer_Tick(object sender, EventArgs e)
  126. {
  127. GetStatisticData();
  128. }
  129. private void GetStatisticData()
  130. {
  131. try
  132. {
  133. Dictionary<int, StatisticMeasurement> statisticMeasurementData = new Dictionary<int, StatisticMeasurement>();
  134. HttpWebRequest request = WebRequest.Create(m_url) as HttpWebRequest;
  135. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  136. {
  137. if (response.StatusCode == HttpStatusCode.OK)
  138. {
  139. StreamReader reader = new StreamReader(response.GetResponseStream());
  140. XElement timeSeriesDataPoints = XElement.Parse(reader.ReadToEnd());
  141. foreach (XElement element in timeSeriesDataPoints.Element("TimeSeriesDataPoints").Elements("TimeSeriesDataPoint"))
  142. {
  143. StatisticMeasurement measurement;
  144. if (RealTimeStatistic.StatisticMeasurements.TryGetValue(Convert.ToInt32(element.Element("HistorianID").Value), out measurement))
  145. {
  146. DateTime sourceDateTime;
  147. string quality;
  148. if (DateTime.TryParseExact(element.Element("Time").Value, "yyyy-MM-dd HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out sourceDateTime) && DateTime.UtcNow.Subtract(sourceDateTime).TotalSeconds > 30)
  149. quality = "Unknown";
  150. else
  151. quality = element.Element("Quality").Value;
  152. measurement.Quality = quality;
  153. measurement.Value = string.Format(measurement.DisplayFormat, ConvertValueToType(element.Element("Value").Value, measurement.DataType));
  154. measurement.TimeTag = sourceDateTime.ToString("HH:mm:ss.fff");
  155. StreamStatistic streamStatistic;
  156. if (measurement.ConnectedState) //if measurement defines connection state.
  157. {
  158. if ((measurement.Source == "InputStream" && RealTimeStatistic.InputStreamStatistics.TryGetValue(measurement.DeviceID, out streamStatistic)) ||
  159. (measurement.Source == "OutputStream" && RealTimeStatistic.OutputStreamStatistics.TryGetValue(measurement.DeviceID, out streamStatistic)))
  160. {
  161. if (DateTime.TryParseExact(element.Element("Time").Value, "yyyy-MM-dd HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out sourceDateTime) && DateTime.UtcNow.Subtract(sourceDateTime).TotalSeconds > 30)
  162. streamStatistic.StatusColor = "Gray";
  163. else if (Convert.ToBoolean(measurement.Value))
  164. streamStatistic.StatusColor = "Green";
  165. else
  166. streamStatistic.StatusColor = "Red";
  167. }
  168. }
  169. }
  170. }
  171. }
  172. }
  173. }
  174. catch (Exception ex)
  175. {
  176. if (ex.InnerException != null)
  177. CommonFunctions.LogException(null, "Get Statistic Data ", ex.InnerException);
  178. else
  179. CommonFunctions.LogException(null, "Get Statistic Data ", ex);
  180. }
  181. LastRefresh = "Last Refresh: " + DateTime.Now.ToString("HH:mm:ss.fff");
  182. }
  183. private object ConvertValueToType(string xmlValue, string xmlDataType)
  184. {
  185. Type dataType = Type.GetType(xmlDataType);
  186. float value;
  187. if (float.TryParse(xmlValue, out value))
  188. {
  189. switch (xmlDataType)
  190. {
  191. case "System.DateTime":
  192. return new DateTime((long)value);
  193. default:
  194. return Convert.ChangeType(value, dataType);
  195. }
  196. }
  197. return "".ConvertToType<object>(dataType);
  198. }
  199. public void Stop()
  200. {
  201. if (m_refreshTimer != null)
  202. {
  203. try
  204. {
  205. m_refreshTimer.Stop();
  206. }
  207. finally
  208. {
  209. m_refreshTimer = null;
  210. }
  211. }
  212. }
  213. #endregion
  214. }
  215. }