Example #1
0
        // If it's an Insert we fetch the @@Identity value and stuff it in the proper column
        protected void OnRowUpdated(object sender, VistaDBRowUpdatedEventArgs e)
        {
            try
            {
                if (e.Status == UpdateStatus.Continue && e.StatementType == StatementType.Insert)
                {
                    TransactionMgr txMgr = TransactionMgr.ThreadTransactionMgr();

                    string[] identityCols = this.GetAutoKeyColumns().Split(';');

                    VistaDBCommand cmd = new VistaDBCommand();

                    foreach (string col in identityCols)
                    {
                        cmd.CommandText = "SELECT LastIdentity([" + col + "]) FROM [" + this.QuerySource + "]";

                        // We make sure we enlist in the ongoing transaction, otherwise, we
                        // would most likely deadlock
                        txMgr.Enlist(cmd, this);
                        object o = cmd.ExecuteScalar();                         // Get the Identity Value
                        txMgr.DeEnlist(cmd, this);

                        if (o != null)
                        {
                            e.Row[col] = o;
                        }
                    }

                    e.Row.AcceptChanges();
                }
            }
            catch {}
        }
Example #2
0
        public static object executeScalar(this API_VistaDB vistaDB, string command)
        {
            "[API_VistaDB] Executing Scalar: {0}".info(command);
            VistaDBConnection sqlConnection = null;

            try
            {
                sqlConnection = new VistaDBConnection(vistaDB.ConnectionString);
                sqlConnection.Open();
                var sqlCommand = new VistaDBCommand();
                sqlCommand.Connection  = sqlConnection;
                sqlCommand.CommandText = command;
                sqlCommand.CommandType = CommandType.Text;
                return(sqlCommand.ExecuteScalar());
            }
            catch (Exception ex)
            {
                vistaDB.LastError = ex.Message;
                "[executeNonQuery] {0}".error(ex.Message);
                //ex.log();
            }
            finally
            {
                sqlConnection.Close();
            }
            return(null);
        }
Example #3
0
        public Object ExecuteScalar(String sql)
        {
            VistaDBCommand cmd = new VistaDBCommand(sql, co);
            Object         o   = null;

            try
            {
                o          = cmd.ExecuteScalar();
                _lastError = "";
            }
            catch (Exception e)
            {
                _lastError = e.Message;
            }

            return(o);
        }
Example #4
0
        /// <summary>
        /// 同步文件
        /// </summary>
        /// <param name="currentFile">The current file.</param>
        public void SynFileInfo(FileInfo currentFile)
        {
            //检查项目中是否存在该文件(目录+文件名)
            //比较文件:是否更新?
            string sql = string.Format("select top 1 FileID from [FileSystem] where ProjectID={0} AND FileDir='{1}' AND FileName='{2}'",
                                       1,
                                       currentFile.DirectoryName.Replace(BaseDir, "").Replace("\\", "/"),
                                       currentFile.Name);
            VistaDBCommand cmd     = new VistaDBCommand(sql, conn);
            object         oFileID = cmd.ExecuteScalar();

            if (oFileID == null)
            {
                PackageFile(currentFile);
            }
            else
            {
                #region 比较版本

                #endregion

                #region 插入新文件
                sql = "insert into [FileSystem](FileName,FileDir,FileSize,HashCode,BinData,FileVersion,CreateDate,LastChangeDate) values("
                      + "@FileName,@FileDir,@FileSize,@HashCode,@BinData,2, @CreateDate, @LastChangeDate"
                      + ")";
                VistaDBCommand cmdAdd = new VistaDBCommand(sql, conn);
                cmd.Parameters.AddWithValue("@FileName", currentFile.Name);
                cmd.Parameters.AddWithValue("@FileDir", currentFile.DirectoryName.Replace(BaseDir, "").Replace("\\", "/"));
                cmd.Parameters.AddWithValue("@FileSize", currentFile.Length);

                byte[] fBin = InitialProject.GetFileBytes(currentFile.FullName);
                cmd.Parameters.AddWithValue("@HashCode", InitialProject.GetMD5Hash(fBin));
                cmd.Parameters.AddWithValue("@BinData", fBin);
                cmd.Parameters.AddWithValue("@CreateDate", currentFile.CreationTimeUtc);
                cmd.Parameters.AddWithValue("@LastChangeDate", currentFile.LastWriteTimeUtc);

                cmd.ExecuteNonQuery();
                cmd.Dispose();
                #endregion
            }
        }
