Example #1
0
        private void sinhvienMainForm_Load(object sender, EventArgs e)
        {
            //lopItems.Add(new Lop() {
            //    LopId = 1,
            //    TenLop = "cntt k37",
            //    GVCN = "A"
            //});
            //lopItems.Add(new Lop()
            //{
            //    LopId = 2,
            //    TenLop = "cntt k38",
            //    GVCN = "B"
            //});
            //lopItems.Add(new Lop()
            //{
            //    LopId = 3,
            //    TenLop = "cntt k39",
            //    GVCN = "C"
            //});
            var db = new SqlDatabase();
            lopItems = db.GetList<Lop>("select * from lop");

            //lopItems = DataExtensions.GetList<Lop>(db, "select * from Lop");

            lopBindingSource.DataSource = lopItems;
            sinhvienBindingSource.DataSource = data;
        }
Example #2
0
        protected override void DoGet()
        {
            chkDelFlag.Enabled = DbHelper.isAdmin(Page.User.Identity.Name);

            DbHelper.FillList(drpJobType, "Select * from Mst_JobType", "Name", "id");
            action = Request["Action"];
            id = Request["id"];

            hidId.Value = id;
            hidAction.Value = action;

            SqlDatabase db = new SqlDatabase();
            if (action == "Edit")
            {
                lblHeader.Text = "Thông Tin Chi Tiết " + title;
                btnRegister.Text = "Cập Nhật";
                btnCancel.Text = "Đóng";
                btnRegister.CommandName = "Edit";
                if (!IsPostBack)
                {
                    LoadData();
                }
            }
            else // Add new case
            {
                lblHeader.Text = "Thêm Mới " + title;
                btnRegister.Text = "Thêm Mới";
                btnRegister.CommandName = "Register";
                btnCancel.Text = "Đóng";
            }
        }
Example #3
0
 private static void Write(int operationId,int actionId, string information, string creator,int status)
 {
     string sql = string.Empty;
     StringBuilder sb = new StringBuilder();
     SqlDatabase db = new SqlDatabase(ICJSystem.Instance.ConnectionString1);
     try
     {
         Func.AddSqlString(sb, "INSERT INTO OperationLog");
         Func.AddSqlString(sb, "(");
         Func.AddSqlString(sb, "  [Date],");                
         Func.AddSqlString(sb, "  OperationId,");
         Func.AddSqlString(sb, "  ActionId,");
         Func.AddSqlString(sb, "  Information,");
         Func.AddSqlString(sb, "  [Status],");                
         Func.AddSqlString(sb, "  Creator");
         Func.AddSqlString(sb, ")VALUES");
         Func.AddSqlString(sb, "(");
         Func.AddSqlString(sb, "	'" + DateTime.Now.ToString("yyyyMMddHHmmss") + "',");                
         Func.AddSqlString(sb, "	" + operationId + ",");
         Func.AddSqlString(sb, "	" + actionId + ",");
         Func.AddSqlString(sb, "	'" + information + "',");
         Func.AddSqlString(sb, "	" + status + ",");                
         Func.AddSqlString(sb, "	'" + creator + "'");
         Func.AddSqlString(sb, ")");
         sql = sb.ToString();
         db.ExecuteNonQuery(sql);
     }
     catch (Exception ex)
     {
         ApplicationLog.WriteError(ex);
     }            
 }
 private static void InsertDefaultIfNull(BubbleGroup group)
 {
     lock (_lock)
     {
         if (group.Settings == null)
         {
             using (var db = new SqlDatabase<BubbleGroupSettings>(GetPath()))
             {
                 var settings = new BubbleGroupSettings
                 {
                     Mute = false,
                     Unread = true,
                     Guid = group.ID,
                     LastUnreadSetTime = 0,
                     ReadTimes = null,
                     ParticipantNicknames = null,
                     NotificationLed = DefaultNotificationLedColor,
                     VibrateOption = null,
                     VibrateOptionCustomPattern = null,
                     Ringtone = null,
                 };
                 db.Add(settings);
                 group.Settings = settings;
             }
         }
     }
 }        
Example #5
0
 public void CanGetConnectionWithoutCredentials()
 {
     SqlDatabase sqlDatabase = new SqlDatabase();
     sqlDatabase.ConfigurationName = "DbWithSqlServerAuthn";
     sqlDatabase.Initialize(new DatabaseConfigurationView(context));
     Assert.AreEqual("server=localhost;database=northwind;", sqlDatabase.GetConnectionStringWithoutCredentials());
 }
 public static void Load()
 {
     lock (_lock)
     {
         using (var db = new SqlDatabase<BubbleGroupSettings>(GetPath()))
         {
             var toRemoves = new List<BubbleGroupSettings>();
             foreach (var settings in db.Store.ToList())
             {
                 var bubbleGroup = BubbleGroupManager.Find(settings.Guid);
                 if (bubbleGroup == null)
                 {
                     toRemoves.Add(settings);
                 }
                 else
                 {
                     bubbleGroup.Settings = settings;
                 }
             }
             if (toRemoves.Any())
             {
                 foreach (var toRemove in toRemoves)
                 {
                     db.Remove(toRemove);
                 }
             }
         }
     }
 }
Example #7
0
        protected override void DoGet()
        {
            action = Request["Action"];
            id = Request["id"];

            hidId.Value = id;
            hidAction.Value = action;

            SqlDatabase db = new SqlDatabase();
            if (action == "Edit")
            {
                lblHeader.Text = "Thông Tin Chi Tiết " + title;
                btnRegister.Text = "Cập Nhật";
                btnCancel.Text = "Đóng";
                btnRegister.CommandName = "Edit";
                if (!IsPostBack)
                {
                    LoadData();
                }
            }
            else // Add new case
            {
                lblHeader.Text = "Thêm Mới " + title;
                btnRegister.Text = "Thêm Mới";
                btnRegister.CommandName = "Register";
                btnCancel.Text = "Đóng";
            }
        }
Example #8
0
        protected override void DoGet()
        {
            chkDelFlag.Enabled = DbHelper.isAdmin(Page.User.Identity.Name);

            action = Request["Action"];
            id = Request["id"];

            hidId.Value = id;
            hidAction.Value = action;
            hidJobType.Value = Func.ParseString(Request["JobType"]);

            DbHelper.FillList(drpPosition, "Select * from Mst_Position Where Jobtype = '"+ hidJobType.Value +"'", "Position", "id");
            DbHelper.FillListSearch(drpWorkingPlace, "Select WorkingPlaceId + '('+ Name +')' As Name, ID from BD_WorkingPlace Where JobTypeId = '" + hidJobType.Value + "' and BuildingId = '" + Func.ParseString(Session["__BUILDINGID__"]) + "' and DelFlag = 0", "Name", "id");

            SqlDatabase db = new SqlDatabase();
            if (action == "Edit")
            {
                lblHeader.Text = "Thông Tin Chi Tiết " + title;
                btnRegister.Text = "Cập Nhật";
                btnCancel.Text = "Đóng";
                btnRegister.CommandName = "Edit";
                txtStaffId.Enabled = false;
                if (!IsPostBack)
                {
                    LoadData();
                }
            }
            else // Add new case
            {
                lblHeader.Text = "Thêm Mới " + title;
                btnRegister.Text = "Thêm Mới";
                btnRegister.CommandName = "Register";
                btnCancel.Text = "Đóng";
            }
        }
Example #9
0
        protected override void DoGet()
        {
            action = Request["Action"];
            id = Request["id"];
            chkDelFlag.Enabled = DbHelper.isAdmin(Page.User.Identity.Name);

            txtCustomerId.Text = Request["CustomerId"];
            hidId.Value = id;
            hidAction.Value = action;
            txtId.Text = id;
            SqlDatabase db = new SqlDatabase();
            if (action == "Edit")
            {
                lblHeader.Text = "Thông Tin Chi Tiết " + title;
                btnRegister.Text = "Cập Nhật";
                btnCancel.Text = "Đóng";
                btnRegister.CommandName = "Edit";
                txtId.Enabled = false;
                if (!IsPostBack)
                {
                    LoadData();
                }
            }
            else // Add new case
            {
                lblHeader.Text = "Thêm Mới " + title;
                btnRegister.Text = "Thêm Mới";
                btnRegister.CommandName = "Register";
                btnCancel.Text = "Đóng";
            }
        }
 /// <summary>
 /// Override to specify how the trace entry should be logged.
 /// </summary>
 /// <param name="item">Trace entry</param>
 protected override void DoLog(TraceLogItem item)
 {
     using (var db = new SqlDatabase(_sqlConnectionOrName))
     {
         var logRecord = new TraceRecord
             {
                 // ReSharper disable PossibleInvalidOperationException
                 Timestamp = item.TimestampUtc.Value,
                 // ReSharper restore PossibleInvalidOperationException
                 Type = (int)item.Type,
                 OperationType = item.OperationType,
                 SessionId = item.SessionId,
                 BusinessTransactionId = item.BusinessTransactionId,
                 OperationInstanceId = item.OperationInstanceId,
                 TenantId = item.TenantId,
                 Message = item.Message,
                 DetailedMessage = item.DetailedMessage,
                 ServerName = item.ServerName,
                 // ReSharper disable PossibleInvalidOperationException
                 ThreadId = item.ThreadId.Value
                 // ReSharper restore PossibleInvalidOperationException
             };
         db.Insert(logRecord);
     }
 }
 private static void NotQueuedSanityCheckup()
 {
     lock (_dbLock)
     {
         using (var db = new SqlDatabase<NotQueuedEntry>(NotQueuedLocation))
         {
             const int secondsInWeek = 604800;
             var nowTime = Time.GetNowUnixTimestamp();
             var truncateTime = nowTime - secondsInWeek;
             var removing = false;
             var bubblesToTruncate = new List<NotQueuedEntry>();
             foreach (var possibleBubble in db.Store.Where(x => x.Time < truncateTime))
             {
                 if (!removing)
                 {
                     Utils.DebugPrint("Pruning not queued bubbles database. Some bubbles are too old!");
                 }
                 removing = true;
                 bubblesToTruncate.Add(possibleBubble);
             }
             foreach (var possibleBubble in bubblesToTruncate)
             {
                 db.Remove(possibleBubble);
             }
         }
     }
 }
