当前位置: 首页>>代码示例>>C#>>正文


C# AdoDataConnection.ExecuteNonQuery方法代码示例

本文整理汇总了C#中AdoDataConnection.ExecuteNonQuery方法的典型用法代码示例。如果您正苦于以下问题:C# AdoDataConnection.ExecuteNonQuery方法的具体用法?C# AdoDataConnection.ExecuteNonQuery怎么用?C# AdoDataConnection.ExecuteNonQuery使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在AdoDataConnection的用法示例。


在下文中一共展示了AdoDataConnection.ExecuteNonQuery方法的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();
			}
		}
开发者ID:rmc00,项目名称:gsf,代码行数:38,代码来源:MeasurementRepository.cs

示例2: GetGroupCount

        /// <summary>
        /// Counts measurements assigned to <see cref="Subscriber"/>.
        /// </summary>
        /// <param name="database"><see cref="AdoDataConnection"/> to connection to database.</param>
        /// <param name="subscriberID">ID of the <see cref="Subscriber"/> for which to count measurements.</param>
        /// <param name="allowed">boolean flag to indicate if measurements are allowed or denied.</param>
        /// <returns>string, indicating success for UI display.</returns>
        public static int GetGroupCount(AdoDataConnection database, Guid subscriberID, bool allowed)
        {
            const string QueryFormat = "SELECT COUNT(*) FROM SubscriberMeasurementGroup WHERE SubscriberID = {0} AND Allowed = {1}";

            bool createdConnection = false;

            try
            {
                createdConnection = CreateConnection(ref database);
                return database.ExecuteNonQuery(DefaultTimeout, QueryFormat, subscriberID, allowed);
            }
            finally
            {
                if (createdConnection && database != null)
                    database.Dispose();
            }
        }
开发者ID:rmc00,项目名称:gsf,代码行数:24,代码来源:Subscriber.cs

示例3: 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++)
//.........这里部分代码省略.........
开发者ID:GridProtectionAlliance,项目名称:PQDashboard,代码行数:101,代码来源:mapService.cs

示例4: CleanUpAnimation

 private static void CleanUpAnimation()
 {
     using (AdoDataConnection connection = new AdoDataConnection(connectionstring, typeof(SqlConnection), typeof(SqlDataAdapter)))
     {
         DateTime yesterday = DateTime.UtcNow.AddDays(-1);
         connection.ExecuteNonQuery("DELETE FROM ContourAnimationFrame WHERE ContourAnimationID IN (SELECT ID FROM ContourAnimation WHERE AccessedOn < {0})", yesterday);
         connection.ExecuteNonQuery("DELETE FROM ContourAnimation WHERE AccessedOn < {0}", yesterday);
     }
 }
开发者ID:GridProtectionAlliance,项目名称:PQDashboard,代码行数:9,代码来源:mapService.cs

示例5: ValidateAlarmStatistics

        private static void ValidateAlarmStatistics(AdoDataConnection connection, Guid nodeID, string source)
        {
            const string MissingStatisticsFormat = "SELECT DISTINCT Severity FROM Alarm WHERE Severity <> 0 AND Severity NOT IN (SELECT Arguments FROM Statistic WHERE Source = {0} AND MethodName = {1})";
            const string MaxSignalIndexFormat = "SELECT COALESCE(MAX(SignalIndex), 0) FROM Statistic WHERE Source = {0}";
            const string InsertAlarmStatisticFormat = "INSERT INTO Statistic(Source, SignalIndex, Name, Description, AssemblyName, TypeName, MethodName, Arguments, Enabled, DataType, DisplayFormat, IsConnectedState, LoadOrder) VALUES({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12})";

            string methodName;

            DataTable missingStatistics;

            int signalIndex;
            int severity;
            string name;
            string description;

            // Add statistics for the alarms defined in the Alarm table.
            methodName = string.Format("Get{0}Statistic_MeasurementCountForSeverity", source);
            missingStatistics = connection.RetrieveData(MissingStatisticsFormat, source, methodName);

            if (missingStatistics.Rows.Count > 0)
            {
                signalIndex = connection.ExecuteScalar<int>(MaxSignalIndexFormat, source);

                foreach (DataRow missingStatistic in missingStatistics.Rows)
                {
                    signalIndex++;
                    severity = missingStatistic.ConvertField<int>("Severity");
                    name = string.Format("Alarm Severity {0}", severity);
                    description = string.Format("Number of measurements received while alarm with severity {0} was raised during the last reporting interval.", severity);

                    connection.ExecuteNonQuery(InsertAlarmStatisticFormat, source, signalIndex, name, description, "DataQualityMonitoring.dll", "DataQualityMonitoring.AlarmStatistics", methodName, severity, 1, "System.Int32", "{0:N0}", 0, 1001 - severity);
                }
            }
        }