Example #5
0
        /// <summary>
        /// Logs an error to the database.
        /// </summary>
        /// <remarks>
        /// Use the stored procedure called by this implementation to set a
        /// policy on how long errors are kept in the log. The default
        /// implementation stores all errors for an indefinite time.
        /// </remarks>

        public override string Log(Error error)
        {
            if (error == null)
            {
                throw new ArgumentNullException("error");
            }

            string errorXml = ErrorXml.EncodeString(error);

            using (VistaDBConnection connection = new VistaDBConnection(this.ConnectionString))
                using (VistaDBCommand command = connection.CreateCommand())
                {
                    connection.Open();
                    command.CommandText = @"INSERT INTO ELMAH_Error
                                            (Application, Host, Type, Source, 
                                            Message, [User], AllXml, StatusCode, TimeUtc)
                                        VALUES
                                            (@Application, @Host, @Type, @Source,
                                            @Message, @User, @AllXml, @StatusCode, @TimeUtc);

                                        SELECT @@IDENTITY";
                    command.CommandType = CommandType.Text;

                    VistaDBParameterCollection parameters = command.Parameters;
                    parameters.Add("@Application", VistaDBType.NVarChar, _maxAppNameLength).Value = ApplicationName;
                    parameters.Add("@Host", VistaDBType.NVarChar, 30).Value     = error.HostName;
                    parameters.Add("@Type", VistaDBType.NVarChar, 100).Value    = error.Type;
                    parameters.Add("@Source", VistaDBType.NVarChar, 60).Value   = error.Source;
                    parameters.Add("@Message", VistaDBType.NVarChar, 500).Value = error.Message;
                    parameters.Add("@User", VistaDBType.NVarChar, 50).Value     = error.User;
                    parameters.Add("@AllXml", VistaDBType.NText).Value          = errorXml;
                    parameters.Add("@StatusCode", VistaDBType.Int).Value        = error.StatusCode;
                    parameters.Add("@TimeUtc", VistaDBType.DateTime).Value      = error.Time.ToUniversalTime();

                    return(Convert.ToString(command.ExecuteScalar(), CultureInfo.InvariantCulture));
                }
        }
        esDataResponse IDataProvider.ExecuteScalar(esDataRequest request)
        {
            esDataResponse response = new esDataResponse();
            VistaDBCommand cmd      = null;

            try
            {
                cmd = new VistaDBCommand();
                if (request.CommandTimeout != null)
                {
                    cmd.CommandTimeout = request.CommandTimeout.Value;
                }
                if (request.Parameters != null)
                {
                    Shared.AddParameters(cmd, request);
                }

                switch (request.QueryType)
                {
                case esQueryType.TableDirect:
                    cmd.CommandType = CommandType.TableDirect;
                    cmd.CommandText = request.QueryText;
                    break;

                case esQueryType.StoredProcedure:
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = Shared.CreateFullName(request);
                    break;

                case esQueryType.Text:
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = request.QueryText;
                    break;

                case esQueryType.DynamicQuery:
                    cmd = QueryBuilder.PrepareCommand(request);
                    break;
                }

                try
                {
                    esTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate);
                    response.Scalar = cmd.ExecuteScalar();
                }
                finally
                {
                    esTransactionScope.DeEnlist(cmd);
                }

                if (request.Parameters != null)
                {
                    Shared.GatherReturnParameters(cmd, request, response);
                }
            }
            catch (Exception ex)
            {
                CleanupCommand(cmd);
                response.Exception = ex;
            }

            return(response);
        }
        protected static void OnRowUpdated(object sender, VistaDBRowUpdatedEventArgs e)
        {
            try
            {
                PropertyCollection props = e.Row.Table.ExtendedProperties;
                if (props.ContainsKey("props"))
                {
                    props = (PropertyCollection)props["props"];
                }

                if (e.Status == UpdateStatus.Continue && (e.StatementType == StatementType.Insert || e.StatementType == StatementType.Update))
                {
                    esDataRequest      request = props["esDataRequest"] as esDataRequest;
                    esEntitySavePacket packet  = (esEntitySavePacket)props["esEntityData"];
                    string             source  = props["Source"] as string;

                    if (e.StatementType == StatementType.Insert)
                    {
                        if (props.Contains("AutoInc"))
                        {
                            string autoInc = props["AutoInc"] as string;

                            VistaDBCommand cmd = new VistaDBCommand();
                            cmd.Connection  = e.Command.Connection;
                            cmd.Transaction = e.Command.Transaction;
                            cmd.CommandText = "SELECT LastIdentity([" + autoInc + "]) FROM [" + source + "]";

                            object o = null;
                            o = cmd.ExecuteScalar();

                            if (o != null)
                            {
                                e.Row[autoInc] = o;
                                e.Command.Parameters["@" + autoInc].Value = o;
                            }
                        }

                        if (props.Contains("EntitySpacesConcurrency"))
                        {
                            string esConcurrencyColumn = props["EntitySpacesConcurrency"] as string;
                            packet.CurrentValues[esConcurrencyColumn] = 1;
                        }
                    }

                    if (props.Contains("Timestamp"))
                    {
                        string column = props["Timestamp"] as string;

                        VistaDBCommand cmd = new VistaDBCommand();
                        cmd.Connection  = e.Command.Connection;
                        cmd.Transaction = e.Command.Transaction;
                        cmd.CommandText = "SELECT LastTimestamp('" + source + "');";

                        object o = null;
                        o = cmd.ExecuteScalar();

                        if (o != null)
                        {
                            e.Command.Parameters["@" + column].Value = o;
                        }
                    }

                    //-------------------------------------------------------------------------------------------------
                    // Fetch any defaults, SQLite doesn't support output parameters so we gotta do this the hard way
                    //-------------------------------------------------------------------------------------------------
                    if (props.Contains("Defaults"))
                    {
                        // Build the Where parameter and parameters
                        VistaDBCommand cmd = new VistaDBCommand();
                        cmd.Connection  = e.Command.Connection;
                        cmd.Transaction = e.Command.Transaction;

                        string select = (string)props["Defaults"];

                        string[] whereParameters = ((string)props["Where"]).Split(',');

                        string comma = String.Empty;
                        string where = String.Empty;
                        int i = 1;
                        foreach (string parameter in whereParameters)
                        {
                            VistaDBParameter p = new VistaDBParameter("@p" + i++.ToString(), e.Row[parameter]);
                            cmd.Parameters.Add(p);
                            where += comma + "[" + parameter + "]=" + p.ParameterName;
                            comma  = " AND ";
                        }

                        // Okay, now we can execute the sql and get any values that have defaults that were
                        // null at the time of the insert and/or our timestamp
                        cmd.CommandText = "SELECT " + select + " FROM [" + request.ProviderMetadata.Source + "] WHERE " + where + ";";

                        VistaDBDataReader rdr = null;

                        try
                        {
                            rdr = cmd.ExecuteReader(CommandBehavior.SingleResult);

                            if (rdr.Read())
                            {
                                select = select.Replace("[", String.Empty).Replace("]", String.Empty);
                                string[] selectCols = select.Split(',');

                                for (int k = 0; k < selectCols.Length; k++)
                                {
                                    packet.CurrentValues[selectCols[k]] = rdr.GetValue(k);
                                }
                            }
                        }
                        finally
                        {
                            // Make sure we close the reader no matter what
                            if (rdr != null)
                            {
                                rdr.Close();
                            }
                        }
                    }

                    if (e.StatementType == StatementType.Update)
                    {
                        string colName = props["EntitySpacesConcurrency"] as string;
                        object o       = e.Row[colName];

                        VistaDBParameter p = e.Command.Parameters["@" + colName];
                        object           v = null;

                        switch (Type.GetTypeCode(o.GetType()))
                        {
                        case TypeCode.Int16: v = ((System.Int16)o) + 1; break;

                        case TypeCode.Int32: v = ((System.Int32)o) + 1; break;

                        case TypeCode.Int64: v = ((System.Int64)o) + 1; break;

                        case TypeCode.UInt16: v = ((System.UInt16)o) + 1; break;

                        case TypeCode.UInt32: v = ((System.UInt32)o) + 1; break;

                        case TypeCode.UInt64: v = ((System.UInt64)o) + 1; break;
                        }

                        p.Value = v;
                    }
                }
            }
            catch { }
        }