Example #12
0
        protected override void DoGet()
        {
            chkDelFlag.Enabled = DbHelper.isAdmin(Page.User.Identity.Name);

            action = Request["Action"];
            txtBuildingId.Text = Request["Id"];

            hidAction.Value = action;

            SqlDatabase db = new SqlDatabase();
            if (action == "Edit")
            {
                lblHeader.Text = "Thông Tin Chi Tiết " + title;
                btnRegister.Text = "Cập Nhật";
                btnCancel.Text = "Đóng";
                btnRegister.CommandName = "Edit";
                if (!IsPostBack)
                {
                    LoadData();
                }
            }
            else // Add new case
            {
                //chkDelFlag.Checked = true;
                //lblHeader.Text = "Thêm Mới " + title;
                //btnRegister.Text = "Thêm Mới";
                //btnRegister.CommandName = "Register";
                //btnCancel.Text = "Đóng";
            }
        }
Example #13
0
        public void CanGetConnectionForStringWithNoCredentials()
        {
            DatabaseConfigurationView view = new DatabaseConfigurationView(TestConfigurationSource.CreateConfigurationSource());
            ConnectionStringSettings data = view.GetConnectionStringSettings("NewDatabase");
            SqlDatabase sqlDatabase = new SqlDatabase(data.ConnectionString);

            Assert.AreEqual(@"server=(local)\sqlexpress;database=northwind;integrated security=true;", sqlDatabase.ConnectionStringWithoutCredentials);
        }
        public void CanGetConnectionForStringWithNoCredentials()
        {
            DatabaseSyntheticConfigSettings settings = new DatabaseSyntheticConfigSettings(TestConfigurationSource.CreateConfigurationSource());
            ConnectionStringSettings data = settings.GetConnectionStringSettings("NewDatabase");
            SqlDatabase sqlDatabase = new SqlDatabase(data.ConnectionString);

            Assert.AreEqual(@"server=(localdb)\v11.0;database=northwind;integrated security=true;", sqlDatabase.ConnectionStringWithoutCredentials);
        }
Example #15
0
        public void CanGetConnectionWithoutCredentials()
        {
            DatabaseConfigurationView view = new DatabaseConfigurationView(TestConfigurationSource.CreateConfigurationSource());
            ConnectionStringSettings data = view.GetConnectionStringSettings("DbWithSqlServerAuthn");
            SqlDatabase sqlDatabase = new SqlDatabase(data.ConnectionString);

            Assert.AreEqual(@"server=(local)\sqlexpress;database=northwind;", sqlDatabase.ConnectionStringWithoutCredentials);
        }
Example #16
0
        public void CanGetConnectionForStringWithNoCredentials()
        {
            SqlDatabase sqlDatabase = new SqlDatabase();
            sqlDatabase.ConfigurationName = "NewDatabase";
            sqlDatabase.Initialize(new DatabaseConfigurationView(context));

            Assert.AreEqual("server=localhost;database=northwind;integrated security=true;", sqlDatabase.GetConnectionStringWithoutCredentials());
        }
        public void CanGetConnectionWithoutCredentials()
        {
            DatabaseSyntheticConfigSettings settings = new DatabaseSyntheticConfigSettings(TestConfigurationSource.CreateConfigurationSource());
            ConnectionStringSettings data = settings.GetConnectionStringSettings("DbWithSqlServerAuthn");
            SqlDatabase sqlDatabase = new SqlDatabase(data.ConnectionString);

            Assert.AreEqual(@"server=(localdb)\v11.0;database=northwind;", sqlDatabase.ConnectionStringWithoutCredentials);
        }
        public void InitializeExisting_WhenDatabaseDoesNotExist_ThrowsSisoDbException()
        {
            DbHelper.DropDatabase(LocalConstants.TempDbName);
            var connectionInfo = new SisoConnectionInfo(LocalConstants.ConnectionStringNameForTemp);

            var db = new SqlDatabase(connectionInfo);

            Assert.Throws<SisoDbException>(() => db.InitializeExisting());
        }
        public void CTor_ConnectionInfoWithDbName_ExtractsCorrectDbName()
        {
            var cnInfo = new SisoConnectionInfo(
                @"sisodb:provider=Sql2008||plain:Data Source=.\sqlexpress;Initial Catalog=DummyDb;Integrated Security=True");

            var db = new SqlDatabase(cnInfo);

            Assert.AreEqual("DummyDb", db.Name);
        }
        public void CTor_ConnectionInfoWithDbName_ServerConnectionInfoGainsNoDbName()
        {
            var cnInfo = new SisoConnectionInfo(
                @"sisodb:provider=Sql2008||plain:Data Source=.\sqlexpress;Initial Catalog=DummyDb;Integrated Security=True");

            var db = new SqlDatabase(cnInfo);

            Assert.AreEqual(@"Data Source=.\sqlexpress;Initial Catalog=;Integrated Security=True", db.ServerConnectionInfo.ConnectionString.PlainString);
        }
        public void Exists_WhenItExists_ReturnsTrue()
        {
            DbHelper.EnsureDbExists(LocalConstants.TempDbName);
            var connectionInfo = new SisoConnectionInfo(LocalConstants.ConnectionStringNameForTemp);

            var db = new SqlDatabase(connectionInfo);
            var dbExists = db.Exists();

            Assert.IsTrue(dbExists);
        }
        public void ForServerConnection_WhenServerExists_ConnectionIsAgainstMaster()
        {
            var connectionInfo = new SisoConnectionInfo(LocalConstants.ConnectionStringNameForTemp);
            var db = new SqlDatabase(connectionInfo);

            using (var dbClient = new SqlDbClient(db.ServerConnectionInfo, false))
            {
                Assert.AreEqual("master", dbClient.DbName);
            }
        }
 private static void Update(BubbleGroupSettings settings)
 {
     lock (_lock)
     {
         using (var db = new SqlDatabase<BubbleGroupSettings>(GetPath()))
         {
             db.Update(settings);
         }
     }
 }
        public void InitializeExisting_WhenDatabaseExists_CreatesSisoSysTables()
        {
            DbHelper.EnsureDbExists(LocalConstants.TempDbName);
            var connectionInfo = new SisoConnectionInfo(LocalConstants.ConnectionStringNameForTemp);

            var db = new SqlDatabase(connectionInfo);
            db.InitializeExisting();

            var identitiesTableExists = DbHelper.TableExists("SisoDbIdentities");
            Assert.IsTrue(identitiesTableExists);
        }
        public void ForDatabaseConnection_WhenDatabaseExists_ConnectionIsAgainstSpecifiedDb()
        {
            DbHelper.EnsureDbExists(LocalConstants.TempDbName);
            var connectionInfo = new SisoConnectionInfo(LocalConstants.ConnectionStringNameForTemp);
            var db = new SqlDatabase(connectionInfo);

            using (var dbClient = new SqlDbClient(db.ConnectionInfo, false))
            {
                Assert.AreEqual("SisoDb.IntegrationTests.Temp", dbClient.DbName);
            }
        }
Example #26
0
		public int Restore(
			DatabaseLogger logger,
			string connectionString,
			IEnumerable<DbMaintenanceSettings> databasesToRestore)
		{
			var sqlDatabase = new SqlDatabase(connectionString);

			Action<string, string> action = sqlDatabase.Restore;

			return Run(logger, databasesToRestore, action);
		}
        public void CreateIfNotExists_WhenNoDatabaseExists_DatabaseGetsCreated()
        {
            DbHelper.DropDatabase(LocalConstants.TempDbName);
            var connectionInfo = new SisoConnectionInfo(LocalConstants.ConnectionStringNameForTemp);

            var db = new SqlDatabase(connectionInfo);
            db.CreateIfNotExists();

            var dbExists = DbHelper.DatabaseExists(LocalConstants.TempDbName);
            Assert.IsTrue(dbExists);
        }
        public void DeleteIfExists_WhenDatabaseExists_DatabaseGetsDropped()
        {
            DbHelper.EnsureDbExists(LocalConstants.TempDbName);
            var connectionInfo = new SisoConnectionInfo(LocalConstants.ConnectionStringNameForTemp);

            var db = new SqlDatabase(connectionInfo);
            db.DeleteIfExists();

            var dbExists = db.Exists();
            Assert.IsFalse(dbExists);
        }
Example #29
0
		public int Restore(
			DatabaseLogger logger,
			string connectionString,
			IEnumerable<DbMaintenanceSettings> databasesToRestore,
			string restorePath)
		{
			var sqlDatabase = new SqlDatabase(connectionString);

			Action<string, string> action =
				(databaseName, backupPath) => sqlDatabase.Restore(databaseName, backupPath, restorePath);

			return Run(logger, databasesToRestore, action);
		}
Example #30
0
		public static Product ToDocumentDatabaseProducts(SqlDatabase.Product sqlProduct)
		{
			return new Product
			{
				id = sqlProduct.ProductID.ToString(),
				Name = sqlProduct.Name,
				Line = sqlProduct.ProductLine,
				Number = sqlProduct.ProductNumber,
				Model = ToModel(sqlProduct.ProductModel),
				Reviews = ToReviews(sqlProduct.ProductReviews),
				Subcategory = ToSubcategory(sqlProduct.ProductSubcategory)
			};
		}
Example #31
0
 /// <summary>
 /// Khởi tạo tham số
 /// </summary>
 /// <param name="TS"></param>
 /// <param name="DB"></param>
 /// Create by: dvthang:28.03.2018
 public void Init(DbTransaction TS, SqlDatabase DB)
 {
     this.DB = DB;
     this.TS = TS;
 }