开发者ID:avs009,项目名称:gsf,代码行数:34,代码来源:TimeSeriesStartupOperations.cs

示例6: ValidateAlarming

        /// <summary>
        /// Data operation to validate and ensure that certain records
        /// that are required for alarming exist in the database.
        /// </summary>
        private static void ValidateAlarming(AdoDataConnection connection, string nodeIDQueryString)
        {
            // SELECT queries
            const string AlarmCountFormat = "SELECT COUNT(*) FROM Alarm";
            const string AlarmAdapterCountFormat = "SELECT COUNT(*) FROM CustomActionAdapter WHERE AdapterName = 'ALARM!SERVICES' AND NodeID = {0}";
            const string AlarmConfigEntityCountFormat = "SELECT COUNT(*) FROM ConfigurationEntity WHERE RuntimeName = 'Alarms'";
            const string AlarmSignalTypeCountFormat = "SELECT COUNT(*) FROM SignalType WHERE Name = 'Alarm'";

            // INSERT queries
            const string AlarmAdapterInsertFormat = "INSERT INTO CustomActionAdapter(NodeID, AdapterName, AssemblyName, TypeName, LoadOrder, Enabled) VALUES({0}, 'ALARM!SERVICES', 'DataQualityMonitoring.dll', 'DataQualityMonitoring.AlarmAdapter', 0, 1)";
            const string AlarmConfigEntityInsertFormat = "INSERT INTO ConfigurationEntity(SourceName, RuntimeName, Description, LoadOrder, Enabled) VALUES('Alarm', 'Alarms', 'Defines alarms that monitor the values of measurements', 17, 1)";
            const string AlarmSignalTypeInsertFormat = "INSERT INTO SignalType(Name, Acronym, Suffix, Abbreviation, Source, EngineeringUnits) VALUES('Alarm', 'ALRM', 'AL', 'AL', 'Any', '')";

            bool alarmTableExists;

            Guid nodeID;
            int alarmAdapterCount;
            int alarmConfigEntityCount;
            int alarmSignalTypeCount;

            try
            {
                // Determine whether the alarm table exists
                // before inserting records related to alarming
                connection.Connection.ExecuteScalar(AlarmCountFormat);
                alarmTableExists = true;
            }
            catch
            {
                alarmTableExists = false;
            }

            if (alarmTableExists)
            {
                nodeID = Guid.Parse(nodeIDQueryString.Trim('\''));

                // Ensure that the alarm adapter is defined.
                alarmAdapterCount = connection.ExecuteScalar<int>(AlarmAdapterCountFormat, nodeID);

                if (alarmAdapterCount == 0)
                    connection.ExecuteNonQuery(AlarmAdapterInsertFormat, nodeID);

                // Ensure that the alarm record is defined in the ConfigurationEntity table.
                alarmConfigEntityCount = connection.ExecuteScalar<int>(AlarmConfigEntityCountFormat);

                if (alarmConfigEntityCount == 0)
                    connection.ExecuteNonQuery(AlarmConfigEntityInsertFormat);

                // Ensure that the alarm record is defined in the SignalType table.
                alarmSignalTypeCount = connection.ExecuteScalar<int>(AlarmSignalTypeCountFormat);

                if (alarmSignalTypeCount == 0)
                    connection.ExecuteNonQuery(AlarmSignalTypeInsertFormat);

                ValidateAlarmStatistics(connection, nodeID, "Point");
            }
        }
