Example #1
0
        public questStatus Delete(TablesetId tablesetId)
        {
            // Initialize
            questStatus      status = null;
            DbMgrTransaction trans  = null;


            // BEGIN TRANSACTION
            status = BeginTransaction("DeleteTableset_" + Guid.NewGuid().ToString(), out trans);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }


            try
            {
                // Delete tableset filters
                FiltersMgr filtersMgr = new FiltersMgr(this.UserSession);
                status = filtersMgr.Delete(trans, tablesetId);
                if (!questStatusDef.IsSuccess(status))
                {
                    RollbackTransaction(trans);
                    return(status);
                }

                // Delete Tableset
                DbTablesetsMgr dbTablesetsMgr = new DbTablesetsMgr(this.UserSession);
                status = dbTablesetsMgr.Delete(tablesetId);
                if (!questStatusDef.IsSuccess(status))
                {
                    RollbackTransaction(trans);
                    return(status);
                }

                // COMMIT TRANSACTION
                status = CommitTransaction(trans);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }
            }
            catch (System.Exception ex)
            {
                if (trans != null)
                {
                    RollbackTransaction(trans);
                }
                return(new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}",
                                                                     this.GetType().Name, MethodBase.GetCurrentMethod().Name,
                                                                     ex.InnerException != null ? ex.InnerException.Message : ex.Message)));
            }


            return(new questStatus(Severity.Success));
        }
        public questStatus PerformBulkInsert(BulkInsertRequest bulkInsertRequest)
        {
            // Initialize
            questStatus status = null;


            // Execute bulk insert SQL
            try
            {
                // Get tableset
                TablesetId     tablesetId     = new TablesetId(bulkInsertRequest.Filter.TablesetId);
                Tableset       tableset       = null;
                DbTablesetsMgr dbTablesetsMgr = new DbTablesetsMgr(this.UserSession);
                status = dbTablesetsMgr.Read(tablesetId, out tableset);
                if (!questStatusDef.IsSuccessOrWarning(status))
                {
                    return(status);
                }

                // Get database
                DatabaseId databaseId = new DatabaseId(tableset.DatabaseId);
                Quest.Functional.MasterPricing.Database database = null;
                DbDatabasesMgr dbDatabasesMgr = new DbDatabasesMgr(this.UserSession);
                status = dbDatabasesMgr.Read(databaseId, out database);
                if (!questStatusDef.IsSuccessOrWarning(status))
                {
                    return(status);
                }

                // Execute sql
                using (SqlConnection sqlConnection = new SqlConnection(database.ConnectionString))
                {
                    sqlConnection.Open();

                    using (SqlCommand cmd = sqlConnection.CreateCommand())
                    {
                        cmd.CommandText = bulkInsertRequest.SQL;
                        cmd.CommandType = CommandType.Text;

                        int numRows = cmd.ExecuteNonQuery();
                        if (numRows != bulkInsertRequest.Rows.Count)
                        {
                            return(new questStatus(Severity.Error, String.Format("ERROR: Bulk insert SQL execution failed: Rows: {0}", numRows)));
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                return(new questStatus(Severity.Fatal, String.Format("EXCEPTION: executing bulk insert SQL {0} SQL: {1}",
                                                                     bulkInsertRequest.SQL, ex.Message)));
            }
            return(new questStatus(Severity.Success));
        }
Example #3
0
        public questStatus ClearTablesetEntities(DbMgrTransaction trans, TablesetId tablesetId)
        {
            // Initialize
            questStatus status = null;

            DbTablesetsMgr dbTablesetsMgr = new DbTablesetsMgr(this.UserSession);

            status = dbTablesetsMgr.ClearTablesetEntities(trans, tablesetId);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            return(new questStatus(Severity.Success));
        }
        /*==================================================================================================================================
        * Private Methods
        *=================================================================================================================================*/
        private questStatus initialize()
        {
            // Initialize
            questStatus status = null;

            try
            {
                _dbTablesetsMgr = new DbTablesetsMgr(this.UserSession);
            }
            catch (System.Exception ex)
            {
                status = new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}",
                                                                       this.GetType().ToString(), MethodInfo.GetCurrentMethod().Name, ex.Message));
                throw new System.Exception(status.Message, ex);
            }
            return(new questStatus(Severity.Success));
        }
        private questStatus klugieGetFilterItemInfo(FilterItem filterItem, out DatabaseId databaseId, out TablesetId tablesetId)
        {
            // Initialize
            questStatus status = null;

            databaseId = null;
            tablesetId = null;


            // Klugie: temporary
            // Just back up and get stuff we need.  (All this due to refactoring, more to do).

            // Get the filter
            FilterId     filterId     = new FilterId(filterItem.FilterId);
            Filter       filter       = null;
            DbFiltersMgr dbFiltersMgr = new DbFiltersMgr(this.UserSession);

            status = dbFiltersMgr.Read(filterId, out filter);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }

            // Get the tableset
            DbTablesetsMgr dbTablesetsMgr = new DbTablesetsMgr(this.UserSession);

            tablesetId = new TablesetId(filter.TablesetId);
            Tableset tableset = null;

            status = dbTablesetsMgr.Read(tablesetId, out tableset);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }

            // Return info.
            databaseId = new DatabaseId(tableset.DatabaseId);
            tablesetId = new TablesetId(tableset.Id);

            return(new questStatus(Severity.Success));
        }
