1253 lines · 50.1 KB · C#
RawDownload
//******************************************************************************************************//  CommonFunctions.cs - Gbtc////  Copyright © 2012, Grid Protection Alliance.  All Rights Reserved.////  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See//  the NOTICE file distributed with this work for additional information regarding copyright ownership.//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may//  not use this file except in compliance with the License. You may obtain a copy of the License at:////      http://www.opensource.org/licenses/MIT////  Unless agreed to in writing, the subject software distributed under the License is distributed on an//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the//  License for the specific language governing permissions and limitations.////  Code Modification History://  ----------------------------------------------------------------------------------------------------//  03/31/2011 - Mehulbhai P Thakkar//       Generated original version of source code.//  12/20/2012 - Starlynn Danyelle Gilliam//       Modified Header.////****************************************************************************************************** using System;using System.Collections.Generic;using System.Data;using System.Diagnostics;using System.IO.Ports;using System.Linq;using System.Net;using System.Net.Sockets;using System.Security.Principal;using System.Threading;using System.Windows;using System.Windows.Controls;using System.Windows.Controls.Primitives;using System.Windows.Documents;using System.Windows.Media;using System.Windows.Threading;using GSF.Communication;using GSF.Data;using GSF.Identity;using GSF.IO;using GSF.Security;using GSF.TimeSeries.UI.DataModels; namespace GSF.TimeSeries.UI{    /// <summary>    /// Represents a static class containing common methods.    /// </summary>    public static class CommonFunctions    {        #region [ Members ]         /// <summary>        /// Defines the default settings category for TimeSeriesFramework data connections.        /// </summary>        public const string DefaultSettingsCategory = "systemSettings";         /// <summary>        /// Defines the maximum number of pages to be stored in page history.        /// </summary>        public const int MaxPageHistory = 10;         #endregion         #region [ Static ]         // Static Fields        private static SecurityPrincipal s_currentPrincipal;        private static Guid s_currentNodeID;        private static string s_serviceConnectionString;        private static string s_dataPublisherConnectionString;        private static string s_realTimeStatisticServiceUrl;        private static string s_timeSeriesDataServiceUrl;        private static WindowsServiceClient s_windowsServiceClient;        private static bool s_retryServiceConnection;        private static LinkedList<Tuple<string, Type, object[]>> s_pageHistory;        private static LinkedListNode<Tuple<string, Type, object[]>> s_currentPage;         // Static Properties         /// <summary>        /// Defines the current principal for the thread owning the common functions.        /// </summary>        public static SecurityPrincipal CurrentPrincipal        {            get            {                return s_currentPrincipal;            }            set            {                s_currentPrincipal = value;            }        }         /// <summary>        /// Defines the current user name as defined in the CurrentPrincipal.Identity.        /// </summary>        public static string CurrentUser => CurrentPrincipal.Identity.Name;         /// <summary>        /// Gets the flag that indicates whether we can go forward to the next user control in history.        /// </summary>        public static bool CanGoForward        {            get            {                SecurityPrincipal currentPrincipal = CurrentPrincipal;                ISecurityProvider securityProvider = currentPrincipal.Identity.Provider;                 return                    ((object)s_currentPage != null) &&                    ((object)s_currentPage.Next != null) &&                    currentPrincipal.Identity.IsAuthenticated &&                    securityProvider.UserData.Roles.Any();            }        }         /// <summary>        /// Gets the flag that indicates whether we can go back to the previous user control in history.        /// </summary>        public static bool CanGoBack        {            get            {                SecurityPrincipal currentPrincipal = CurrentPrincipal;                ISecurityProvider securityProvider = currentPrincipal.Identity.Provider;                 return                    ((object)s_currentPage != null) &&                    ((object)s_currentPage.Previous != null) &&                    currentPrincipal.Identity.IsAuthenticated &&                    securityProvider.UserData.Roles.Any();            }        }         // Events         /// <summary>        /// Used to notify main window that connection to service has changed.        /// </summary>        public static event EventHandler ServiceConnectionRefreshed = delegate        {        };         /// <summary>        /// Event raised when the <see cref="CurrentPrincipal"/> property changes as        /// a result of its security provider expiring from the security provider cache.        /// </summary>        public static event EventHandler CurrentPrincipalRefreshed;         /// <summary>        /// Triggered when the flag that indicates whether we can move forward in page history changes.        /// </summary>        public static event EventHandler CanGoForwardChanged;         /// <summary>        /// Triggered when the flag that indicates whether we can move backward in page history changes.        /// </summary>        public static event EventHandler CanGoBackChanged;         // Static Methods         #region [ AdoDataConnection Extension Methods ]         /// <summary>        /// Sets the current user context for the database.        /// </summary>        /// <remarks>        /// Purpose of this method is to supply current user information from the UI to DELETE trigger for change logging.        /// This method must be called before any delete operation on the database in order to log who deleted this record.        /// For SQL server it sets user name into CONTEXT_INFO().        /// For MySQL server it sets user name into session variable @context.        /// For Oracle server it sets user name into context package.        /// MS Access is not supported for change logging.        /// For any other database in the future, such as Oracle, this logic must be extended to support change log in the database.        /// </remarks>        /// <param name="database"><see cref="AdoDataConnection"/> used to set user context before any delete operation.</param>        public static void SetCurrentUserContext(AdoDataConnection database)        {            bool createdConnection = false;             try            {                if (!string.IsNullOrEmpty(CurrentUser))                {                    if ((object)database == null)                    {                        database = new AdoDataConnection(DefaultSettingsCategory);                        createdConnection = true;                    }                     IDbCommand command;                    string connectionType = database.Connection.GetType().Name.ToLower();                     // Set Current User for the database session for this connection.                     switch (connectionType)                    {                        case "sqlconnection":                            const string contextSql = "DECLARE @context VARBINARY(128)\n SELECT @context = CONVERT(VARBINARY(128), CONVERT(VARCHAR(128), @userName))\n SET CONTEXT_INFO @context";                            command = database.Connection.CreateCommand();                            command.CommandText = contextSql;                            command.AddParameterWithValue("@userName", CurrentUser);                            command.ExecuteNonQuery();                            break;                        case "mysqlconnection":                            command = database.Connection.CreateCommand();                            command.CommandText = "SET @context = '" + CurrentUser + "';";                            command.ExecuteNonQuery();                            break;                        case "oracleconnection":                            command = database.Connection.CreateCommand();                            command.CommandText = "BEGIN context.set_current_user('" + CurrentUser + "'); END;";                            command.ExecuteNonQuery();                            break;                    }                }            }            finally            {                if (createdConnection)                    database.Dispose();            }        }         ///// <summary>        ///// Retrieves connection string to connect to backend windows service.        ///// </summary>        ///// <param name="database"><see cref="AdoDataConnection"/> to database.</param>        ///// <returns>IP address and port on which backend windows service is running.</returns>        //public static string RemoteStatusServerConnectionString(this AdoDataConnection database)        //{        //    if (string.IsNullOrEmpty(s_remoteStatusServerConnectionString))        //        database.GetNodeSettings();         //    return s_remoteStatusServerConnectionString;        //}         /// <summary>        /// Retrieves web service url to query real time statistics values.        /// </summary>        /// <param name="database"><see cref="AdoDataConnection"/> to database.</param>        /// <returns>string, url to web service.</returns>        public static string RealTimeStatisticServiceUrl(this AdoDataConnection database)        {            if (string.IsNullOrEmpty(s_realTimeStatisticServiceUrl))                database.GetNodeSettings();             return s_realTimeStatisticServiceUrl;        }         ///// <summary>        ///// Retrieves a port number on which back end service is publishing data.        ///// </summary>        ///// <param name="database"><see cref="AdoDataConnection"/> to database.</param>        ///// <returns>port number on which data is being published.</returns>        //public static string DataPublisherPort(this AdoDataConnection database)        //{        //    if (string.IsNullOrEmpty(s_dataPublisherPort))        //        database.GetNodeSettings();         //    return s_dataPublisherPort;        //}         /// <summary>        /// Retrieves web service url to query real time data.        /// </summary>        /// <param name="database"><see cref="AdoDataConnection"/> to database.</param>        /// <returns>string, url to web service.</returns>        public static string TimeSeriesDataServiceUrl(this AdoDataConnection database)        {            if (string.IsNullOrEmpty(s_timeSeriesDataServiceUrl))                database.GetNodeSettings();             return s_timeSeriesDataServiceUrl;        }         /// <summary>        /// Retrieves connection string information to connect to backed windows service from UI.        /// </summary>        /// <param name="database"><see cref="AdoDataConnection"/> to database.</param>        /// <param name="overwrite">Flag that determines if cached connection string should be overwritten.</param>        /// <returns>Connection string to connect to backend windows service.</returns>        public static string ServiceConnectionString(this AdoDataConnection database, bool overwrite = false)        {            if (string.IsNullOrEmpty(s_serviceConnectionString) || overwrite)                database.GetNodeSettings();             return s_serviceConnectionString;        }         /// <summary>        /// Retrieves connection string to subscribe data from data published hosted by the backend windows service.        /// </summary>        /// <param name="database"><see cref="AdoDataConnection"/> to database.</param>        /// <returns>Connection string to subscribe from data publisher.</returns>        public static string DataPublisherConnectionString(this AdoDataConnection database)        {            if (string.IsNullOrEmpty(s_dataPublisherConnectionString))                database.GetNodeSettings();             return s_dataPublisherConnectionString;        }         /// <summary>        /// Method to parse Settings field value for current node defined in the database and extract various parameters to communicate with backend windows service.        /// </summary>        /// <param name="database"><see cref="AdoDataConnection"/> to database.</param>        private static void GetNodeSettings(this AdoDataConnection database)        {            Node node = Node.GetCurrentNode(database);            if (node != null)            {                string interfaceValue = string.Empty;                Dictionary<string, string> settings = node.Settings.ToLower().ParseKeyValuePairs();                 if (settings.ContainsKey("realtimestatisticserviceurl"))                    s_realTimeStatisticServiceUrl = settings["realtimestatisticserviceurl"];                 if (settings.ContainsKey("timeseriesdataserviceurl"))                    s_timeSeriesDataServiceUrl = settings["timeseriesdataserviceurl"];                 if (settings.ContainsKey("interface"))                    interfaceValue = settings["interface"];                 if (settings.ContainsKey("remotestatusserverconnectionstring"))                {                    Dictionary<string, string> serviceSettings;                     s_serviceConnectionString = settings["remotestatusserverconnectionstring"];                    serviceSettings = s_serviceConnectionString.ParseKeyValuePairs();                     if (serviceSettings.ContainsKey("interface"))                        interfaceValue = serviceSettings["interface"];                     if (serviceSettings.ContainsKey("server"))                    {                        string server = serviceSettings["server"];                         if (serviceSettings.ContainsKey("datapublisherport"))                        {                            s_dataPublisherConnectionString = "server=" + server.Substring(0, server.LastIndexOf(":", StringComparison.OrdinalIgnoreCase) + 1) + serviceSettings["datapublisherport"];                             if (!string.IsNullOrEmpty(interfaceValue))                                s_dataPublisherConnectionString += ";interface=" + interfaceValue;                        }                        else if (settings.ContainsKey("datapublisherport"))                        {                            s_dataPublisherConnectionString = "server=" + server.Substring(0, server.LastIndexOf(":", StringComparison.OrdinalIgnoreCase) + 1) + settings["datapublisherport"];                             if (!string.IsNullOrEmpty(interfaceValue))                                s_dataPublisherConnectionString += ";interface=" + interfaceValue;                        }                    }                }            }        }         /// <summary>        /// Returns current node id <see cref="System.Guid"/> UI is connected to.        /// </summary>        /// <returns>Current Node ID.</returns>        public static Guid CurrentNodeID()        {            return s_currentNodeID;        }         /// <summary>        /// Returns current node id <see cref="System.Guid"/> UI is connected to.        /// </summary>        /// <param name="database">Connected <see cref="AdoDataConnection"/></param>        /// <returns>Proper <see cref="System.Guid"/> implementation for current node id.</returns>        public static object CurrentNodeID(this AdoDataConnection database)        {            return database.Guid(s_currentNodeID);        }         #endregion         /// <summary>        /// Assigns <see cref="CurrentNodeID()"/> based ID of currently active node.        /// </summary>        /// <param name="nodeID">Current node ID <see cref="CurrentNodeID()"/> to assign.</param>        public static void SetAsCurrentNodeID(this Guid nodeID)        {            if (s_currentNodeID != nodeID)            {                s_currentNodeID = nodeID;                 // When node selection changes, reset other static members related to node.                s_serviceConnectionString = string.Empty;                s_dataPublisherConnectionString = string.Empty;                s_realTimeStatisticServiceUrl = string.Empty;                s_timeSeriesDataServiceUrl = string.Empty;                SetRetryServiceConnection(true);                DisconnectWindowsServiceClient();                ConnectWindowsServiceClient();            }        }         /// <summary>        /// Returns <see cref="DBNull"/> if given <paramref name="value"/> is <c>null</c>.        /// </summary>        /// <param name="value">Value to test for null.</param>        /// <returns><see cref="DBNull"/> if <paramref name="value"/> is <c>null</c>; otherwise <paramref name="value"/>.</returns>        public static object ToNotNull(this object value)        {            if ((object)value == null)                return (object)DBNull.Value;             if (value is int && (int)value == 0)                return (object)DBNull.Value;             return value;        }         /// <summary>        /// Returns a collection of down sampling methods.        /// </summary>        /// <returns><see cref="Dictionary{T1,T2}"/> type collection of down sampling methods.</returns>        public static Dictionary<string, string> GetDownsamplingMethodLookupList()        {            Dictionary<string, string> downsamplingLookupList = new Dictionary<string, string>();             downsamplingLookupList.Add("LastReceived", "LastReceived");            downsamplingLookupList.Add("Closest", "Closest");            downsamplingLookupList.Add("Filtered", "Filtered");            downsamplingLookupList.Add("BestQuality", "BestQuality");             return downsamplingLookupList;        }         /// <summary>        /// Returns a collection of system time zones.        /// </summary>        /// <param name="isOptional">Indicates if selection on UI is optional for this collection.</param>        /// <returns><see cref="Dictionary{T1,T2}"/> type collection of system time zones.</returns>        public static Dictionary<string, string> GetTimeZones(bool isOptional)        {            Dictionary<string, string> timeZonesList = new Dictionary<string, string>();             if (isOptional)                timeZonesList.Add("", "Select Time Zone");             foreach (TimeZoneInfo timeZoneInfo in TimeZoneInfo.GetSystemTimeZones())            {                if (!timeZonesList.ContainsKey(timeZoneInfo.Id))                    timeZonesList.Add(timeZoneInfo.Id, timeZoneInfo.DisplayName);            }             return timeZonesList;        }         /// <summary>        /// Retrieves children of an UIElement based on type.        /// </summary>        /// <param name="parent">Parent UIElement.</param>        /// <param name="targetType">Type of child UIElement looking for within parent UIElement.</param>        /// <param name="children">Reference parameter to return child collection.</param>        public static void GetChildren(UIElement parent, Type targetType, ref List<UIElement> children)        {            int count = VisualTreeHelper.GetChildrenCount(parent);            if (count > 0)            {                for (int i = 0; i < count; i++)                {                    UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);                    if (child.GetType() == targetType)                    {                        children.Add(child);                    }                    GetChildren(child, targetType, ref children);                }            }        }         /// <summary>        /// Retrieves first child of an UIElement based on type.        /// </summary>        /// <param name="parent">Parent UIElement</param>        /// <param name="targetType">Type of the child UIElement.</param>        /// <param name="element">Reference parameter to return UIElement.</param>        public static void GetFirstChild(UIElement parent, Type targetType, ref UIElement element)        {            int count = VisualTreeHelper.GetChildrenCount(parent);            if (count > 0)            {                for (int i = 0; i < count; i++)                {                    UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);                    if (child.GetType() == targetType)                    {                        element = child;                        break;

Lines 1–500 of 1253.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t