开发者ID:avs009,项目名称:gsf,代码行数:61,代码来源:TimeSeriesStartupOperations.cs

示例7: CreateAdapterInstance

 /// <summary>
 /// Creates a data operation to run the validations in this class.
 /// </summary>
 /// <param name="database">Database connection to use for creating the data operation</param>
 private static void CreateAdapterInstance(AdoDataConnection database)
 {
     database.ExecuteNonQuery($"INSERT INTO CustomActionAdapter(NodeID, AdapterName, AssemblyName, TypeName, ConnectionString, Enabled) VALUES ('{ConfigurationFile.Current.Settings["systemSettings"]["NodeID"].ValueAs<Guid>()}', 'PHASOR!POWERCALC', 'PowerCalculations.dll', '{typeof(PowerMultiCalculatorAdapter).FullName}', 'FramesPerSecond=30; LagTime=3; LeadTime=1', 1)");
 }
开发者ID:GridProtectionAlliance,项目名称:gsf,代码行数:8,代码来源:PowerCalculationConfigurationValidation.cs

示例8: DatabaseQueryAction

        public static ActionResult DatabaseQueryAction(Session session)
        {
            string connectionString;
            string dataProviderString;
            string query;

            LogInstallMessage(session, "Begin DatabaseQueryAction");

            // Get properties from the installer session
            connectionString = GetPropertyValue(session, "CONNECTIONSTRING");
            dataProviderString = GetPropertyValue(session, "DATAPROVIDERSTRING");
            query = GetPropertyValue(session, "DBQUERY");

            try
            {
                // Execute the database script
                using (AdoDataConnection connection = new AdoDataConnection(connectionString, dataProviderString))
                {
                    connection.ExecuteNonQuery(query);
                }
            }
            catch (Exception ex)
            {
                // Log the error and return failure code
                string message = $"Failed to execute database query: {ex.Message}.";
                LogInstallMessage(session, InstallMessage.Error, message);
                LogInstallMessage(session, EventLogEntryType.Error, ex);

                LogInstallMessage(session, InstallMessage.Error,
                    $"Database Query: {query}{Environment.NewLine}" +
                    $"Connection string: {connectionString}{Environment.NewLine}" +
                    $"Data provider string: {dataProviderString}");

                return ActionResult.Failure;
            }

            LogInstallMessage(session, "End DatabaseQueryAction");

            return ActionResult.Success;
        }
开发者ID:GridProtectionAlliance,项目名称:gsf,代码行数:40,代码来源:CustomActions.cs

