//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace CommunityServer.Spam.Rules
{
	/// <summary>
	/// Summary description for SpamHelper.
	/// </summary>
	public class SqlHelper
	{
		private static string connectionString = ConfigurationSettings.AppSettings["SiteSqlServer"];

		private SqlHelper()
		{
		}

		/// <summary>
		/// Creates an initialized SqlParameter
		/// </summary>
		/// <param name="name">The name of the parameter</param>
		/// <param name="dbType">The type of the parameter</param>
		/// <param name="value">The value of the parameter</param>
		/// <returns>The initialized parameter</returns>
		public static SqlParameter CreateParameter(string name, SqlDbType dbType, object value)
		{
			// Initialize parameter
			SqlParameter parameter = new SqlParameter(name, dbType);
			parameter.Value = value;

			return parameter;
		}


		/// <summary>
		/// Creates an initialized SqlParameter
		/// </summary>
		/// <param name="name">The name of the parameter</param>
		/// <param name="dbType">The type of the parameter</param>
		/// <param name="size">The size of the parameter</param>
		/// <param name="value">The value of the parameter</param>
		/// <returns>The initialized parameter</returns>
		public static SqlParameter CreateParameter(string name, SqlDbType dbType, int size, object value)
		{
			// Initialize parameter
			SqlParameter parameter = new SqlParameter(name, dbType, size);
			parameter.Value = value;

			return parameter;
		}


		/// <summary>
		/// Executes a parameterized stored procedure and returns a value
		/// </summary>
		/// <param name="name">The name of the stored procedure</param>
		/// <param name="parameters">An array of initialized SqlParameter</param>
		public static object ExecuteScalar(string name, SqlParameter[] parameters)
		{
			using (SqlConnection connection = new SqlConnection(connectionString))
			{
				// Initialize command
				SqlCommand command = new SqlCommand(name, connection);
				command.CommandType = CommandType.StoredProcedure;

				// Attach parameters
				foreach (SqlParameter parameter in parameters)
					command.Parameters.Add(parameter);

				// Execute procedure
				connection.Open();
				object value = command.ExecuteScalar();
				connection.Close();

				return value;
			}
		}
	}
}