Example #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Database"/> class.
 /// </summary>
 /// <param name="connectionString">The connection string.</param>
 internal Database(string connectionString)
 {
     this.database = new SqlDatabase(connectionString);
 }
Example #33
0
        protected void FilterSProcsButton_Click(object sender, System.EventArgs e)
        {
            SqlServer server = SqlServer.CurrentServer;

            try
            {
                server.Connect();
            }
            catch (System.Exception ex)
            {
                //Response.Redirect("Error.aspx?errorPassCode=" + 2002);
                Response.Redirect(String.Format("error.aspx?errormsg={0}&stacktrace={1}", Server.UrlEncode(ex.Message), Server.UrlEncode(ex.StackTrace)));
            }

            SqlDatabase database = SqlDatabase.CurrentDatabase(server);

            string databaseName = database.Name;

            SqlObjectType objectTypeFilter;

            switch (SProcTypeDropDownList.SelectedIndex)
            {
            case 0:
                objectTypeFilter = SqlObjectType.User;
                break;

            case 1:
                objectTypeFilter = SqlObjectType.User | SqlObjectType.System;
                break;

            default:
                throw new Exception("Invalid SProcType selected");
            }

            // Get stored procedure list
            AddNewSProcHyperLink.NavigateUrl = String.Format("createstoredprocedure.aspx?database={0}", Server.UrlEncode(Request["database"]));

            SqlStoredProcedureCollection sprocs = database.StoredProcedures;

            server.Disconnect();

            // Create DataSet from result
            DataSet ds = new DataSet();

            ds.Tables.Add();
            ds.Tables[0].Columns.Add("name");
            ds.Tables[0].Columns.Add("encodedname");
            ds.Tables[0].Columns.Add("owner");
            ds.Tables[0].Columns.Add("type");
            ds.Tables[0].Columns.Add("createdate");
            for (int i = 0; i < sprocs.Count; i++)
            {
                SqlStoredProcedure sproc = sprocs[i];

                // Only add objects that we want (system or user)
                if ((sproc.StoredProcedureType & objectTypeFilter) > 0)
                {
                    ds.Tables[0].Rows.Add(new object[] { Server.HtmlEncode(sproc.Name), Server.UrlEncode(sproc.Name), Server.HtmlEncode(sproc.Owner), Server.HtmlEncode(sproc.StoredProcedureType.ToString()), Server.HtmlEncode(sproc.CreateDate.ToString()) });
                }
            }

            // Show message if there are no tables, otherwise show datagrid
            if (ds.Tables[0].Rows.Count == 0)
            {
                SProcsDataGrid.Visible      = false;
                SProcTypeErrorLabel.Visible = true;
            }
            else
            {
                SProcTypeErrorLabel.Visible = false;
                SProcsDataGrid.Visible      = true;

                SProcsDataGrid.DataSource = ds;
                SProcsDataGrid.DataBind();
            }
        }
Example #34
0
        public static ActionStatus AddIssue(Issue issueDto)
        {
            // Create the Database object, using the default database service. The
            // default database service is determined through configuration.
            SqlDatabase db = new SqlDatabase(Config.ConnString);

            ActionStatus status = new ActionStatus();

            Int32 volumeIssueId;

            using (DbConnection connection = db.CreateConnection())
            {
                connection.Open();

                DbTransaction txn = null;

                try
                {
                    //Begin the transaction
                    txn = connection.BeginTransaction();

                    IssueInsertHelper issueHlpr = new IssueInsertHelper();

                    issueHlpr.InitCommand(db, issueDto);

                    volumeIssueId = issueHlpr.Execute(db, txn);

                    foreach (IssueDocument doc in issueDto.Documents)
                    {
                        //Load the data in a stream
                        doc.LoadData();

                        IssueDocInsertHelper issueDocHlpr = new IssueDocInsertHelper();

                        issueDocHlpr.InitCommand(db, volumeIssueId, doc);

                        issueDocHlpr.Execute(db, txn);
                    }

                    status.IsSuccessful = true;

                    // Commit the transaction.
                    txn.Commit();
                }
                catch (SqlException sqlEx)
                {
                    // Roll back the transaction.
                    txn.Rollback();

                    Console.WriteLine(sqlEx.ToString());

                    throw new DataException("An exception occured adding an issue into the database.", sqlEx);
                }
                catch (IOException ioEx)
                {
                    // Roll back the transaction.
                    txn.Rollback();

                    Console.WriteLine(ioEx.ToString());

                    throw new DataException("An exception occured trying to read document data.", ioEx);
                }
                finally
                {
                    connection.Close();
                }
            }

            return(status);
        }
Example #35
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            SqlServer server = SqlServer.CurrentServer;

            server.Connect();

            SqlDatabase database = SqlDatabase.CurrentDatabase(server);

            if (!IsPostBack)
            {
                DataLossWarningLabel.Visible = false;

                // If column isn't specified in request, that means we're adding a new column, not editing an existing one
                if (Request["column"] == null || Request["column"].Length == 0)
                {
                    // Set update button text to "Add" instead of "Update"
                    UpdateButton.Text = "Add";

                    // Create new unique column name
                    string columnName = "";

                    SqlTable table = database.Tables[Request["table"]];
                    if (table == null)
                    {
                        // If table doesn't exist (e.g. new table), set default column name
                        columnName = "Column1";
                    }
                    else
                    {
                        // Come up with non-existent name ColumnXX
                        int i = 1;
                        do
                        {
                            columnName = "Column" + i;
                            i++;
                        } while (table.Columns[columnName] != null);
                    }


                    // Initialize column editor with default values
                    PrimaryKeyCheckbox.Checked         = false;
                    ColumnNameTextbox.Text             = columnName;
                    DataTypeDropdownlist.SelectedIndex = DataTypeDropdownlist.Items.IndexOf(new ListItem("char"));
                    LengthTextbox.Text            = "10";
                    AllowNullCheckbox.Checked     = true;
                    DefaultValueTextbox.Text      = "";
                    PrecisionTextbox.Text         = "0";
                    ScaleTextbox.Text             = "0";
                    IdentityCheckBox.Checked      = false;
                    IdentitySeedTextbox.Text      = "1";
                    IdentityIncrementTextbox.Text = "1";
                    IsRowGuidCheckBox.Checked     = false;
                }
                else
                {
                    // Set update button text to "Update" instead of "Add"
                    UpdateButton.Text = "Update";

                    // Load column from table
                    SqlTable table = database.Tables[Request["table"]];
                    if (table == null)
                    {
                        server.Disconnect();

                        // Table doesn't exist - break out and go to error page
                        Response.Redirect(String.Format("error.aspx?error={0}", 1002));
                        return;
                    }


                    // Select column from table
                    SqlColumn column = table.Columns[Request["column"]];
                    if (column == null)
                    {
                        server.Disconnect();

                        // Column doesn't exist - break out and go to error page
                        Response.Redirect(String.Format("error.aspx?error={0}", 1003));
                        return;
                    }

                    SqlColumnInformation columnInfo = column.ColumnInformation;

                    // Initialize column editor
                    PrimaryKeyCheckbox.Checked         = columnInfo.Key;
                    ColumnNameTextbox.Text             = columnInfo.Name;
                    DataTypeDropdownlist.SelectedIndex = DataTypeDropdownlist.Items.IndexOf(new ListItem(columnInfo.DataType));
                    LengthTextbox.Text            = Convert.ToString(columnInfo.Size);
                    AllowNullCheckbox.Checked     = columnInfo.Nulls;
                    DefaultValueTextbox.Text      = columnInfo.DefaultValue;
                    PrecisionTextbox.Text         = Convert.ToString(columnInfo.Precision);
                    ScaleTextbox.Text             = Convert.ToString(columnInfo.Scale);
                    IdentityCheckBox.Checked      = columnInfo.Identity;
                    IdentitySeedTextbox.Text      = Convert.ToString(columnInfo.IdentitySeed);
                    IdentityIncrementTextbox.Text = Convert.ToString(columnInfo.IdentityIncrement);
                    IsRowGuidCheckBox.Checked     = columnInfo.IsRowGuid;

                    // Since we are editing an existing column, the table will be recreated,
                    // so we must warn about data loss
                    DataLossWarningLabel.Visible = true;
                }
            }

            server.Disconnect();
        }
 protected void Page_Load(object sender, System.EventArgs e)
 {
     OrwellSqlDataSource.ConnectionString = SqlDatabase.GetConnectionString();
 }
Example #37
0
        /// <summary>
        ///     Gets rows from the datasource based on the UQ__Specchietto__182C9B23 index.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_sgutAssociationSpecchiettoID"></param>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">out parameter to get total records for query</param>
        /// <returns>Returns an instance of the <see cref="GenTest.Entities.Specchietto"/> class.</returns>
        /// <remarks></remarks>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
        public override GenTest.Entities.Specchietto GetBySgutAssociationSpecchiettoID(TransactionManager transactionManager, System.Int32?_sgutAssociationSpecchiettoID, int start, int pageLength, out int count)
        {
            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Specchietto_GetBySgutAssociationSpecchiettoID", _useStoredProcedure);

            database.AddInParameter(commandWrapper, "@SgutAssociationSpecchiettoID", DbType.Int32, _sgutAssociationSpecchiettoID);

            IDataReader         reader = null;
            TList <Specchietto> tmp    = new TList <Specchietto>();

            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "GetBySgutAssociationSpecchiettoID", tmp));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                //Create collection and fill
                Fill(reader, tmp, start, pageLength);
                count = -1;
                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "GetBySgutAssociationSpecchiettoID", tmp));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }

            if (tmp.Count == 1)
            {
                return(tmp[0]);
            }
            else if (tmp.Count == 0)
            {
                return(null);
            }
            else
            {
                throw new DataException("Cannot find the unique instance of the class.");
            }

            //return rows;
        }