示例9: MeasurementDeviceAssociation

        private static void MeasurementDeviceAssociation(AdoDataConnection connection, string nodeIDQueryString, ulong trackingVersion, string arguments, Action<string> statusMessage, Action<Exception> processException)
        {
            if (string.IsNullOrEmpty(arguments))
            {
                statusMessage("WARNING: No arguments supplied to MeasurementDeviceAssociation data operation - no action will be performed. Expecting \"deviceAcronym\" and \"lookupExpression\" settings at a minimum.");
                return;
            }

            Dictionary<string, string> args = arguments.ParseKeyValuePairs();

            string deviceAcronym;

            if (!args.TryGetValue("DeviceAcronym", out deviceAcronym))
            {
                statusMessage("WARNING: No \"deviceAcronyym\" argument supplied to MeasurementDeviceAssociation data operation - no action will be performed. Expecting \"deviceAcronym\" and \"lookupExpression\" settings at a minimum.");
                return;
            }

            string lookupExpression;

            if (!args.TryGetValue("LookupExpression", out lookupExpression))
            {
                statusMessage("WARNING: No \"lookupExpression\" argument supplied to MeasurementDeviceAssociation data operation - no action will be performed. Expecting \"deviceAcronym\" and \"lookupExpression\" settings at a minimum.");
                return;
            }

            // Make sure device acronym exists
            if (connection.ExecuteScalar<int>($"SELECT COUNT(*) FROM Device WHERE NodeID={nodeIDQueryString} AND Acronym={{0}}", deviceAcronym) == 0)
            {
                // Lookup virtual device protocol
                if (connection.ExecuteScalar<int>("SELECT COUNT(*) FROM Protocol WHERE Acronym='VirtualInput'") == 0)
                {
                    statusMessage("WARNING: No VirutalInput device protocol was found in source database configuration for MeasurementDeviceAssociation data operation - no action will be performed.");
                    return;
                }

                statusMessage($"Creating new \"{deviceAcronym}\" virtual device...");

                int virtualProtocolID = connection.ExecuteScalar<int>("SELECT ID FROM Protocol WHERE Acronym='VirtualInput'");

                // Create new virtual device record
                connection.ExecuteNonQuery($"INSERT INTO Device(NodeID, Acronym, Name, ProtocolID, Enabled) VALUES({nodeIDQueryString}, {{0}}, {{1}}, {{2}}, 1)", deviceAcronym, deviceAcronym, virtualProtocolID);
            }

            statusMessage($"Validating \"{deviceAcronym}\" virtual device measurement associations...");

            // Get device ID
            int deviceID = connection.ExecuteScalar<int>($"SELECT ID FROM Device WHERE NodeID={nodeIDQueryString} AND Acronym={{0}}", deviceAcronym);

            // Get measurements that should be associated with device ID but are not currently
            IEnumerable<DataRow> measurements = connection.RetrieveData($"SELECT PointID FROM Measurement WHERE ({lookupExpression}) AND (DeviceID IS NULL OR DeviceID <> {{0}})", deviceID).AsEnumerable();

            int associatedMeasurements = 0;

            foreach (DataRow row in measurements)
            {
                connection.ExecuteNonQuery("UPDATE Measurement SET DeviceID={0} WHERE PointID={1}", deviceID, row.Field<int>("PointID"));
                associatedMeasurements++;
            }

            if (associatedMeasurements > 0)
                statusMessage($"Associated \"{associatedMeasurements}\" measurements to \"{deviceAcronym}\" virtual device...");
        }
开发者ID:GridProtectionAlliance,项目名称:gsf,代码行数:63,代码来源:CommonPhasorServices.cs

示例10: LogStateChanges

        private void LogStateChanges()
        {
            IList<StateChange> stateChanges;

            StringBuilder insertQuery;
            List<object> insertParameters;
            StringBuilder deleteQuery;
            List<object> deleteParameters;

            int count;

            Thread.Sleep(m_logProcessingDelay);

            stateChanges = m_stateChanges.Dequeue();
            insertQuery = new StringBuilder();
            insertParameters = new List<object>();
            deleteQuery = new StringBuilder();
            deleteParameters = new List<object>();
            count = 0;

            using (AdoDataConnection connection = new AdoDataConnection("systemSettings"))
            {
                foreach (StateChange stateChange in stateChanges)
                {
                    if (insertQuery.Length == 0)
                    {
                        insertQuery.Append("INSERT INTO AlarmLog(SignalID, PreviousState, NewState, Ticks, Timestamp, Value) ");
                        insertQuery.Append("SELECT {0} AS SignalID, {1} AS PreviousState, {2} AS NewState, {3} AS Ticks, {4} AS Timestamp, {5} AS Value");

                        deleteQuery.Append("DELETE FROM AlarmLog WHERE ");
                        deleteQuery.Append("(SignalID = {0} AND Ticks < {1})");
                    }
                    else
                    {
                        insertQuery.Append(" UNION ALL ");
                        insertQuery.AppendFormat("SELECT {{{0}}}, {{{1}}}, {{{2}}}, {{{3}}}, {{{4}}}, {{{5}}}", Enumerable.Range(count * 6, 6).Cast<object>().ToArray());

                        deleteQuery.Append(" OR ");
                        deleteQuery.AppendFormat("(SignalID = {{{0}}} AND Ticks < {{{1}}})", Enumerable.Range(count * 2, 2).Cast<object>().ToArray());
                    }

                    insertParameters.Add(stateChange.SignalID);
                    insertParameters.Add(stateChange.OldStateID);
                    insertParameters.Add(stateChange.NewStateID);
                    insertParameters.Add(stateChange.Timestamp.Ticks);
                    insertParameters.Add(stateChange.Timestamp);
                    insertParameters.Add(stateChange.Value);

                    deleteParameters.Add(stateChange.SignalID);
                    deleteParameters.Add(stateChange.Timestamp.AddHours(-24.0D).Ticks);

                    count++;

                    if (count == m_bulkInsertLimit)
                    {
                        connection.ExecuteNonQuery(insertQuery.ToString(), insertParameters.ToArray());
                        connection.ExecuteNonQuery(deleteQuery.ToString(), deleteParameters.ToArray());

                        insertQuery.Clear();
                        insertParameters.Clear();
                        deleteQuery.Clear();
                        deleteParameters.Clear();

                        count = 0;
                    }
                }

                if (count > 0)
                {
                    connection.ExecuteNonQuery(insertQuery.ToString(), insertParameters.ToArray());
                    connection.ExecuteNonQuery(deleteQuery.ToString(), deleteParameters.ToArray());
                }
            }
        }