Example #8
0
        protected static void OnRowUpdated(object sender, VistaDBRowUpdatedEventArgs e)
        {
            try
            {
                PropertyCollection props = e.Row.Table.ExtendedProperties;
                if (props.ContainsKey("props"))
                {
                    props = (PropertyCollection)props["props"];
                }

                if (e.Status == UpdateStatus.Continue && (e.StatementType == StatementType.Insert || e.StatementType == StatementType.Update))
                {
                    tgDataRequest request = props["tgDataRequest"] as tgDataRequest;
                    tgEntitySavePacket packet = (tgEntitySavePacket)props["esEntityData"];
                    string source = props["Source"] as string;

                    if (e.StatementType == StatementType.Insert)
                    {
                        if (props.Contains("AutoInc"))
                        {
                            string autoInc = props["AutoInc"] as string;

                            VistaDBCommand cmd = new VistaDBCommand();
                            cmd.Connection = e.Command.Connection;
                            cmd.Transaction = e.Command.Transaction;
                            cmd.CommandText = "SELECT LastIdentity([" + autoInc + "]) FROM [" + source + "]";

                            object o = null;

                            #region Profiling

                            if (sTraceHandler != null)
                            {
                                using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "OnRowUpdated", System.Environment.StackTrace))
                                {
                                    try
                                    {
                                        o = cmd.ExecuteScalar();
                                    }
                                    catch (Exception ex)
                                    {
                                        esTrace.Exception = ex.Message;
                                        throw;
                                    }
                                }
                            }
                            else

                            #endregion Profiling

                            {
                                o = cmd.ExecuteScalar();
                            }

                            if (o != null)
                            {
                                e.Row[autoInc] = o;
                                e.Command.Parameters["@" + autoInc].Value = o;
                            }
                        }

                        if (props.Contains("EntitySpacesConcurrency"))
                        {
                            string esConcurrencyColumn = props["EntitySpacesConcurrency"] as string;
                            packet.CurrentValues[esConcurrencyColumn] = 1;
                        }
                    }

                    if (props.Contains("Timestamp"))
                    {
                        string column = props["Timestamp"] as string;

                        VistaDBCommand cmd = new VistaDBCommand();
                        cmd.Connection = e.Command.Connection;
                        cmd.Transaction = e.Command.Transaction;
                        cmd.CommandText = "SELECT LastTimestamp('" + source + "');";

                        object o = null;

                        #region Profiling

                        if (sTraceHandler != null)
                        {
                            using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "OnRowUpdated", System.Environment.StackTrace))
                            {
                                try
                                {
                                    o = cmd.ExecuteScalar();
                                }
                                catch (Exception ex)
                                {
                                    esTrace.Exception = ex.Message;
                                    throw;
                                }
                            }
                        }
                        else

                        #endregion Profiling

                        {
                            o = cmd.ExecuteScalar();
                        }

                        if (o != null)
                        {
                            e.Command.Parameters["@" + column].Value = o;
                        }
                    }

                    //-------------------------------------------------------------------------------------------------
                    // Fetch any defaults, SQLite doesn't support output parameters so we gotta do this the hard way
                    //-------------------------------------------------------------------------------------------------
                    if (props.Contains("Defaults"))
                    {
                        // Build the Where parameter and parameters
                        VistaDBCommand cmd = new VistaDBCommand();
                        cmd.Connection = e.Command.Connection;
                        cmd.Transaction = e.Command.Transaction;

                        string select = (string)props["Defaults"];

                        string[] whereParameters = ((string)props["Where"]).Split(',');

                        string comma = String.Empty;
                        string where = String.Empty;
                        int i = 1;
                        foreach (string parameter in whereParameters)
                        {
                            VistaDBParameter p = new VistaDBParameter("@p" + i++.ToString(), e.Row[parameter]);
                            cmd.Parameters.Add(p);
                            where += comma + "[" + parameter + "]=" + p.ParameterName;
                            comma = " AND ";
                        }

                        // Okay, now we can execute the sql and get any values that have defaults that were
                        // null at the time of the insert and/or our timestamp
                        cmd.CommandText = "SELECT " + select + " FROM [" + request.ProviderMetadata.Source + "] WHERE " + where + ";";

                        VistaDBDataReader rdr = null;

                        try
                        {
                            #region Profiling

                            if (sTraceHandler != null)
                            {
                                using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "OnRowUpdated", System.Environment.StackTrace))
                                {
                                    try
                                    {
                                        rdr = cmd.ExecuteReader(CommandBehavior.SingleResult);
                                    }
                                    catch (Exception ex)
                                    {
                                        esTrace.Exception = ex.Message;
                                        throw;
                                    }
                                }
                            }
                            else

                            #endregion Profiling

                            {
                                rdr = cmd.ExecuteReader(CommandBehavior.SingleResult);
                            }

                            if (rdr.Read())
                            {
                                select = select.Replace("[", String.Empty).Replace("]", String.Empty);
                                string[] selectCols = select.Split(',');

                                for (int k = 0; k < selectCols.Length; k++)
                                {
                                    packet.CurrentValues[selectCols[k]] = rdr.GetValue(k);
                                }
                            }
                        }
                        finally
                        {
                            // Make sure we close the reader no matter what
                            if (rdr != null) rdr.Close();
                        }
                    }

                    if (e.StatementType == StatementType.Update)
                    {
                        string colName = props["EntitySpacesConcurrency"] as string;
                        object o = e.Row[colName];

                        VistaDBParameter p = e.Command.Parameters["@" + colName];
                        object v = null;

                        switch (Type.GetTypeCode(o.GetType()))
                        {
                            case TypeCode.Int16: v = ((System.Int16)o) + 1; break;
                            case TypeCode.Int32: v = ((System.Int32)o) + 1; break;
                            case TypeCode.Int64: v = ((System.Int64)o) + 1; break;
                            case TypeCode.UInt16: v = ((System.UInt16)o) + 1; break;
                            case TypeCode.UInt32: v = ((System.UInt32)o) + 1; break;
                            case TypeCode.UInt64: v = ((System.UInt64)o) + 1; break;
                        }

                        p.Value = v;
                    }
                }
            }
            catch { }
        }