Example #38
0
        public static void ProcessRequest(HttpRequest request, HttpResponse response, HttpSessionState session, SqlConnection conn, string sharedSecret)
        {
            response.ContentType = "application/octet-stream";

            try
            {
                switch (request.QueryString["cmd"])
                {
                case "challenge":
                    byte[] buffer = new byte[32];
                    _rnd.GetBytes(buffer);

                    session["challenge"] = buffer;
                    response.OutputStream.Write(new byte[4], 0, 4);
                    response.OutputStream.Write(buffer, 0, 32);
                    break;

                case "login":
                    byte[] challenge = session["challenge"] as byte[];
                    if (challenge == null)
                    {
                        throw new WebDatabaseException("Challenge not initialized.");
                    }

                    session["challenge"] = null;

                    string authCode = request.QueryString["code"];
                    if (authCode == null)
                    {
                        throw new WebDatabaseException("Authentication code missing.");
                    }

                    using (HMAC hmac = new HMACSHA256(Encoding.UTF8.GetBytes(sharedSecret)))
                    {
                        string computedAuthCode = BitConverter.ToString(hmac.ComputeHash(challenge)).Replace("-", "").ToLower();
                        if (authCode != computedAuthCode)
                        {
                            throw new WebDatabaseException("Invalid authentication code.");
                        }
                    }

                    session["token"] = request.ServerVariables["REMOTE_ADDR"];
                    response.OutputStream.Write(new byte[4], 0, 4);
                    break;

                case "logout":
                    session.Abandon();
                    response.OutputStream.Write(new byte[4], 0, 4);
                    break;

                default:
                    using (SqlDatabase DB = new SqlDatabase(conn))
                    {
                        WebDatabase.ExecuteQuery(DB, request, response, session);
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                BinaryWriter bW = new BinaryWriter(response.OutputStream);

                //sql error code
                SqlException sqlEx = ex as SqlException;

                if (sqlEx == null)
                {
                    bW.Write(-2);
                }
                else
                {
                    bW.Write(sqlEx.ErrorCode);
                }

                //error message
                string errorMessage = ex.Message;
                bW.Write(errorMessage.Length);
                bW.Write(System.Text.Encoding.UTF8.GetBytes(errorMessage));

                //stack trace message
                string remoteStackTrace = ex.ToString();
                bW.Write(remoteStackTrace.Length);
                bW.Write(Encoding.UTF8.GetBytes(remoteStackTrace));

                bW.Flush();
            }
        }
Example #39
0
        private static void ExecuteQuery(SqlDatabase DB, HttpRequest request, HttpResponse response, HttpSessionState session)
        {
            #region check token

            if ((string)session["token"] != request.ServerVariables["REMOTE_ADDR"])
            {
                throw new WebDatabaseException("Access denied.");
            }

            #endregion

            #region prepare sql command

            SqlCommand cmd = new SqlCommand(request.Form["q"]);

            foreach (string key in request.Form.AllKeys)
            {
                if (key != "q")
                {
                    using (MemoryStream mS = new MemoryStream(Convert.FromBase64String(request.Form[key])))
                    {
                        WebDbDataItem parameter = new WebDbDataItem(mS);

                        if (parameter.Value == null)
                        {
                            cmd.Parameters.Add(key, parameter.Type).Value = DBNull.Value;
                        }
                        else
                        {
                            cmd.Parameters.Add(key, parameter.Type).Value = parameter.Value;
                        }
                    }
                }
            }

            #endregion

            #region execute command

            if (cmd.CommandText.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
            {
                #region TableQuery

                DataTable DT = DB.TableQuery(cmd);

                //write output
                BinaryWriter bW = new BinaryWriter(response.OutputStream);

                //error code
                bW.Write(0);

                //write column names
                bW.Write(Convert.ToByte(DT.Columns.Count));

                foreach (DataColumn col in DT.Columns)
                {
                    bW.Write(Convert.ToByte(col.ColumnName.Length));
                    bW.Write(Encoding.UTF8.GetBytes(col.ColumnName));
                }

                //write row data
                bW.Write(DT.Rows.Count);

                foreach (DataRow DR in DT.Rows)
                {
                    for (int iCol = 0; iCol < DT.Columns.Count; iCol++)
                    {
                        object value;

                        if (DR.IsNull(iCol))
                        {
                            value = null;
                        }
                        else
                        {
                            value = DR[iCol];
                        }

                        Type          type = DR[iCol].GetType();
                        WebDbDataItem dbItem;

                        if (type == typeof(Int64))
                        {
                            dbItem = new WebDbDataItem(SqlDbType.BigInt, value);
                        }

                        else if (type == typeof(byte[]))
                        {
                            dbItem = new WebDbDataItem(SqlDbType.VarBinary, value);
                        }

                        else if (type == typeof(string))
                        {
                            dbItem = new WebDbDataItem(SqlDbType.NVarChar, value);
                        }

                        else if (type == typeof(DateTime))
                        {
                            dbItem = new WebDbDataItem(SqlDbType.DateTime, value);
                        }

                        else if (type == typeof(double))
                        {
                            dbItem = new WebDbDataItem(SqlDbType.Float, value);
                        }

                        else if (type == typeof(int))
                        {
                            dbItem = new WebDbDataItem(SqlDbType.Int, value);
                        }

                        else if (type == typeof(float))
                        {
                            dbItem = new WebDbDataItem(SqlDbType.Real, value);
                        }

                        else if (type == typeof(Int16))
                        {
                            dbItem = new WebDbDataItem(SqlDbType.SmallInt, value);
                        }

                        else if (type == typeof(byte))
                        {
                            dbItem = new WebDbDataItem(SqlDbType.TinyInt, value);
                        }

                        else if (type == typeof(DBNull))
                        {
                            dbItem = new WebDbDataItem(SqlDbType.TinyInt, null);
                        }

                        else
                        {
                            throw new Exception("Data type '" + type.ToString() + "' not supported.");
                        }

                        dbItem.WriteTo(bW);
                    }
                }

                bW.Flush();

                #endregion
            }
            else
            {
                #region Command

                int rowsAffected = DB.Command(cmd);

                //write output
                BinaryWriter bW = new BinaryWriter(response.OutputStream);
                bW.Write(0); //error code
                bW.Write(rowsAffected);
                bW.Flush();

                #endregion
            }

            #endregion
        }
Example #40
0
        public void InsertMateriaPrimaHistorico(string EmpresaID, int UsuarioID, DataTable DtMateriaPrimaHistoricoDetalle, DataTable DtProductosBatch)
        {
            SqlDatabase SqlClient = new SqlDatabase(connectionString);

            DbConnection tCnn;

            tCnn = SqlClient.CreateConnection();
            tCnn.Open();

            DbTransaction tran = tCnn.BeginTransaction();

            Int32 MateriaPrimaHistoricoID;

            try
            {
                DbCommand SqlCommandAccess = SqlClient.GetStoredProcCommand("[Produccion].[Usp_InsertMateriaPrimaHistorico]");
                SqlClient.AddInParameter(SqlCommandAccess, "@EmpresaID", SqlDbType.Char, EmpresaID);
                SqlClient.AddInParameter(SqlCommandAccess, "@UsuarioID", SqlDbType.Int, UsuarioID);
                MateriaPrimaHistoricoID = Convert.ToInt32(SqlClient.ExecuteScalar(SqlCommandAccess, tran));

                //crear nueva tabla y se agrega el codigo obntenido anteriormente
                DataTable DtHistoricoInsert = new DataTable();
                DtHistoricoInsert.Columns.Add("MateriaPrimaHistoricoID", typeof(Int32)).DefaultValue = MateriaPrimaHistoricoID;
                DtHistoricoInsert.Columns.Add("ProductoID", typeof(string));
                DtHistoricoInsert.Columns.Add("ProductoIDMateria", typeof(string));
                DtHistoricoInsert.Columns.Add("AlmacenMateria", typeof(string));
                DtHistoricoInsert.Columns.Add("Cantidad", typeof(decimal));


                foreach (DataRow DRT in DtMateriaPrimaHistoricoDetalle.Rows)
                {
                    DataRow DRH = DtHistoricoInsert.NewRow();
                    DRH["ProductoID"]        = DRT["ProductoID"];
                    DRH["ProductoIDMateria"] = DRT["ProductoIDMateria"];
                    DRH["AlmacenMateria"]    = DRT["AlmacenMateria"];
                    DRH["Cantidad"]          = DRT["Cantidad"];
                    DtHistoricoInsert.Rows.Add(DRH);
                }

                //crear nueva tabla y se agrega el codigo obntenido anteriormente
                DataTable DtProductosBatch2 = new DataTable();
                DtProductosBatch2.Columns.Add("MateriaPrimaHistoricoID", typeof(Int32)).DefaultValue = MateriaPrimaHistoricoID;
                DtProductosBatch2.Columns.Add("ProductoID", typeof(string));
                DtProductosBatch2.Columns.Add("Batch", typeof(decimal));


                foreach (DataRow DRT in DtProductosBatch.Rows)
                {
                    DataRow DRH = DtProductosBatch2.NewRow();
                    DRH["ProductoID"] = DRT["ProductoID"];
                    DRH["Batch"]      = DRT["Batch"];
                    DtProductosBatch2.Rows.Add(DRH);
                }

                //crear tabla y insertarlo en xml
                DtHistoricoInsert.TableName = "MateriaPrimaHistoricoDetalle";
                string    xml = new BaseFunctions().GetXML(DtHistoricoInsert).Replace("NewDataSet", "DocumentElement");
                DbCommand SqlCommandDetalle = SqlClient.GetStoredProcCommand("[Produccion].[Usp_InsertXMLMateriaPrimaHistoricoDetalle]");
                SqlClient.AddInParameter(SqlCommandDetalle, "@XML", SqlDbType.Xml, xml);
                SqlClient.AddInParameter(SqlCommandDetalle, "@UsuarioID", SqlDbType.Int, UsuarioID);
                SqlClient.ExecuteNonQuery(SqlCommandDetalle, tran);
                SqlCommandDetalle.Dispose();

                //crear tabla y insertarlo en xml
                DtProductosBatch2.TableName = "MateriasPrimasFormulados";
                string    xml2 = new BaseFunctions().GetXML(DtProductosBatch2).Replace("NewDataSet", "DocumentElement");
                DbCommand SqlCommandDetalle2 = SqlClient.GetStoredProcCommand("[Produccion].[Usp_InsertXMLMateriasPrimasFormulados]");
                SqlClient.AddInParameter(SqlCommandDetalle2, "@XML", SqlDbType.Xml, xml2);
                SqlClient.AddInParameter(SqlCommandDetalle2, "@UsuarioID", SqlDbType.Int, UsuarioID);
                SqlClient.ExecuteNonQuery(SqlCommandDetalle2, tran);
                SqlCommandDetalle2.Dispose();

                tran.Commit();
                tCnn.Close();
                tCnn.Dispose();
                SqlCommandAccess.Dispose();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                throw new Exception(ex.Message);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="LetterTemplateRepository"/> class.
 /// </summary>
 /// <param name="connectionString">The connection string.</param>
 public PaymentResultRepository(string connectionString)
 {
     _databaseObj = new SqlDatabase(connectionString);
 }
Example #42
0
        /// <summary>
        ///     Gets rows from the datasource based on the PK__Product__B40CC6CD0AD2A005 index.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_productId"></param>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">out parameter to get total records for query.</param>
        /// <returns>Returns an instance of the <see cref="PetShop.Business.Product"/> class.</returns>
        /// <remarks></remarks>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
        public override PetShop.Business.Product GetByProductId(TransactionManager transactionManager, string _productId, int start, int pageLength, out int count)
        {
            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Product_GetByProductId", _useStoredProcedure);

            database.AddInParameter(commandWrapper, "@ProductId", DbType.AnsiString, _productId);

            IDataReader     reader = null;
            TList <Product> tmp    = new TList <Product>();

            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "GetByProductId", tmp));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                //Create collection and fill
                Fill(reader, tmp, start, pageLength);
                count = -1;
                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "GetByProductId", tmp));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }

            if (tmp.Count == 1)
            {
                return(tmp[0]);
            }
            else if (tmp.Count == 0)
            {
                return(null);
            }
            else
            {
                throw new DataException("Cannot find the unique instance of the class.");
            }

            //return rows;
        }
        /// <summary>
        ///     Gets rows from the datasource based on the PK_tblModePayment index.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_pmtMode"></param>
        /// <param name="_forex"></param>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">out parameter to get total records for query.</param>
        /// <returns>Returns an instance of the <see cref="LibraryManagement.Domain.ModePayment"/> class.</returns>
        /// <remarks></remarks>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
        public override LibraryManagement.Domain.ModePayment GetByPmtModeForex(TransactionManager transactionManager, System.String _pmtMode, System.String _forex, int start, int pageLength, out int count)
        {
            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.tblModePayment_GetByPmtModeForex", _useStoredProcedure);

            database.AddInParameter(commandWrapper, "@PmtMode", DbType.StringFixedLength, _pmtMode);
            database.AddInParameter(commandWrapper, "@Forex", DbType.StringFixedLength, _forex);

            IDataReader         reader = null;
            TList <ModePayment> tmp    = new TList <ModePayment>();

            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "GetByPmtModeForex", tmp));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                //Create collection and fill
                Fill(reader, tmp, start, pageLength);
                count = -1;
                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "GetByPmtModeForex", tmp));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }

            if (tmp.Count == 1)
            {
                return(tmp[0]);
            }
            else if (tmp.Count == 0)
            {
                return(null);
            }
            else
            {
                throw new DataException("Cannot find the unique instance of the class.");
            }

            //return rows;
        }
        public override TList <ContractNexus> Find(TransactionManager transactionManager, string whereClause, int start, int pageLength, out int count)
        {
            count = -1;
            if (whereClause.IndexOf(";") > -1)
            {
                return(new TList <ContractNexus>());
            }
            SqlDatabase database = new SqlDatabase(this._connectionString);
            DbCommand   command  = StoredProcedureProvider.GetCommandWrapper(database, "dbo.ContractNexus_Find", this._useStoredProcedure);
            bool        flag     = false;

            if (whereClause.IndexOf(" OR ") > 0)
            {
                flag = true;
            }
            database.AddInParameter(command, "@SearchUsingOR", DbType.Boolean, flag);
            database.AddInParameter(command, "@ContractNexusCode", DbType.AnsiString, DBNull.Value);
            database.AddInParameter(command, "@ContractCode", DbType.AnsiString, DBNull.Value);
            database.AddInParameter(command, "@ContractChangeCode", DbType.AnsiString, DBNull.Value);
            database.AddInParameter(command, "@Code", DbType.AnsiString, DBNull.Value);
            database.AddInParameter(command, "@Type", DbType.AnsiString, DBNull.Value);
            database.AddInParameter(command, "@Name", DbType.AnsiString, DBNull.Value);
            database.AddInParameter(command, "@ID", DbType.AnsiString, DBNull.Value);
            database.AddInParameter(command, "@Person", DbType.AnsiString, DBNull.Value);
            database.AddInParameter(command, "@Date", DbType.DateTime, DBNull.Value);
            database.AddInParameter(command, "@Path", DbType.AnsiString, DBNull.Value);
            database.AddInParameter(command, "@Money", DbType.Decimal, DBNull.Value);
            whereClause = whereClause.Replace(" AND ", "|").Replace(" OR ", "|");
            string[] textArray = whereClause.ToLower().Split(new char[] { '|' });
            char[]   trimChars = new char[] { '=' };
            char[]   chArray2  = new char[] { '\'' };
            foreach (string text in textArray)
            {
                if (text.Trim().StartsWith("contractnexuscode ") || text.Trim().StartsWith("contractnexuscode="))
                {
                    database.SetParameterValue(command, "@ContractNexusCode", text.Replace("contractnexuscode", "").Trim().TrimStart(trimChars).Trim().Trim(chArray2));
                }
                else if (text.Trim().StartsWith("contractcode ") || text.Trim().StartsWith("contractcode="))
                {
                    database.SetParameterValue(command, "@ContractCode", text.Replace("contractcode", "").Trim().TrimStart(trimChars).Trim().Trim(chArray2));
                }
                else if (text.Trim().StartsWith("contractchangecode ") || text.Trim().StartsWith("contractchangecode="))
                {
                    database.SetParameterValue(command, "@ContractChangeCode", text.Replace("contractchangecode", "").Trim().TrimStart(trimChars).Trim().Trim(chArray2));
                }
                else if (text.Trim().StartsWith("code ") || text.Trim().StartsWith("code="))
                {
                    database.SetParameterValue(command, "@Code", text.Replace("code", "").Trim().TrimStart(trimChars).Trim().Trim(chArray2));
                }
                else if (text.Trim().StartsWith("type ") || text.Trim().StartsWith("type="))
                {
                    database.SetParameterValue(command, "@Type", text.Replace("type", "").Trim().TrimStart(trimChars).Trim().Trim(chArray2));
                }
                else if (text.Trim().StartsWith("name ") || text.Trim().StartsWith("name="))
                {
                    database.SetParameterValue(command, "@Name", text.Replace("name", "").Trim().TrimStart(trimChars).Trim().Trim(chArray2));
                }
                else if (text.Trim().StartsWith("id ") || text.Trim().StartsWith("id="))
                {
                    database.SetParameterValue(command, "@ID", text.Replace("id", "").Trim().TrimStart(trimChars).Trim().Trim(chArray2));
                }
                else if (text.Trim().StartsWith("person ") || text.Trim().StartsWith("person="))
                {
                    database.SetParameterValue(command, "@Person", text.Replace("person", "").Trim().TrimStart(trimChars).Trim().Trim(chArray2));
                }
                else if (text.Trim().StartsWith("date ") || text.Trim().StartsWith("date="))
                {
                    database.SetParameterValue(command, "@Date", text.Replace("date", "").Trim().TrimStart(trimChars).Trim().Trim(chArray2));
                }
                else if (text.Trim().StartsWith("path ") || text.Trim().StartsWith("path="))
                {
                    database.SetParameterValue(command, "@Path", text.Replace("path", "").Trim().TrimStart(trimChars).Trim().Trim(chArray2));
                }
                else
                {
                    if (!text.Trim().StartsWith("money ") && !text.Trim().StartsWith("money="))
                    {
                        throw new ArgumentException("Unable to use this part of the where clause in this version of Find: " + text);
                    }
                    database.SetParameterValue(command, "@Money", text.Replace("money", "").Trim().TrimStart(trimChars).Trim().Trim(chArray2));
                }
            }
            IDataReader           reader = null;
            TList <ContractNexus> rows   = new TList <ContractNexus>();

            try
            {
                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, command);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, command);
                }
                ContractNexusProviderBaseCore.Fill(reader, rows, start, pageLength);
                if (reader.NextResult() && reader.Read())
                {
                    count = reader.GetInt32(0);
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return(rows);
        }