开发者ID:rmc00,项目名称:gsf,代码行数:74,代码来源:AlarmAdapter.cs

示例11: LoadSentEmail

        private static int LoadSentEmail(List<string> recipients, string subject, string body)
        {
            DateTime now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, s_timeZone);
            string toLine = string.Join("; ", recipients.Select(recipient => recipient.Trim()));

            using (AdoDataConnection connection = new AdoDataConnection(s_dbAdapterContainer.Connection, typeof(SqlDataAdapter), false))
            {
                connection.ExecuteNonQuery("INSERT INTO SentEmail VALUES({0}, {1}, {2}, {3})", now, toLine, subject, body);
                return connection.ExecuteScalar<int>("SELECT @@IDENTITY");
            }
        }
开发者ID:GridProtectionAlliance,项目名称:openXDA,代码行数:11,代码来源:EventEmailWriter.cs

示例12: AddMeasurements

        /// <summary>
        /// Method to add <see cref="Measurement"/>s to <see cref="MeasurementGroup"/>.
        /// </summary>
        /// <param name="database"><see cref="AdoDataConnection"/> to connection to database.</param>
        /// <param name="measurementGroupID">ID of the <see cref="MeasurementGroup"/> to add <see cref="Measurement"/> to.</param>
        /// <param name="measurementsToBeAdded">List of <see cref="Measurement"/> signal ids to be added.</param>
        /// <returns>string, indicating success for UI display.</returns>
        public static int AddMeasurements(AdoDataConnection database, int measurementGroupID, ICollection<Guid> measurementsToBeAdded)
        {
            string QueryFormat =
                "INSERT INTO MeasurementGroupMeasurement (NodeID, MeasurementGroupID, SignalID) " +
                "SELECT {0}, {1}, {2} " +
                "WHERE (SELECT COUNT(*) FROM MeasurementGroupMeasurement WHERE MeasurementGroupID = {1} AND SignalID = {2}) = 0";

            bool createdConnection = false;
            int rowsAffected = 0;

            try
            {
                createdConnection = CreateConnection(ref database);

                foreach (Guid id in measurementsToBeAdded)
                    rowsAffected += database.ExecuteNonQuery(DefaultTimeout, QueryFormat, CommonFunctions.CurrentNodeID(), measurementGroupID, id);

                return rowsAffected;
            }
            finally
            {
                if (createdConnection && database != null)
                    database.Dispose();
            }
        }
开发者ID:rmc00,项目名称:gsf,代码行数:32,代码来源:MeasurementGroup.cs