Example #6
0
        public questStatus PerformBulkUpdateFilterProcedure(BulkUpdateRequest bulkUpdateRequest, FilterProcedure filterProcedure, ResultsSet resultsSet)
        {
            // Initialize
            questStatus     status           = null;
            BulkUpdateLog   bulkUpdateLog    = bLogging ? new BulkUpdateLog() : null;
            BulkUpdateLogId bulkUpdateLogId  = null;
            int             numRows          = 0;
            string          logMessage       = null;
            List <string>   logParameterList = null;


            try
            {
                // Initialize log
                if (bLogging)
                {
                    bulkUpdateLog.Event         = "Initialize";
                    bulkUpdateLog.UserSessionId = this.UserSession.Id;
                    bulkUpdateLog.Username      = this.UserSession.User.Username;
                    bulkUpdateLog.Batch         = Guid.NewGuid().ToString();
                    string Filter = null;
                    status = _dbBulkUpdateLogsMgr.SetFilter(bulkUpdateRequest.Filter, out Filter);
                    if (!questStatusDef.IsSuccess(status))
                    {
                        return(status);
                    }
                    bulkUpdateLog.Filter = Filter;
                }

                // Get database connection string
                TablesetId     tablesetId     = new TablesetId(bulkUpdateRequest.Filter.TablesetId);
                Tableset       tableset       = null;
                DbTablesetsMgr dbTablesetsMgr = new DbTablesetsMgr(this.UserSession);
                status = dbTablesetsMgr.Read(tablesetId, out tableset);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }
                if (bLogging)
                {
                    string Tableset = null;
                    status = _dbBulkUpdateLogsMgr.SetTableset(tableset, out Tableset);
                    if (!questStatusDef.IsSuccess(status))
                    {
                        return(status);
                    }
                    bulkUpdateLog.Tableset = Tableset;
                }

                DatabaseId databaseId = new DatabaseId(tableset.DatabaseId);
                Quest.Functional.MasterPricing.Database database = null;
                DbDatabasesMgr dbDatabasesMgr = new DbDatabasesMgr(this.UserSession);
                status = dbDatabasesMgr.Read(databaseId, out database);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }
                if (bLogging)
                {
                    string Database = null;
                    status = _dbBulkUpdateLogsMgr.SetDatabase(database, out Database);
                    if (!questStatusDef.IsSuccess(status))
                    {
                        return(status);
                    }
                    bulkUpdateLog.Database = Database;
                }


                // Connect and execute
                bool bTransaction = true;  // Update all rows are none of them.
                using (SqlConnection conn = new SqlConnection(database.ConnectionString))
                {
                    bulkUpdateLog.Event = "Connect";
                    conn.Open();
                    SqlTransaction trans = null;
                    if (bTransaction)
                    {
                        trans = conn.BeginTransaction();
                        if (bLogging)
                        {
                            bulkUpdateLog.Event = "BeginTransaction";
                        }
                    }
                    numRows = 0;
                    foreach (dynamic _dynRow in resultsSet.Data)
                    {
                        using (SqlCommand cmd = new SqlCommand(null, conn, trans))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.CommandText = filterProcedure.Name;

                            // Initialize logging info
                            if (bLogging)
                            {
                                logParameterList         = new List <string>();
                                bulkUpdateLog.Event      = null;
                                bulkUpdateLog.NumRows    = numRows;
                                bulkUpdateLog.Parameters = null;
                                bulkUpdateLog.Message    = null;
                                bulkUpdateLog.Data       = null;
                            }

                            List <string> dataValueList = new List <string>();
                            foreach (FilterProcedureParameter filterParam in filterProcedure.ParameterList)
                            {
                                if (bLogging)
                                {
                                    bulkUpdateLog.Event = "Next Parameter: " + filterParam.ParameterName;
                                }

                                if (filterParam.Direction != "Input")
                                {
                                    SqlParameter sqlParam = new SqlParameter();
                                    if (filterParam.Direction == "ReturnValue")
                                    {
                                        sqlParam.Direction = ParameterDirection.ReturnValue;
                                    }
                                    else if (filterParam.Direction == "Output")
                                    {
                                        sqlParam.Direction = ParameterDirection.Output;
                                    }
                                    else
                                    {
                                        continue; // Input/ouput TODO
                                    }
                                    sqlParam.ParameterName = filterParam.ParameterName;


                                    // TEMPORARY
                                    continue;
                                }
                                if (bLogging)
                                {
                                    logParameterList.Add(String.Format(" Id: {0}, ParameterName: {1}, SqlDbType: {2} ", filterParam.Id, filterParam.ParameterName, filterParam.SqlDbType.ToString()));
                                    string parameterArray = null;
                                    _dbBulkUpdateLogsMgr.SetArray(logParameterList, out parameterArray);
                                    bulkUpdateLog.Parameters = parameterArray;
                                }

                                // If a meta-parameter, fill in its value and continue.
                                bool         bIsMetaParameter = false;
                                SqlParameter sqlMetaParameter = null;
                                if (filterParam.ParameterName.Equals("@_Username", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    bIsMetaParameter       = true;
                                    sqlMetaParameter       = new SqlParameter(filterParam.ParameterName, SqlDbType.NVarChar);
                                    sqlMetaParameter.Value = this.UserSession.User.Username;
                                }
                                else if (filterParam.ParameterName.Equals("@_UserSessionId", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    bIsMetaParameter       = true;
                                    sqlMetaParameter       = new SqlParameter(filterParam.ParameterName, SqlDbType.Int);
                                    sqlMetaParameter.Value = this.UserSession.Id;
                                }
                                else if (filterParam.ParameterName.StartsWith("@_", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    logMessage = String.Format("ERROR: unknown meta-parameter: {0}", filterParam.ParameterName);
                                    if (bLogging)
                                    {
                                        bulkUpdateLog.Message = logMessage;
                                        _dbBulkUpdateLogsMgr.Create(bulkUpdateLog, out bulkUpdateLogId);
                                    }
                                    return(new questStatus(Severity.Error, logMessage));
                                }
                                if (bIsMetaParameter)
                                {
                                    cmd.Parameters.Add(sqlMetaParameter);
                                    continue;
                                }


                                // Get the column name from the parameter name
                                FilterItem bulkUpdateFilterItem = bulkUpdateRequest.Filter.FilterItemList.Find(delegate(FilterItem fi)
                                {
                                    return(String.Equals(fi.ParameterName, filterParam.ParameterName, StringComparison.CurrentCultureIgnoreCase));
                                });
                                if (bulkUpdateFilterItem == null)
                                {
                                    if (bTransaction)
                                    {
                                        trans.Rollback();
                                    }
                                    logMessage = String.Format("ERROR: filter item not found for sproc parameter {0}",
                                                               filterParam.ParameterName);
                                    if (bLogging)
                                    {
                                        bulkUpdateLog.Message = logMessage;
                                        _dbBulkUpdateLogsMgr.Create(bulkUpdateLog, out bulkUpdateLogId);
                                    }
                                    return(new questStatus(Severity.Error, logMessage));
                                }

                                // Get the bulk update value.
                                // NOTE: THIS COULD BE A TROUBLE SPOT.  ORIGINAL REQUIREMENT WAS SINGLE-ENTITY FILTERS ONLY HAD PROCEDURES.  THUS, THOSE FILTER ITEMS
                                //       WOULD NEVER HAVE NAMES QUALIFIED BY THE ENTITY THEY'RE IN.  BUT, FILTERS WITH ENTITIES THAT HAVE NO COLUMNS IN THE FILTER ITEMS
                                //       TECHNICALLY QUALIFY AS 'SINGLE-ENTITY FILTER'.  THUS, IF THE NAME ALONE DOESN'T MATCH.  GO FOR THE ENTITY_NAME AS A MATCH.
                                BulkUpdateColumnValue bulkUpdateColumnValue = bulkUpdateRequest.Columns.Find(delegate(BulkUpdateColumnValue cv)
                                {
                                    return(cv.Name == bulkUpdateFilterItem.FilterColumn.Name);
                                });
                                if (bulkUpdateColumnValue == null)
                                {
                                    bulkUpdateColumnValue = bulkUpdateRequest.Columns.Find(delegate(BulkUpdateColumnValue cv)
                                    {
                                        string[] parts = cv.Name.Split('_');
                                        if (parts.Length == 2)
                                        {
                                            return(parts[0] == bulkUpdateFilterItem.FilterColumn.ParentEntityType.Name && parts[1] == bulkUpdateFilterItem.FilterColumn.Name);
                                        }
                                        return(false);
                                    });
                                }
                                if (bulkUpdateColumnValue == null)
                                {
                                    return(new questStatus(Severity.Error, String.Format("ERROR: bulk update column value {0} not found in bulk update columns",
                                                                                         bulkUpdateFilterItem.FilterColumn.Name)));
                                }
                                if (bLogging)
                                {
                                    bulkUpdateLog.BulkUpdateColumn = String.Format(" Name: {0}, Value: {1} ", bulkUpdateColumnValue.Name, bulkUpdateColumnValue.Value);
                                }


                                // Determine bulk update value to use.
                                string updateValue = null;
                                if (bulkUpdateColumnValue.bNull)
                                {
                                    updateValue = null;
                                }
                                else if (!string.IsNullOrEmpty(bulkUpdateColumnValue.Value))
                                {
                                    updateValue = bulkUpdateColumnValue.Value;
                                }
                                else if (filterParam.bRequired)
                                {
                                    // Indexing not working, but should be ...
                                    ////updateValue = _dynRow[bulkUpdateColumnValue.Name];
                                    bool bFound = false;
                                    foreach (KeyValuePair <string, object> kvp in _dynRow)
                                    {
                                        if (kvp.Key == bulkUpdateColumnValue.Name)
                                        {
                                            updateValue = kvp.Value != null?kvp.Value.ToString() : null;    // Not sure if we go w/ Null here. But, oh well ...

                                            bFound = true;
                                            break;
                                        }
                                    }
                                    if (!bFound)
                                    {
                                        return(new questStatus(Severity.Error, String.Format("ERROR: filter results column {0} not found to use in bulk update operation",
                                                                                             bulkUpdateColumnValue.Name)));
                                    }
                                }
                                else  // Value is required, use results value since a value not specified in bulk updates.
                                {
                                    updateValue = null;
                                }



                                // Bind the parameter
                                // TODO:REFACTOR
                                SqlDbType    sqlDbType    = (SqlDbType)Enum.Parse(typeof(SqlDbType), filterParam.SqlDbType, true);
                                SqlParameter sqlParameter = new SqlParameter(filterParam.ParameterName, sqlDbType);

                                if (bLogging)
                                {
                                    bulkUpdateLog.Event = "Set Parameter Value";
                                }


                                if (sqlDbType == SqlDbType.Bit)
                                {
                                    bool bValue = updateValue != "0";
                                    sqlParameter.Value = bValue;
                                }
                                else if (sqlDbType == SqlDbType.Int)
                                {
                                    int intValue = Convert.ToInt32(updateValue);
                                    sqlParameter.Value = intValue;
                                }
                                else if (sqlDbType == SqlDbType.NVarChar)
                                {
                                    if (updateValue == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = updateValue.ToString();
                                    }
                                }
                                else if (sqlDbType == SqlDbType.VarChar)
                                {
                                    if (updateValue == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = updateValue.ToString();
                                    }
                                }
                                else if (sqlDbType == SqlDbType.DateTime)
                                {
                                    if (updateValue == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = Convert.ToDateTime(updateValue);
                                    }
                                }
                                else if (sqlDbType == SqlDbType.DateTime2)
                                {
                                    if (updateValue == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = Convert.ToDateTime(updateValue);
                                    }
                                }
                                else if (sqlDbType == SqlDbType.Date)
                                {
                                    if (updateValue == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = Convert.ToDateTime(updateValue);
                                    }
                                }
                                else if (sqlDbType == SqlDbType.Decimal)
                                {
                                    if (updateValue == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = Convert.ToDecimal(updateValue);
                                    }
                                }
                                else
                                {
                                    if (updateValue == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = updateValue;
                                    }
                                }
                                cmd.Parameters.Add(sqlParameter);
                                if (bLogging)
                                {
                                    dataValueList.Add(String.Format(" Name: {0}, Value: {1} ", sqlParameter.ParameterName,
                                                                    sqlParameter.Value == DBNull.Value ? "null" : sqlParameter.Value.ToString()));
                                }
                            }
                            // Execute the command
                            try
                            {
                                if (bLogging)
                                {
                                    bulkUpdateLog.Event = "ExecuteNonQuery";
                                }
                                int _numRows = cmd.ExecuteNonQuery();
                                if (_numRows != 1)
                                {
                                    if (bTransaction)
                                    {
                                        trans.Rollback();
                                    }
                                    logMessage = String.Format("ERROR: Bulk update stored procedure failed: Rows: {0}", _numRows);
                                    if (bLogging)
                                    {
                                        bulkUpdateLog.Message = logMessage;
                                        _dbBulkUpdateLogsMgr.Create(bulkUpdateLog, out bulkUpdateLogId);
                                    }
                                    return(new questStatus(Severity.Error, logMessage));
                                }
                                else if (bLoggingPerRow)
                                {
                                    bulkUpdateLog.Message          = "Successful bulk update";
                                    bulkUpdateLog.NumRows          = _numRows;
                                    bulkUpdateLog.BulkUpdateColumn = null;

                                    string valueArray = null;
                                    _dbBulkUpdateLogsMgr.SetArray(dataValueList, out valueArray);
                                    bulkUpdateLog.Data = valueArray;

                                    _dbBulkUpdateLogsMgr.Create(bulkUpdateLog, out bulkUpdateLogId);
                                }
                            }
                            catch (SqlException ex)
                            {
                                if (bTransaction)
                                {
                                    trans.Rollback();
                                }
                                logMessage = String.Format("SQL EXCEPTION: Bulk update stored procedure {0}: {1}",
                                                           filterProcedure.Name, ex.Message);
                                if (bLogging)
                                {
                                    bulkUpdateLog.Message = logMessage;
                                    _dbBulkUpdateLogsMgr.Create(bulkUpdateLog, out bulkUpdateLogId);
                                }
                                return(new questStatus(Severity.Error, logMessage));
                            }
                            catch (System.Exception ex)
                            {
                                if (bTransaction)
                                {
                                    trans.Rollback();
                                }
                                logMessage = String.Format("EXCEPTION: Bulk update stored procedure {0}: {1}",
                                                           filterProcedure.Name, ex.Message);
                                if (bLogging)
                                {
                                    bulkUpdateLog.Message = logMessage;
                                    _dbBulkUpdateLogsMgr.Create(bulkUpdateLog, out bulkUpdateLogId);
                                }
                                return(new questStatus(Severity.Error, logMessage));
                            }
                        }
                        numRows += 1;
                    }
                    if (bTransaction)
                    {
                        trans.Commit();
                    }
                    if (bLogging)
                    {
                        bulkUpdateLog.Event            = "COMMIT";
                        bulkUpdateLog.NumRows          = numRows;
                        bulkUpdateLog.BulkUpdateColumn = null;
                        bulkUpdateLog.Message          = "Bulk update operation successful";
                        bulkUpdateLog.Data             = null;

                        _dbBulkUpdateLogsMgr.Create(bulkUpdateLog, out bulkUpdateLogId);
                    }
                }
            }
            catch (System.Exception ex)
            {
                logMessage = String.Format("EXCEPTION: Bulk Update Operation: {0}.{1}: {2}",
                                           this.GetType().Name, MethodBase.GetCurrentMethod().Name,
                                           ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                if (bLogging)
                {
                    bulkUpdateLog.Event   = bulkUpdateLog.Event == null ? "EXCEPTION" : bulkUpdateLog.Event;
                    bulkUpdateLog.Message = logMessage;
                    bulkUpdateLog.NumRows = numRows;

                    string parameterArray = null;
                    _dbBulkUpdateLogsMgr.SetArray(logParameterList, out parameterArray);
                    bulkUpdateLog.Parameters = parameterArray;

                    string Exception = null;
                    _dbBulkUpdateLogsMgr.SetException(ex, out Exception);
                    bulkUpdateLog.Data = Exception;

                    _dbBulkUpdateLogsMgr.Create(bulkUpdateLog, out bulkUpdateLogId);
                }
                return(new questStatus(Severity.Fatal, logMessage));
            }
            return(new questStatus(Severity.Success));
        }
Example #7
0
        public questStatus PerformBulkUpdate(BulkUpdateRequest bulkUpdateRequest, out int numRows)
        {
            // Initialize
            questStatus status = null;

            numRows = -1;

            try
            {
                // Get database connection string
                TablesetId     tablesetId     = new TablesetId(bulkUpdateRequest.Filter.TablesetId);
                Tableset       tableset       = null;
                DbTablesetsMgr dbTablesetsMgr = new DbTablesetsMgr(this.UserSession);
                status = dbTablesetsMgr.Read(tablesetId, out tableset);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }
                DatabaseId databaseId = new DatabaseId(tableset.DatabaseId);
                Quest.Functional.MasterPricing.Database database = null;
                DbDatabasesMgr dbDatabasesMgr = new DbDatabasesMgr(this.UserSession);
                status = dbDatabasesMgr.Read(databaseId, out database);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }

                using (SqlConnection conn = new SqlConnection(database.ConnectionString))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand(null, conn))
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = bulkUpdateRequest.SQL;
                        try
                        {
                            int retval = cmd.ExecuteNonQuery();
                            if (retval < 0)
                            {
                                return(new questStatus(Severity.Error, String.Format("ERROR: Bulk update failed: {0}", numRows)));
                            }
                            if (retval == 0)
                            {
                                return(new questStatus(Severity.Warning, String.Format("WARNING: {0} rows bulk updated", numRows)));
                            }
                            numRows += retval;
                        }
                        catch (System.Exception ex)
                        {
                            return(new questStatus(Severity.Error, String.Format("EXCEPTION: Bulk update failed: {0}",
                                                                                 ex.Message)));
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                return(new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}",
                                                                     this.GetType().Name, MethodBase.GetCurrentMethod().Name,
                                                                     ex.InnerException != null ? ex.InnerException.Message : ex.Message)));
            }
            return(new questStatus(Severity.Success));
        }
        public questStatus PerformBulkInsertFilterProcedure(BulkInsertRequest bulkInsertRequest, FilterProcedure filterProcedure)
        {
            // Initialize
            questStatus     status           = null;
            BulkInsertLog   bulkInsertLog    = bLogging ? new BulkInsertLog() : null;
            BulkInsertLogId bulkInsertLogId  = null;
            int             numRows          = 0;
            string          logMessage       = null;
            List <string>   logParameterList = null;


            try
            {
                // Initialize log
                if (bLogging)
                {
                    bulkInsertLog.Event         = "Initialize";
                    bulkInsertLog.UserSessionId = this.UserSession.Id;
                    bulkInsertLog.Username      = this.UserSession.User.Username;
                    bulkInsertLog.Batch         = Guid.NewGuid().ToString();
                    string Filter = null;
                    status = _dbBulkInsertLogsMgr.SetFilter(bulkInsertRequest.Filter, out Filter);
                    if (!questStatusDef.IsSuccess(status))
                    {
                        return(status);
                    }
                    bulkInsertLog.Filter = Filter;
                }

                // Get database connection string
                TablesetId     tablesetId     = new TablesetId(bulkInsertRequest.TablesetId);
                Tableset       tableset       = null;
                DbTablesetsMgr dbTablesetsMgr = new DbTablesetsMgr(this.UserSession);
                status = dbTablesetsMgr.Read(tablesetId, out tableset);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }
                if (bLogging)
                {
                    string Tableset = null;
                    status = _dbBulkInsertLogsMgr.SetTableset(tableset, out Tableset);
                    if (!questStatusDef.IsSuccess(status))
                    {
                        return(status);
                    }
                    bulkInsertLog.Tableset = Tableset;
                }

                DatabaseId databaseId = new DatabaseId(tableset.DatabaseId);
                Quest.Functional.MasterPricing.Database database = null;
                DbDatabasesMgr dbDatabasesMgr = new DbDatabasesMgr(this.UserSession);
                status = dbDatabasesMgr.Read(databaseId, out database);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }
                if (bLogging)
                {
                    string Database = null;
                    status = _dbBulkInsertLogsMgr.SetDatabase(database, out Database);
                    if (!questStatusDef.IsSuccess(status))
                    {
                        return(status);
                    }
                    bulkInsertLog.Database = Database;
                }

                // Connect and execute
                bool bTransaction = false;
                bulkInsertLog.Event = "Open";
                using (SqlConnection conn = new SqlConnection(database.ConnectionString))
                {
                    bulkInsertLog.Event = "Connect";
                    conn.Open();
                    SqlTransaction trans = null;
                    if (bTransaction)
                    {
                        trans = conn.BeginTransaction();
                        if (bLogging)
                        {
                            bulkInsertLog.Event = "BeginTransaction";
                        }
                    }
                    numRows = 0;
                    foreach (BulkInsertRow bulkInsertRow in bulkInsertRequest.Rows)
                    {
                        using (SqlCommand cmd = new SqlCommand(null, conn, trans))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.CommandText = filterProcedure.Name;

                            // Initialize logging info
                            if (bLogging)
                            {
                                logParameterList         = new List <string>();
                                bulkInsertLog.Event      = null;
                                bulkInsertLog.NumRows    = numRows;
                                bulkInsertLog.Parameters = null;
                                bulkInsertLog.Message    = null;
                                bulkInsertLog.Data       = null;
                            }

                            // Build each parameter
                            List <string> dataValueList = new List <string>();
                            foreach (FilterProcedureParameter filterParam in filterProcedure.ParameterList)
                            {
                                if (bLogging)
                                {
                                    bulkInsertLog.Event = "Next Parameter: " + filterParam.ParameterName;
                                }

                                if (filterParam.Direction != "Input")
                                {
                                    continue;
                                }
                                if (bLogging)
                                {
                                    logParameterList.Add(String.Format(" Id: {0}, ParameterName: {1}, SqlDbType: {2} ", filterParam.Id, filterParam.ParameterName, filterParam.SqlDbType.ToString()));
                                    string parameterArray = null;
                                    _dbBulkInsertLogsMgr.SetArray(logParameterList, out parameterArray);
                                    bulkInsertLog.Parameters = parameterArray;
                                }

                                // If a meta-parameter, fill in its value and continue.
                                bool         bIsMetaParameter = false;
                                SqlParameter sqlMetaParameter = null;
                                if (filterParam.ParameterName.Equals("@_Username", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    bIsMetaParameter       = true;
                                    sqlMetaParameter       = new SqlParameter(filterParam.ParameterName, SqlDbType.NVarChar);
                                    sqlMetaParameter.Value = this.UserSession.User.Username;
                                }
                                else if (filterParam.ParameterName.Equals("@_UserSessionId", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    bIsMetaParameter       = true;
                                    sqlMetaParameter       = new SqlParameter(filterParam.ParameterName, SqlDbType.Int);
                                    sqlMetaParameter.Value = this.UserSession.Id;
                                }
                                else if (filterParam.ParameterName.StartsWith("@_", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    logMessage = String.Format("ERROR: unknown meta-parameter: {0}", filterParam.ParameterName);
                                    if (bLogging)
                                    {
                                        bulkInsertLog.Message = logMessage;
                                        _dbBulkInsertLogsMgr.Create(bulkInsertLog, out bulkInsertLogId);
                                    }
                                    return(new questStatus(Severity.Error, logMessage));
                                }
                                if (bIsMetaParameter)
                                {
                                    cmd.Parameters.Add(sqlMetaParameter);
                                    continue;
                                }


                                // Not a meta-parameter, so the bulk insert value should be provided.
                                BulkInsertColumnValue bulkInsertColumnValue = bulkInsertRow.Columns.Find(delegate(BulkInsertColumnValue cv) {
                                    return(cv.Name == filterParam.ParameterName);
                                });
                                if (bulkInsertColumnValue == null)
                                {
                                    if (bTransaction)
                                    {
                                        trans.Rollback();
                                    }

                                    logMessage = String.Format("ERROR: sproc parameter {0} not found in bulk insert columns",
                                                               filterParam.ParameterName);
                                    if (bLogging)
                                    {
                                        bulkInsertLog.Message = logMessage;
                                        _dbBulkInsertLogsMgr.Create(bulkInsertLog, out bulkInsertLogId);
                                    }
                                    return(new questStatus(Severity.Error, logMessage));
                                }
                                if (bLogging)
                                {
                                    bulkInsertLog.BulkInsertColumn = String.Format(" Name: {0}, Value: {1} ", bulkInsertColumnValue.Name, bulkInsertColumnValue.Value);
                                }



                                // Bind the parameter
                                // TODO:REFACTOR
                                SqlDbType    sqlDbType    = (SqlDbType)Enum.Parse(typeof(SqlDbType), filterParam.SqlDbType, true);
                                SqlParameter sqlParameter = new SqlParameter(filterParam.ParameterName, sqlDbType);


                                if (bLogging)
                                {
                                    bulkInsertLog.Event = "Set Parameter Value";
                                }

                                if (sqlDbType == SqlDbType.Bit)
                                {
                                    bool bValue = bulkInsertColumnValue.Value != "0";
                                    sqlParameter.Value = bValue;
                                }
                                else if (sqlDbType == SqlDbType.Int)
                                {
                                    int intValue = Convert.ToInt32(bulkInsertColumnValue.Value);
                                    sqlParameter.Value = intValue;
                                }
                                else if (sqlDbType == SqlDbType.NVarChar)
                                {
                                    if (bulkInsertColumnValue.Value == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = bulkInsertColumnValue.Value.ToString();
                                    }
                                }
                                else if (sqlDbType == SqlDbType.VarChar)
                                {
                                    if (bulkInsertColumnValue.Value == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = bulkInsertColumnValue.Value.ToString();
                                    }
                                }
                                else if (sqlDbType == SqlDbType.DateTime)
                                {
                                    if (bulkInsertColumnValue.Value == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = Convert.ToDateTime(bulkInsertColumnValue.Value);
                                    }
                                }
                                else if (sqlDbType == SqlDbType.DateTime2)
                                {
                                    if (bulkInsertColumnValue.Value == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = Convert.ToDateTime(bulkInsertColumnValue.Value);
                                    }
                                }
                                else if (sqlDbType == SqlDbType.Date)
                                {
                                    if (bulkInsertColumnValue.Value == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = Convert.ToDateTime(bulkInsertColumnValue.Value);
                                    }
                                }
                                else if (sqlDbType == SqlDbType.Decimal)
                                {
                                    if (bulkInsertColumnValue.Value == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = Convert.ToDecimal(bulkInsertColumnValue.Value);
                                    }
                                }
                                else
                                {
                                    if (bulkInsertColumnValue.Value == null)
                                    {
                                        sqlParameter.Value = DBNull.Value;
                                    }
                                    else
                                    {
                                        sqlParameter.Value = bulkInsertColumnValue.Value;
                                    }
                                }
                                cmd.Parameters.Add(sqlParameter);
                                if (bLogging)
                                {
                                    dataValueList.Add(String.Format(" Name: {0}, Value: {1} ", sqlParameter.ParameterName,
                                                                    sqlParameter.Value == DBNull.Value ? "null" : sqlParameter.Value.ToString()));
                                }
                            }
                            try
                            {
                                if (bLogging)
                                {
                                    bulkInsertLog.Event = "ExecuteNonQuery";
                                }
                                int _numRows = cmd.ExecuteNonQuery();
                                if (_numRows != 1)
                                {
                                    if (bTransaction)
                                    {
                                        trans.Rollback();
                                    }
                                    logMessage = String.Format("ERROR: Bulk insert stored procedure failed: Rows: {0}", _numRows);
                                    if (bLogging)
                                    {
                                        bulkInsertLog.Message = logMessage;
                                        _dbBulkInsertLogsMgr.Create(bulkInsertLog, out bulkInsertLogId);
                                    }
                                    return(new questStatus(Severity.Error, logMessage));
                                }
                                else if (bLoggingPerRow)
                                {
                                    bulkInsertLog.Message          = "Successful bulk insert";
                                    bulkInsertLog.NumRows          = _numRows;
                                    bulkInsertLog.BulkInsertColumn = null;

                                    string valueArray = null;
                                    _dbBulkInsertLogsMgr.SetArray(dataValueList, out valueArray);
                                    bulkInsertLog.Data = valueArray;

                                    _dbBulkInsertLogsMgr.Create(bulkInsertLog, out bulkInsertLogId);
                                }
                            }
                            catch (SqlException ex)
                            {
                                if (bTransaction)
                                {
                                    trans.Rollback();
                                }
                                logMessage = String.Format("SQL EXCEPTION: Bulk insert stored procedure {1}: {2}",
                                                           numRows, filterProcedure.Name, ex.Message);
                                if (bLogging)
                                {
                                    bulkInsertLog.Message = logMessage;
                                    _dbBulkInsertLogsMgr.Create(bulkInsertLog, out bulkInsertLogId);
                                }
                                return(new questStatus(Severity.Error, logMessage));
                            }
                            catch (System.Exception ex)
                            {
                                if (bTransaction)
                                {
                                    trans.Rollback();
                                }
                                logMessage = String.Format("After {0} rows, EXCEPTION: Bulk insert stored procedure {0}: {1}",
                                                           numRows, filterProcedure.Name, ex.Message);
                                if (bLogging)
                                {
                                    bulkInsertLog.Message = logMessage;
                                    _dbBulkInsertLogsMgr.Create(bulkInsertLog, out bulkInsertLogId);
                                }
                                return(new questStatus(Severity.Error, logMessage));
                            }
                        }
                        numRows += 1;
                    }
                    if (bTransaction)
                    {
                        trans.Commit();
                    }
                    if (bLogging)
                    {
                        bulkInsertLog.Event            = "COMMIT";
                        bulkInsertLog.NumRows          = numRows;
                        bulkInsertLog.BulkInsertColumn = null;
                        bulkInsertLog.Message          = "Bulk isnert operation successful";
                        bulkInsertLog.Data             = null;

                        _dbBulkInsertLogsMgr.Create(bulkInsertLog, out bulkInsertLogId);
                    }
                }
            }
            catch (System.Exception ex)
            {
                logMessage = String.Format("EXCEPTION: Bulk Insert Operation: {0}.{1}: {2}",
                                           this.GetType().Name, MethodBase.GetCurrentMethod().Name,
                                           ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                if (bLogging)
                {
                    bulkInsertLog.Event   = bulkInsertLog.Event == null ? "EXCEPTION" : bulkInsertLog.Event;
                    bulkInsertLog.Message = logMessage;
                    bulkInsertLog.NumRows = numRows;

                    string parameterArray = null;
                    _dbBulkInsertLogsMgr.SetArray(logParameterList, out parameterArray);
                    bulkInsertLog.Parameters = parameterArray;

                    string Exception = null;
                    _dbBulkInsertLogsMgr.SetException(ex, out Exception);
                    bulkInsertLog.Data = Exception;

                    _dbBulkInsertLogsMgr.Create(bulkInsertLog, out bulkInsertLogId);
                }
                return(new questStatus(Severity.Fatal, logMessage));
            }
            return(new questStatus(Severity.Success));
        }
        /*==================================================================================================================================
        * Public Methods
        *=================================================================================================================================*/
        public questStatus ExecuteFilter(RunFilterRequest runFilterRequest, out ResultsSet resultsSet)
        {
            // Initialize
            questStatus status = null;

            resultsSet = null;


            // Get the filter
            FilterId    filterId    = new FilterId(runFilterRequest.FilterId.Id);
            Filter      filter      = null;
            DbFilterMgr dbFilterMgr = new DbFilterMgr(this.UserSession);

            status = dbFilterMgr.GetFilter(filterId, out filter);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }

            // If no SQL, return.
            if (string.IsNullOrEmpty(filter.SQL))
            {
                return(new questStatus(Severity.Error, "Filter has no SQL"));
            }


            // Read the tableset
            TablesetId     tablesetId     = new TablesetId(filter.TablesetId);
            Tableset       tableset       = null;
            DbTablesetsMgr dbTablesetsMgr = new DbTablesetsMgr(this.UserSession);

            status = dbTablesetsMgr.Read(tablesetId, out tableset);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }

            // Read the database
            DatabaseId databaseId = new DatabaseId(tableset.DatabaseId);

            Quest.Functional.MasterPricing.Database database = null;
            DbDatabasesMgr dbDatabasesMgr = new DbDatabasesMgr(this.UserSession);

            status = dbDatabasesMgr.Read(databaseId, out database);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }

            // Execute SQL.
            try {
                status = executeSQL(runFilterRequest, database, filter, out resultsSet);
                if (!questStatusDef.IsSuccess(status))
                {
                    return(status);
                }
            }
            catch (System.Exception ex)
            {
                return(new questStatus(Severity.Error, String.Format("EXCEPTION: executing filter SQL: {0}", ex.Message)));
            }

            // klugie: Get number of FROM entities
            string FROMClause = null;
            List <FilterEntity> FROMEntityList = null;
            List <JoinEntity>   joinEntityList = null;
            DbFilterSQLMgr      dbFilterSQLMgr = new DbFilterSQLMgr();

            status = dbFilterSQLMgr.GetFROMEntities(filter, out FROMClause, out FROMEntityList, out joinEntityList);
            if (!questStatusDef.IsSuccess(status))
            {
                return(status);
            }
            int numItemEntities = FROMEntityList.Count + joinEntityList.Count;


            // Append lookup or type list Id's to result columns with lookups.
            // NOTE: Lookups and typeList are mutually exclusive.
            FilterItem filterItem = null;

            try {
                for (int idx = 0; idx < filter.FilterItemList.Count; idx += 1)
                {
                    filterItem = filter.FilterItemList[idx];

                    string       columnIdentifier = null;
                    FilterColumn filterColumn     = null;
                    status = GetResultsColumnIdentifier(filter, filterItem, numItemEntities, out columnIdentifier, out filterColumn);
                    if (!questStatusDef.IsSuccess(status))
                    {
                        return(status);
                    }
                    if (columnIdentifier == null)
                    {
                        return(new questStatus(Severity.Error, String.Format("ERROR: columnIdentifier is NULL for filterItem {0}  FilterId: {1}",
                                                                             filterItem.Id, filterItem.FilterId)));
                    }
                    if (filterColumn == null)
                    {
                        return(new questStatus(Severity.Error, String.Format("ERROR: filterColumn is NULL for filterItem {0}  FilterId: {1}",
                                                                             filterItem.Id, filterItem.FilterId)));
                    }
                    if (!string.IsNullOrEmpty(filterItem.Label))
                    {
                        resultsSet.ResultColumns[columnIdentifier].Name  = filterColumn.TablesetColumn.Name;
                        resultsSet.ResultColumns[columnIdentifier].Label = filterItem.Label;
                    }
                    if (filterItem.LookupId.HasValue)
                    {
                        resultsSet.ResultColumns[columnIdentifier].LookupId = filterItem.LookupId;
                    }
                    if (filterItem.TypeListId.HasValue)
                    {
                        resultsSet.ResultColumns[columnIdentifier].TypeListId = filterItem.TypeListId;
                    }
                    resultsSet.ResultColumns[columnIdentifier].bIsHidden = filterItem.bHidden;
                }
            }
            catch (System.Exception ex)
            {
                return(new questStatus(Severity.Error, String.Format("EXCEPTION: building filter results set with FilterItem {0}: {1}",
                                                                     filterItem.Id, ex.Message)));
            }
            return(new questStatus(Severity.Success));
        }