Example #45
0
 public TermRepository(SqlDatabase db, DbTransaction ts) : base(db, ts)
 {
 }
Example #46
0
 public ProjectData()
 {
     sqlDatabase = new SqlDatabase(GetConnectionString());
 }
Example #47
0
        protected void ApplyButton_Click(object sender, System.EventArgs e)
        {
            ErrorLabel.Visible = false;

            SqlServer server = SqlServer.CurrentServer;

            try
            {
                server.Connect();
            }
            catch (System.Exception ex)
            {
                //Response.Redirect("Error.aspx?errorPassCode=" + 2002);
                Response.Redirect(String.Format("error.aspx?errormsg={0}&stacktrace={1}", Server.UrlEncode(ex.Message), Server.UrlEncode(ex.StackTrace)));
            }

            SqlDatabase database = SqlDatabase.CurrentDatabase(server);

            // Grab data from the form
            SqlDatabaseProperties props = null;

            SqlFileProperties dataFileProperties = null;
            SqlFileProperties logFileProperties  = null;

            try
            {
                dataFileProperties = DataFileProperties.Properties;
            }
            catch (Exception ex)
            {
                ErrorLabel.Visible = true;
                ErrorLabel.Text    = "Error reading data file properties: " + Server.HtmlEncode(ex.Message).Replace("\n", "<br>") + "<br><br>";
                return;
            }

            try
            {
                logFileProperties = LogFileProperties.Properties;
            }
            catch (Exception ex)
            {
                ErrorLabel.Visible = true;
                ErrorLabel.Text    = "Error reading log file properties: " + Server.HtmlEncode(ex.Message).Replace("\n", "<br>") + "<br><br>";
                return;
            }

            props = new SqlDatabaseProperties(dataFileProperties, logFileProperties);
            SqlDatabaseProperties origProps = database.GetDatabaseProperties();

            // First validate input ourselves
            ArrayList errorList = new ArrayList();

            if (props.DataFile.FileGrowth < 0)
            {
                errorList.Add("Data file growth must be positive");
            }

            if (props.DataFile.MaximumSize < -1)
            {
                errorList.Add("Data file maximum size must be positive");
            }

            if (props.LogFile.FileGrowth < 0)
            {
                errorList.Add("Log file growth must be positive");
            }

            if (props.LogFile.MaximumSize < -1)
            {
                errorList.Add("Log file maximum size must be positive");
            }

            if (props.DataFile.MaximumSize != -1 && origProps.Size > props.DataFile.MaximumSize)
            {
                errorList.Add("Maximum file growth must be greater than or equal to the current database size");
            }

            if (errorList.Count > 0)
            {
                ErrorLabel.Visible = true;

                ErrorLabel.Text = "The following error(s) occured:<br><ul>";
                for (int i = 0; i < errorList.Count; i++)
                {
                    ErrorLabel.Text += String.Format("<li>{0}</li>", (string)errorList[i]);
                }
                ErrorLabel.Text += "</ul>";

                return;
            }

            // Try to set properties
            try
            {
                database.SetDatabaseProperties(props);
            }
            catch (Exception ex)
            {
                // Show error message and quit
                server.Disconnect();

                ErrorLabel.Text = "The following error occured:<br>" + Server.HtmlEncode(ex.Message).Replace("\n", "<br>") + "<br><br>";
                return;
            }

            // Only reload data if there were no errors
            // Get database properties and fill in their info
            props = database.GetDatabaseProperties();

            DataFileProperties.Properties = props.DataFile;
            LogFileProperties.Properties  = props.LogFile;

            server.Disconnect();
        }