Example #9
0
        tgDataResponse IDataProvider.ExecuteScalar(tgDataRequest request)
        {
            tgDataResponse response = new tgDataResponse();
            VistaDBCommand cmd = null;

            try
            {
                cmd = new VistaDBCommand();
                if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
                if (request.Parameters != null) Shared.AddParameters(cmd, request);

                switch (request.QueryType)
                {
                    case tgQueryType.TableDirect:
                        cmd.CommandType = CommandType.TableDirect;
                        cmd.CommandText = request.QueryText;
                        break;

                    case tgQueryType.StoredProcedure:
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = Shared.CreateFullName(request);
                        break;

                    case tgQueryType.Text:
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = request.QueryText;
                        break;

                    case tgQueryType.DynamicQuery:
                        cmd = QueryBuilder.PrepareCommand(request);
                        break;
                }

                try
                {
                    tgTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate);

                    #region Profiling

                    if (sTraceHandler != null)
                    {
                        using (esTraceArguments esTrace = new esTraceArguments(request, cmd, "ExecuteScalar", System.Environment.StackTrace))
                        {
                            try
                            {
                                response.Scalar = cmd.ExecuteScalar();
                            }
                            catch (Exception ex)
                            {
                                esTrace.Exception = ex.Message;
                                throw;
                            }
                        }
                    }
                    else

                    #endregion Profiling

                    {
                        response.Scalar = cmd.ExecuteScalar();
                    }
                }
                finally
                {
                    tgTransactionScope.DeEnlist(cmd);
                }

                if (request.Parameters != null)
                {
                    Shared.GatherReturnParameters(cmd, request, response);
                }
            }
            catch (Exception ex)
            {
                CleanupCommand(cmd);
                response.Exception = ex;
            }

            return response;
        }