示例13: DatabaseQueryAction

        public static ActionResult DatabaseQueryAction(Session session)
        {
            string connectionString;
            string dataProviderString;
            string query;

            session.Log("Begin DatabaseQueryAction");

            // Get properties from the installer session
            connectionString = session.CustomActionData["CONNECTIONSTRING"];
            dataProviderString = session.CustomActionData["DATAPROVIDERSTRING"];
            query = session.CustomActionData["DBQUERY"];

            try
            {
                // Execute the database script
                using (AdoDataConnection connection = new AdoDataConnection(connectionString, dataProviderString))
                {
                    connection.ExecuteNonQuery(query);
                }
            }
            catch (Exception ex)
            {
                // Log the error and return failure code
                LogInstallMessage(session, EventLogEntryType.Error, string.Format("Failed to execute database query: {0}.", ex.Message));
                LogInstallMessage(session, EventLogEntryType.Error, string.Format("Database Query: {0}", query));
                LogInstallMessage(session, EventLogEntryType.Error, string.Format("Connection string: {0}", connectionString));
                LogInstallMessage(session, EventLogEntryType.Error, string.Format("Data provider string: {0}", dataProviderString));
                return ActionResult.Failure;
            }

            session.Log("End DatabaseQueryAction");

            return ActionResult.Success;
        }
开发者ID:rmc00,项目名称:gsf,代码行数:35,代码来源:CustomActions.cs

示例14: AddMeasurementGroups

        /// <summary>
        /// Adds measurement groups to <see cref="Subscriber"/>.
        /// </summary>
        /// <param name="database"><see cref="AdoDataConnection"/> to connection to database.</param>
        /// <param name="subscriberID">ID of the <see cref="Subscriber"/> to which measurements to be added.</param>
        /// <param name="measurementGroupsToBeAdded">List of <see cref="MeasurementGroup"/> IDs to be added.</param>
        /// <param name="allowed">boolean flag to indicate if measurement groups are allowed or denied.</param>
        /// <returns>string, indicating success for UI display.</returns>
        public static int AddMeasurementGroups(AdoDataConnection database, Guid subscriberID, List<int> measurementGroupsToBeAdded, bool allowed)
        {
            const string QueryFormat =
                "INSERT INTO SubscriberMeasurementGroup (NodeID, SubscriberID, MeasurementGroupID, Allowed, UpdatedOn, UpdatedBy, CreatedOn, CreatedBy) " +
                "SELECT {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7} " +
                "WHERE (SELECT COUNT(*) FROM SubscriberMeasurementGroup WHERE SubscriberID = {1} AND MeasurementGroupID = {2}) = 0";

            bool createdConnection = false;
            int rowsAffected = 0;

            try
            {
                createdConnection = CreateConnection(ref database);

                foreach (int id in measurementGroupsToBeAdded)
                {
                    rowsAffected += database.ExecuteNonQuery(DefaultTimeout, QueryFormat, CommonFunctions.CurrentNodeID(), subscriberID, id, allowed,
                        database.UtcNow, CommonFunctions.CurrentUser, database.UtcNow, CommonFunctions.CurrentUser);
                }

                return rowsAffected;
            }
            finally
            {
                if (createdConnection && database != null)
                    database.Dispose();
            }
        }
开发者ID:rmc00,项目名称:gsf,代码行数:36,代码来源:Subscriber.cs

示例15: CreateDataOperation

 /// <summary>
 /// Creates a data operation to run the validations in this class.
 /// </summary>
 /// <param name="database">Database connection to use for creating the data operation</param>
 private static void CreateDataOperation(AdoDataConnection database)
 {
     database.ExecuteNonQuery($"INSERT INTO DataOperation(Description, AssemblyName, TypeName, MethodName, Enabled) VALUES ('Power Calculation Validations', 'PowerCalculations.dll', '{typeof(PowerCalculationConfigurationValidation).FullName}', 'ValidatePowerCalculationConfigurations', 1)");
 }
开发者ID:GridProtectionAlliance,项目名称:gsf,代码行数:8,代码来源:PowerCalculationConfigurationValidation.cs


注:本文中的AdoDataConnection.ExecuteNonQuery方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。