Example #48
0
        public void Handle()
        {
            var selectedText = _input.ProcedureName;

            if (string.IsNullOrWhiteSpace(selectedText))
            {
                CreateNewSqlFile(Environment.NewLine, "Temp Sql File");
                return;
            }

            selectedText = ProcedureTextUtility.ClearProcedureText(selectedText);

            string query = null;

            var dbItemNameParser = DbItemNameInfoParser.Parse(selectedText);

            var procedureName = dbItemNameParser.Name;
            var schemaName    = dbItemNameParser.SchemaName;
            var databaseName  = dbItemNameParser.DatabaseName;

            var foundCount = 0;

            foreach (var info in DatabaseConnectionStrings.Connections)
            {
                if (databaseName != null && info.DatabaseName != databaseName)
                {
                    continue;
                }

                Result.ProcedureContainerDatabaseConnectionInfo = info;

                var dev  = new SqlDatabase(info.ConnectionStringDev);
                var prep = new SqlDatabase(info.ConnectionStringPrep);

                using (dev)
                {
                    using (prep)
                    {
                        string devVersion  = null;
                        string prepVersion = null;
                        var    found       = false;

                        var fileName = info.DatabaseName + "." + selectedText;

                        query = "SELECT sm.definition,SCHEMA_NAME(O.schema_id) AS SchemaName " +
                                "  from sys.sql_modules sm WITH(NOLOCK) INNER JOIN " +
                                "       sys.objects o WITH(NOLOCK) ON sm.object_id = o.object_id " +
                                " where o.name = " + " '" + procedureName + "' AND SCHEMA_NAME(O.schema_id)= '" + schemaName + "'";

                        dev.CommandText = query;
                        var dr = dev.ExecuteReader();
                        while (dr.Read())
                        {
                            devVersion = dr.GetString(0);
                            found      = true;
                            foundCount++;
                            break;
                        }
                        dr.Close();

                        prep.CommandText = query;
                        dr = prep.ExecuteReader();
                        while (dr.Read())
                        {
                            prepVersion = dr.GetString(0);
                            found       = true;
                            foundCount++;
                            break;
                        }

                        dr.Close();

                        // maybe table information was requested.
                        if (!found)
                        {
                            if (prep.IsTable(procedureName, schemaName))
                            {
                                prepVersion = sp_Help(prep, procedureName, schemaName);
                                found       = true;
                                foundCount++;
                            }

                            if (dev.IsTable(procedureName, schemaName))
                            {
                                devVersion = sp_Help(dev, procedureName, schemaName);
                                found      = true;
                                foundCount++;
                            }
                        }

                        if (found)
                        {
                            var isEqual = Comparer.Compare(devVersion, prepVersion);
                            if (isEqual)
                            {
                                CreateNewSqlFile(devVersion, fileName);
                            }
                            else
                            {
                                if (devVersion != null)
                                {
                                    CreateNewSqlFile(devVersion, "DEV - " + fileName);
                                }
                                if (prepVersion != null)
                                {
                                    CreateNewSqlFile(prepVersion, "PREP - " + fileName);
                                }
                            }

                            // do not search in other databases.
                            return;
                        }
                    }
                }
            }

            if (foundCount == 0)
            {
                Result.ErrorMessage = "Sp bulunamadı.";
            }
        }
Example #49
0
        protected void UpdateButton_Click(object sender, System.EventArgs e)
        {
            if (!IsValid)
            {
                return;
            }

            SqlServer server = SqlServer.CurrentServer;

            server.Connect();

            SqlDatabase database = SqlDatabase.CurrentDatabase(server);

            // Parse user input and stick it into ColumnInfo
            SqlColumnInformation columnInfo = new SqlColumnInformation();

            columnInfo.Key      = PrimaryKeyCheckbox.Checked;
            columnInfo.Name     = ColumnNameTextbox.Text;
            columnInfo.DataType = DataTypeDropdownlist.SelectedItem.Text;

            try {
                columnInfo.Size = Convert.ToInt32(LengthTextbox.Text);
            }
            catch {
                // Show error and quit
                ErrorUpdatingColumnLabel.Visible = true;
                ErrorUpdatingColumnLabel.Text    = "Invalid input: Size must be an integer";
                return;
            }

            columnInfo.Nulls        = AllowNullCheckbox.Checked;
            columnInfo.DefaultValue = DefaultValueTextbox.Text;

            try {
                columnInfo.Precision = Convert.ToInt32(PrecisionTextbox.Text);
            }
            catch {
                // Show error and quit
                ErrorUpdatingColumnLabel.Visible = true;
                ErrorUpdatingColumnLabel.Text    = "Invalid input: Precision must be an integer";
                return;
            }

            try {
                columnInfo.Scale = Convert.ToInt32(ScaleTextbox.Text);
            }
            catch {
                // Show error and quit
                ErrorUpdatingColumnLabel.Visible = true;
                ErrorUpdatingColumnLabel.Text    = "Invalid input: Scale must be an integer";
                return;
            }

            columnInfo.Identity = IdentityCheckBox.Checked;

            try {
                columnInfo.IdentitySeed = Convert.ToInt32(IdentitySeedTextbox.Text);
            }
            catch {
                // Show error and quit
                ErrorUpdatingColumnLabel.Visible = true;
                ErrorUpdatingColumnLabel.Text    = "Invalid input: Identity seed must be an integer";
                return;
            }

            try {
                columnInfo.IdentityIncrement = Convert.ToInt32(IdentityIncrementTextbox.Text);
            }
            catch {
                // Show error and quit
                ErrorUpdatingColumnLabel.Visible = true;
                ErrorUpdatingColumnLabel.Text    = "Invalid input: Identity increment must be an integer";
                return;
            }

            columnInfo.IsRowGuid = IsRowGuidCheckBox.Checked;

            SqlTable table = database.Tables[Request["table"]];

            // First check if the table exists or not
            // If it doesn't exist, that means we are adding the first column of a new table
            // If it does exist, then either we are adding a new column to an existing table
            //   or we are editing an existing column in an existing table

            if (table == null)
            {
                // Table does not exist - create a new table and add the new column
                try {
                    SqlColumnInformation[] columnInfos = new SqlColumnInformation[1] {
                        columnInfo
                    };
                    table = database.Tables.Add(Request["table"], columnInfos);
                }
                catch (Exception ex) {
                    // If the table was somehow created, get rid of it
                    table = database.Tables[Request["table"]];
                    if (table != null)
                    {
                        table.Remove();
                    }

                    // Show error and quit
                    ErrorUpdatingColumnLabel.Visible = true;
                    ErrorUpdatingColumnLabel.Text    = "The following error occured while trying to apply the changes.<br>" + Server.HtmlEncode(ex.Message).Replace("\n", "<br>");

                    server.Disconnect();
                    return;
                }
            }
            else
            {
                // Table does exist, do further check

                // If original name is blank that means it is a new column
                string originalColumnName = Request["column"];

                if (originalColumnName == null || originalColumnName.Length == 0)
                {
                    try {
                        table.Columns.Add(columnInfo);
                    }
                    catch (Exception ex) {
                        // Show error and quit
                        ErrorUpdatingColumnLabel.Visible = true;
                        ErrorUpdatingColumnLabel.Text    = "The following error occured while trying to apply the changes:<br>" + Server.HtmlEncode(ex.Message).Replace("\n", "<br>");

                        server.Disconnect();
                        return;
                    }
                }
                else
                {
                    // If we get here that means we are editing an existing column

                    // Simply set the column info - internally the table gets recreated
                    try {
                        table.Columns[originalColumnName].ColumnInformation = columnInfo;
                    }
                    catch (Exception ex) {
                        // Show error and quit
                        ErrorUpdatingColumnLabel.Visible = true;
                        ErrorUpdatingColumnLabel.Text    = "The following error occured while trying to apply the changes.<br>" + Server.HtmlEncode(ex.Message).Replace("\n", "<br>");

                        server.Disconnect();
                        return;
                    }
                }
            }

            server.Disconnect();

            // If we get here then that means a column was successfully added/edited
            Response.Redirect(String.Format("columns.aspx?database={0}&table={1}", Server.UrlEncode(Request["database"]), Server.UrlEncode(Request["table"])));
        }