Example #10
0
        // If it's an Insert we fetch the @@Identity value and stuff it in the proper column
        protected void OnRowUpdated(object sender, VistaDBRowUpdatedEventArgs e)
        {
            try
            {
                if(e.Status == UpdateStatus.Continue && e.StatementType == StatementType.Insert)
                {
                    TransactionMgr txMgr = TransactionMgr.ThreadTransactionMgr();

                    string[] identityCols = this.GetAutoKeyColumns().Split(';');

                    VistaDBCommand cmd = new VistaDBCommand();

                    foreach(string col in identityCols)
                    {
                        cmd.CommandText = "SELECT LastIdentity([" + col + "]) FROM [" + this.QuerySource + "]";

                        // We make sure we enlist in the ongoing transaction, otherwise, we
                        // would most likely deadlock
                        txMgr.Enlist(cmd, this);
                        object o = cmd.ExecuteScalar(); // Get the Identity Value
                        txMgr.DeEnlist(cmd, this);

                        if(o != null)
                        {
                            e.Row[col] = o;
                        }
                    }

                    e.Row.AcceptChanges();
                }
            }
            catch {}
        }
        esDataResponse IDataProvider.ExecuteScalar(esDataRequest request)
        {
            esDataResponse response = new esDataResponse();
            VistaDBCommand cmd = null;

            try
            {
                cmd = new VistaDBCommand();
                if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value;
                if (request.Parameters != null) Shared.AddParameters(cmd, request);

                switch (request.QueryType)
                {
                    case esQueryType.TableDirect:
                        cmd.CommandType = CommandType.TableDirect;
                        cmd.CommandText = request.QueryText;
                        break;

                    case esQueryType.StoredProcedure:
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = Shared.CreateFullName(request);
                        break;

                    case esQueryType.Text:
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = request.QueryText;
                        break;

                    case esQueryType.DynamicQuery:
                        cmd = QueryBuilder.PrepareCommand(request);
                        break;
                }

                try
                {
                    esTransactionScope.Enlist(cmd, request.ConnectionString, CreateIDbConnectionDelegate);
                    response.Scalar = cmd.ExecuteScalar();
                }
                finally
                {
                    esTransactionScope.DeEnlist(cmd);
                }

                if (request.Parameters != null)
                {
                    Shared.GatherReturnParameters(cmd, request, response);
                }
            }
            catch (Exception ex)
            {
                CleanupCommand(cmd);
                response.Exception = ex;
            }

            return response;
        }
 public static string GetDatabaseVersionFunction()
 {
     try
     {
         //To open a SQL connection to VistaDB from within a CLR Proc you must set the connection string to Context connection=true like this....
         //NOTE: We DO want to dispose of this object because we are the ones allocating it
         using (VistaDBConnection conn = new VistaDBConnection("Context Connection=true"))
         {
             conn.Open();
             using (VistaDBCommand command = new VistaDBCommand())
             {
                 command.Connection = conn;
                 command.CommandText = "SELECT @@Version";
                 return Convert.ToString(command.ExecuteScalar());
             }
         }
     }
     catch (Exception e)
     {
         return e.Message;
     }
 }
 public static int GetDatabaseVersionProcedure(out string versionString )
 {
     try
     {
         //To open a SQL connection to VistaDB from within a CLR Proc you must set the connection string to Context connection=true like this....
         //NOTE: We DO want to dispose of this object because we are the ones allocating it
         using (VistaDBConnection conn = new VistaDBConnection("Context Connection=true"))
         {
             conn.Open();
             using (VistaDBCommand command = new VistaDBCommand())
             {
                 command.Connection = conn;
                 command.CommandText = "SELECT @@Version";
                 versionString = Convert.ToString(command.ExecuteScalar());
                 return 0;
             }
         }
     }
     catch (Exception e)
     {
         throw new ApplicationException("Unable to get the database version due to Application Error", e);
     }
 }
        /// <summary>
        /// Call the Sql Function version to get the database version
        /// </summary>
        public static void CallGetDatabaseVersionFunctionSQL()
        {
            Console.WriteLine("Attempting to execute CLR Function GetDatabaseVersionFunction");
            using (VistaDBConnection connection = new VistaDBConnection(SampleRunner.ConnectionString))
            {
                connection.Open();

                try
                {
                    // Straight forward way to call a function is just using SELECT
                    // You cannot EXEC a SqlFunction, and you cannot set the command here to be a stored proc
                    // Setting this command to a stored proc is a common error, the two are not the same
                    // SqlFunction = SELECT to call
                    // SqlProcdure = EXEC or direct call using StoredProcedure command type
                    using (VistaDBCommand command = new VistaDBCommand())
                    {
                        command.Connection = connection;
                        command.CommandText = "SELECT GetVersionFunction();";
                        // The results are returned as a part of the standard rowset, so we only need to get back the first entry
                        Console.WriteLine(Convert.ToString(command.ExecuteScalar()));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to execute CLR Function GetVersionFunction, Reason: " + e.Message);
                }
            }
        }
        /// <summary>
        /// Execute a VistaDBCommand (that returns a 1x1 resultset) against the specified VistaDBTransaction
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int orderCount = (int)ExecuteScalar(trans, CommandType.Text, "Select count(Order) from TableTransaction where ProdId=?", new VistaDBParameter("@prodid", 24));
        /// </remarks>
        /// <param name="transaction">A valid VistaDBTransaction</param>
        /// <param name="commandType">The CommandType (TableDirect, Text)</param>
        /// <param name="commandText">The T-SQL command</param>
        /// <param name="commandParameters">An array of VistaDBParamters used to execute the command</param>
        /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
        public static object ExecuteScalar(VistaDBTransaction transaction, CommandType commandType, string commandText, params VistaDBParameter[] commandParameters)
        {
            if( transaction == null ) throw new ArgumentNullException( "transaction" );
            if( transaction != null && transaction.Connection == null ) throw new ArgumentException( "The transaction was rollbacked or commited, please provide an open transaction.", "transaction" );

            // Create a command and prepare it for execution
            VistaDBCommand cmd = new VistaDBCommand();
            bool mustCloseConnection = false;
            PrepareCommand(cmd, (VistaDBConnection)transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

            // Execute the command & return the results
            object retval = cmd.ExecuteScalar();

            // Detach the VistaDBParameters from the command object, so they can be used again
            cmd.Parameters.Clear();
            return retval;
        }
        /// <summary>
        /// Execute a VistaDBCommand (that returns a 1x1 resultset) against the specified VistaDBConnection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int orderCount = (int)ExecuteScalar(conn, CommandType.Text, "Select count(Order) from TableTransaction where ProdId=?", new VistaDBParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">A valid VistaDBConnection</param>
        /// <param name="commandType">The CommandType (TableDirect, Text)</param>
        /// <param name="commandText">The T-SQL command</param>
        /// <param name="commandParameters">An array of VistaDBParamters used to execute the command</param>
        /// <returns>An object containing the value in the 1x1 resultset generated by the command</returns>
        public static object ExecuteScalar(VistaDBConnection connection, CommandType commandType, string commandText, params VistaDBParameter[] commandParameters)
        {
            if( connection == null ) throw new ArgumentNullException( "connection" );

            // Create a command and prepare it for execution
            VistaDBCommand cmd = new VistaDBCommand();

            bool mustCloseConnection = false;
            PrepareCommand(cmd, connection, (VistaDBTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection );

            // Execute the command & return the results
            object retval = cmd.ExecuteScalar();

            // Detach the VistaDBParameters from the command object, so they can be used again
            cmd.Parameters.Clear();

            if( mustCloseConnection )
                connection.Close();

            return retval;
        }