Example #50
0
        public void Handle()
        {
            var procedureName = _input.ProcedureName;

            if (procedureName.IsNullOrEmpty())
            {
                Result.ErrorMessage = "Herhangi bir procedure ismi seçilmelidir";
                return;
            }
            var connectionInfo = FindProcedureContainerDatabaseConnectionInfo();

            if (connectionInfo == null)
            {
                return;
            }

            using (var database = new SqlDatabase(connectionInfo.ConnectionStringDev))
            {
                procedureName = ClearProcedure(procedureName);

                var dotNetMethodName = GetMethodNameFromProcedure(procedureName);

                var data = new CustomExecution
                {
                    DotNetMethodName  = dotNetMethodName,
                    SqlProcedureName  = procedureName.Split('.').Last(),
                    ExecutionType     = ExecutionType.ExecuteReader,
                    DatabaseEnumName  = connectionInfo.DatabaseName,
                    ProcedureFullName = procedureName,
                    Database          = database
                };

                if (dotNetMethodName.StartsWith("Update") ||
                    dotNetMethodName.StartsWith("Delete"))
                {
                    data.ExecutionType = ExecutionType.ExecuteNonQuery;
                }
                if (dotNetMethodName.StartsWith("Insert"))
                {
                    data.ExecutionType = ExecutionType.ExecuteScalar;
                }

                var generator = new CustomExecutionCs(null, data);

                if (dotNetMethodName.StartsWith("Select"))
                {
                    if (generator.ProcedureInfoReturnColumns.Count == 1)
                    {
                        data.ExecutionType = ExecutionType.ExecuteReaderForOneColumn;
                    }
                }

                if (data.ReturnValueType == null)
                {
                    if (generator.ParameterIsContract ||
                        data.ExecutionType == ExecutionType.ExecuteReader)
                    {
                        data.ReturnValueType = FindType();
                    }
                }

                Result.GeneratedCsCode = generator.Generate();
            }
        }
Example #51
0
        protected void ExportButton_Click(object sender, System.EventArgs e)
        {
            // Do the export - this will just pop open a Save As dialog box
            string databaseName           = this.ExportDatabaseList.SelectedItem.Text;
            bool   scriptDatabase         = this.ScriptDatabaseCheckBox.Checked;
            bool   scriptDrop             = this.ScriptDropCheckBox.Checked;
            bool   scriptTableSchema      = this.ScriptTableSchemeCheckBox.Checked;
            bool   scriptTableData        = this.ScriptTableDataCheckBox.Checked;
            bool   scriptStoredProcedures = this.ScriptStoredProceduresCheckBox.Checked;
            bool   scriptComments         = this.ScriptCommentsCheckBox.Checked;

            SqlServer server = SqlServer.CurrentServer;

            try
            {
                server.Connect();
            }
            catch (System.Exception ex)
            {
                //Response.Redirect("Error.aspx?errorPassCode=" + 2002);
                Response.Redirect(String.Format("error.aspx?errormsg={0}&stacktrace={1}", Server.UrlEncode(ex.Message), Server.UrlEncode(ex.StackTrace)));
            }

            SqlDatabase database = server.Databases[databaseName];

            if (database == null)
            {
                server.Disconnect();

                // Database doesn't exist - break out and go to error page
                Response.Redirect(String.Format("error.aspx?error={0}", 1000));
                return;
            }

            SqlTableCollection           tables = database.Tables;
            SqlStoredProcedureCollection sprocs = database.StoredProcedures;

            StringBuilder scriptResult = new StringBuilder();

            scriptResult.Append(String.Format("/* Generated by Web Data Administrator on {0} */\r\n\r\n", DateTime.Now.ToString()));
            scriptResult.Append("/* Options selected: ");
            if (scriptDatabase)
            {
                scriptResult.Append("database ");
            }
            if (scriptDrop)
            {
                scriptResult.Append("drop-commands ");
            }
            if (scriptTableSchema)
            {
                scriptResult.Append("table-schema ");
            }
            if (scriptTableData)
            {
                scriptResult.Append("table-data ");
            }
            if (scriptStoredProcedures)
            {
                scriptResult.Append("stored-procedures ");
            }
            if (scriptComments)
            {
                scriptResult.Append("comments ");
            }
            scriptResult.Append(" */\r\n\r\n");

            // Script flow:
            // DROP and CREATE database
            // use [database]
            // GO
            // DROP sprocs
            // DROP tables
            // CREATE tables without constraints
            // Add table data
            // Add table constraints
            // CREATE sprocs

            // Drop and create database
            if (scriptDatabase)
            {
                scriptResult.Append(database.Script(
                                        SqlScriptType.Create |
                                        (scriptDrop ? SqlScriptType.Drop : 0) |
                                        (scriptComments ? SqlScriptType.Comments : 0)));
            }

            // Use database
            scriptResult.Append(String.Format("\r\nuse [{0}]\r\nGO\r\n\r\n", databaseName));

            // Drop stored procedures
            if (scriptStoredProcedures && scriptDrop)
            {
                for (int i = 0; i < sprocs.Count; i++)
                {
                    if (sprocs[i].StoredProcedureType == SqlObjectType.User)
                    {
                        scriptResult.Append(sprocs[i].Script(SqlScriptType.Drop | (scriptComments ? SqlScriptType.Comments : 0)));
                    }
                }
            }

            // Drop tables (this includes schemas and data)
            if (scriptTableSchema && scriptDrop)
            {
                for (int i = 0; i < tables.Count; i++)
                {
                    if (tables[i].TableType == SqlObjectType.User)
                    {
                        scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.Drop | (scriptComments ? SqlScriptType.Comments : 0)));
                    }
                }
            }

            // Create table schemas
            if (scriptTableSchema)
            {
                // First create tables with no constraints
                for (int i = 0; i < tables.Count; i++)
                {
                    if (tables[i].TableType == SqlObjectType.User)
                    {
                        scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.Create | (scriptComments ? SqlScriptType.Comments : 0)));
                    }
                }
            }

            // Create table data
            if (scriptTableData)
            {
                for (int i = 0; i < tables.Count; i++)
                {
                    if (tables[i].TableType == SqlObjectType.User)
                    {
                        scriptResult.Append(tables[i].ScriptData(scriptComments ? SqlScriptType.Comments : 0));
                    }
                }
            }

            if (scriptTableSchema)
            {
                // Add defaults, primary key, and checks
                for (int i = 0; i < tables.Count; i++)
                {
                    if (tables[i].TableType == SqlObjectType.User)
                    {
                        scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.Defaults | SqlScriptType.PrimaryKey | SqlScriptType.Checks | (scriptComments ? SqlScriptType.Comments : 0)));
                    }
                }

                // Add foreign keys
                for (int i = 0; i < tables.Count; i++)
                {
                    if (tables[i].TableType == SqlObjectType.User)
                    {
                        scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.ForeignKeys | (scriptComments ? SqlScriptType.Comments : 0)));
                    }
                }

                // Add unique keys
                for (int i = 0; i < tables.Count; i++)
                {
                    if (tables[i].TableType == SqlObjectType.User)
                    {
                        scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.UniqueKeys | (scriptComments ? SqlScriptType.Comments : 0)));
                    }
                }

                // Add indexes
                for (int i = 0; i < tables.Count; i++)
                {
                    if (tables[i].TableType == SqlObjectType.User)
                    {
                        scriptResult.Append(tables[i].ScriptSchema(SqlScriptType.Indexes | (scriptComments ? SqlScriptType.Comments : 0)));
                    }
                }
            }

            // Create stored procedures
            if (scriptStoredProcedures)
            {
                for (int i = 0; i < sprocs.Count; i++)
                {
                    if (sprocs[i].StoredProcedureType == SqlObjectType.User)
                    {
                        scriptResult.Append(sprocs[i].Script(SqlScriptType.Create | (scriptComments ? SqlScriptType.Comments : 0)));
                    }
                }
            }

            server.Disconnect();

            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();

            // Set the filename to consist of only valid filename chars: [A-Za-z0-9]
            string filename = "";

            for (int i = 0; i < databaseName.Length; i++)
            {
                if (IsValidChar(databaseName[i]))
                {
                    filename += databaseName[i];
                }
            }

            // This header (RFC 1806) lets us set the suggested filename
            Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(filename) + "_export.sql");
            Response.Write(scriptResult.ToString());

            Response.End();
        }
Example #52
0
 public TasksTable(SqlDatabase db)
 {
     _db = db;
 }
Example #53
0
 /// <summary>
 /// Contructor có tham số
 /// </summary>
 /// <param name="DB">Đối tượng thao tác với database</param>
 /// Create by: dvthang:19.04.2017
 public UnitOfWork(SqlDatabase DB)
 {
     this.DB         = DB;
     this.connection = this.DB.CreateConnection();
 }
Example #54
0
        }        //end Delete

        #endregion

        #region Find Functions

        #region Parsed Find Methods
        /// <summary>
        ///     Returns rows meeting the whereclause condition from the DataSource.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">out. The number of rows that match this query.</param>
        /// <remarks>Operators must be capitalized (OR, AND)</remarks>
        /// <returns>Returns a typed collection of GenTest.Entities.Specchietto objects.</returns>
        public override TList <Specchietto> Find(TransactionManager transactionManager, string whereClause, int start, int pageLength, out int count)
        {
            count = -1;
            if (whereClause.IndexOf(";") > -1)
            {
                return(new TList <Specchietto>());
            }

            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Specchietto_Find", _useStoredProcedure);

            bool searchUsingOR = false;

            if (whereClause.IndexOf(" OR ") > 0)     // did they want to do "a=b OR c=d OR..."?
            {
                searchUsingOR = true;
            }

            database.AddInParameter(commandWrapper, "@SearchUsingOR", DbType.Boolean, searchUsingOR);

            database.AddInParameter(commandWrapper, "@Larghezza", DbType.Double, DBNull.Value);
            database.AddInParameter(commandWrapper, "@ID", DbType.Int32, DBNull.Value);
            database.AddInParameter(commandWrapper, "@AggregationMacchinaID", DbType.Int32, DBNull.Value);
            database.AddInParameter(commandWrapper, "@SgutAssociationSpecchiettoID", DbType.Int32, DBNull.Value);
            database.AddInParameter(commandWrapper, "@AssociationSpecchiettoID", DbType.Int32, DBNull.Value);

            // replace all instances of 'AND' and 'OR' because we already set searchUsingOR
            whereClause = whereClause.Replace(" AND ", "|").Replace(" OR ", "|");
            string[] clauses = whereClause.ToLower().Split('|');

            // Here's what's going on below: Find a field, then to get the value we
            // drop the field name from the front, trim spaces, drop the '=' sign,
            // trim more spaces, and drop any outer single quotes.
            // Now handles the case when two fields start off the same way - like "Friendly='Yes' AND Friend='john'"

            char[] equalSign   = { '=' };
            char[] singleQuote = { '\'' };
            foreach (string clause in clauses)
            {
                if (clause.Trim().StartsWith("larghezza ") || clause.Trim().StartsWith("larghezza="))
                {
                    database.SetParameterValue(commandWrapper, "@Larghezza",
                                               clause.Trim().Remove(0, 9).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
                    continue;
                }
                if (clause.Trim().StartsWith("id ") || clause.Trim().StartsWith("id="))
                {
                    database.SetParameterValue(commandWrapper, "@ID",
                                               clause.Trim().Remove(0, 2).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
                    continue;
                }
                if (clause.Trim().StartsWith("aggregationmacchinaid ") || clause.Trim().StartsWith("aggregationmacchinaid="))
                {
                    database.SetParameterValue(commandWrapper, "@AggregationMacchinaID",
                                               clause.Trim().Remove(0, 21).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
                    continue;
                }
                if (clause.Trim().StartsWith("sgutassociationspecchiettoid ") || clause.Trim().StartsWith("sgutassociationspecchiettoid="))
                {
                    database.SetParameterValue(commandWrapper, "@SgutAssociationSpecchiettoID",
                                               clause.Trim().Remove(0, 28).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
                    continue;
                }
                if (clause.Trim().StartsWith("associationspecchiettoid ") || clause.Trim().StartsWith("associationspecchiettoid="))
                {
                    database.SetParameterValue(commandWrapper, "@AssociationSpecchiettoID",
                                               clause.Trim().Remove(0, 24).Trim().TrimStart(equalSign).Trim().Trim(singleQuote));
                    continue;
                }

                throw new ArgumentException("Unable to use this part of the where clause in this version of Find: " + clause);
            }

            IDataReader reader = null;
            //Create Collection
            TList <Specchietto> rows = new TList <Specchietto>();


            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "Find", rows));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                Fill(reader, rows, start, pageLength);

                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "Find", rows));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }
            return(rows);
        }
Example #55
0
        /// <summary>
        ///     Gets rows from the datasource based on the PK_Culture_CultureID index.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="_cultureId">Primary key for Culture records.</param>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">out parameter to get total records for query.</param>
        /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.Culture"/> class.</returns>
        /// <remarks></remarks>
        /// <exception cref="System.Exception">The command could not be executed.</exception>
        /// <exception cref="System.Data.DataException">The <paramref name="transactionManager"/> is not open.</exception>
        /// <exception cref="System.Data.Common.DbException">The command could not be executed.</exception>
        public override Nettiers.AdventureWorks.Entities.Culture GetByCultureId(TransactionManager transactionManager, System.String _cultureId, int start, int pageLength, out int count)
        {
            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "Production.usp_adwTiers_Culture_GetByCultureId", _useStoredProcedure);

            database.AddInParameter(commandWrapper, "@CultureId", DbType.StringFixedLength, _cultureId);

            IDataReader     reader = null;
            TList <Culture> tmp    = new TList <Culture>();

            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "GetByCultureId", tmp));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                //Create collection and fill
                Fill(reader, tmp, start, pageLength);
                count = -1;
                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "GetByCultureId", tmp));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }

            if (tmp.Count == 1)
            {
                return(tmp[0]);
            }
            else if (tmp.Count == 0)
            {
                return(null);
            }
            else
            {
                throw new DataException("Cannot find the unique instance of the class.");
            }

            //return rows;
        }
Example #56
0
        /// <summary>
        ///     Returns rows from the DataSource that meet the parameter conditions.
        /// </summary>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
        /// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">out. The number of rows that match this query.</param>
        /// <returns>Returns a typed collection of GenTest.Entities.Specchietto objects.</returns>
        public override TList <Specchietto> Find(TransactionManager transactionManager, IFilterParameterCollection parameters, string orderBy, int start, int pageLength, out int count)
        {
            SqlFilterParameterCollection filter = null;

            if (parameters == null)
            {
                filter = new SqlFilterParameterCollection();
            }
            else
            {
                filter = parameters.GetParameters();
            }

            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Specchietto_Find_Dynamic", typeof(SpecchiettoColumn), filter, orderBy, start, pageLength);

            SqlFilterParameter param;

            for (int i = 0; i < filter.Count; i++)
            {
                param = filter[i];
                database.AddInParameter(commandWrapper, param.Name, param.DbType, param.GetValue());
            }

            TList <Specchietto> rows   = new TList <Specchietto>();
            IDataReader         reader = null;

            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "Find", rows));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                Fill(reader, rows, 0, int.MaxValue);
                count = rows.Count;

                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "Find", rows));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }

            return(rows);
        }
Example #57
0
 /// <summary>
 /// Contructor
 /// </summary>
 /// <param name="DB">Đối tượng thao tác với DB</param>
 /// <param name="ts">Transaction</param>
 /// Create by: dvthang:24.04.2017
 public BaseRepository(SqlDatabase DB, DbTransaction ts)
 {
     this.Init(ts, DB);
 }
Example #58
0
        }        //end getall

        #endregion

        #region GetPaged Methods

        /// <summary>
        /// Gets a page of rows from the DataSource.
        /// </summary>
        /// <param name="start">Row number at which to start reading.</param>
        /// <param name="pageLength">Number of rows to return.</param>
        /// <param name="count">Number of rows in the DataSource.</param>
        /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
        /// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
        /// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
        /// <remarks></remarks>
        /// <returns>Returns a typed collection of GenTest.Entities.Specchietto objects.</returns>
        public override TList <Specchietto> GetPaged(TransactionManager transactionManager, string whereClause, string orderBy, int start, int pageLength, out int count)
        {
            SqlDatabase database       = new SqlDatabase(this._connectionString);
            DbCommand   commandWrapper = StoredProcedureProvider.GetCommandWrapper(database, "dbo.Specchietto_GetPaged", _useStoredProcedure);


            if (commandWrapper.CommandType == CommandType.Text &&
                commandWrapper.CommandText != null)
            {
                commandWrapper.CommandText = commandWrapper.CommandText.Replace(SqlUtil.PAGE_INDEX, string.Concat(SqlUtil.PAGE_INDEX, Guid.NewGuid().ToString("N").Substring(0, 8)));
            }

            database.AddInParameter(commandWrapper, "@WhereClause", DbType.String, whereClause);
            database.AddInParameter(commandWrapper, "@OrderBy", DbType.String, orderBy);
            database.AddInParameter(commandWrapper, "@PageIndex", DbType.Int32, start);
            database.AddInParameter(commandWrapper, "@PageSize", DbType.Int32, pageLength);

            IDataReader reader = null;
            //Create Collection
            TList <Specchietto> rows = new TList <Specchietto>();

            try
            {
                //Provider Data Requesting Command Event
                OnDataRequesting(new CommandEventArgs(commandWrapper, "GetPaged", rows));

                if (transactionManager != null)
                {
                    reader = Utility.ExecuteReader(transactionManager, commandWrapper);
                }
                else
                {
                    reader = Utility.ExecuteReader(database, commandWrapper);
                }

                Fill(reader, rows, 0, int.MaxValue);
                count = rows.Count;

                if (reader.NextResult())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt32(0);
                    }
                }

                //Provider Data Requested Command Event
                OnDataRequested(new CommandEventArgs(commandWrapper, "GetPaged", rows));
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                commandWrapper = null;
            }

            return(rows);
        }
 public void Dispose()
 {
     _databaseCommandObj.Dispose();
     _databaseObj = null;
 }
        public void SetUp()
        {
            DatabaseProviderFactory factory = new DatabaseProviderFactory(new TestConfigurationContext());

            sqlDatabase = (SqlDatabase)factory.CreateDefaultDatabase();
        }