Пример #1
0
        private void frmMain_Load(object sender, EventArgs e)
        {
            string sql = "SELECT * FROM Students";
            using (SqlServerHelper ssh = new SqlServerHelper(
                DataConst.dataBase, DataConst.userName, DataConst.password))
            {
                DataSet ds = ssh.ExecuteQuery(sql);

                if (ds != null && ds.Tables.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    int index = 0;
                    lvStudents.Items.Clear();
                    foreach (DataRow dr in dt.AsEnumerable())
                    {
                        ListViewItem lvi = new ListViewItem(dr.Field<string>("XM"));

                        //byte[] buff = (byte[])dr["Image"];
                        //MemoryStream ms = new MemoryStream(buff);
                        //ms.Position = 0;
                        //Image ret = System.Drawing.Image.FromStream(ms, true);
                        //ilLarge.Images.Add("zs", ret);

                        lvi.ImageIndex = index;

                        lvi.Tag = dr;

                        index++;

                        lvStudents.Items.Add(lvi);
                    }
                }
            }
        }
Пример #2
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (tbNewPwd.Text.Trim() != tbConformPwd.Text.Trim())
            {
                MessageBox.Show("新密码与确认新密码不一致!");

                return;
            }

            string sql = "UPDATE [User] SET Password = '******' WHERE Name = '{1}'";
            sql = string.Format(sql, tbNewPwd.Text, m_UserName);
            using (SqlServerHelper ssh = new SqlServerHelper(
                DataConst.dataBase, DataConst.userName, DataConst.password))
            {
                object o = ssh.ExecuteNonQuery(sql);

                if ((int)o == 0)
                {
                    MessageBox.Show(string.Format("用户 {0} 不存在!",
                        m_UserName), "用户密码修改提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(string.Format("用户 {0} 的密码修改成功!",
                        m_UserName), "用户密码修改提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                }
            }
        }
Пример #3
0
 public void DapperOnlyReturnOneItem()
 {
     var sqlHelper = new SqlServerHelper(ConnectionString);
     string storedName = "usp_Blog_GetUserByName";
     User user = sqlHelper.GetItem<User>(storedName, new { UserName = "******" });
     Assert.AreEqual("toan", user.UserName);
 }
Пример #4
0
 public async Task DapperAsyncReturnManyItems()
 {
     var sqlHelper = new SqlServerHelper(ConnectionString);
     string storedName = "usp_Blog_GetActiveUsers";
     DateTime? onday = null;
     var query = await sqlHelper.GetManyItemsAsync<User>(storedName, new { OnDay = onday });
     List<User> users = query.ToList();
     Assert.IsTrue(users != null && users[0].UserName == "toan");
 }
Пример #5
0
 public async Task DapperAsyncOnlyReturnOneItem()
 {
     var sqlHelper = new SqlServerHelper(ConnectionString);
     string storedName = "usp_Blog_GetUserByName";
     var parameter = new DynamicParameters();
     parameter.Add("@UserName", "toan");
     //User user = sqlHelper.Get<User>(storedName, new { UserName = "******" });
     User user = await sqlHelper.GetItemAsync<User>(storedName, parameter);
     Assert.AreEqual("*****@*****.**", user.Email);
 }
Пример #6
0
 private DAOManager()
 {
     database = new SqlServerHelper();
     SQLServerConfig config = new SQLServerConfig();
     config.Server = "127.0.0.1";
     config.DatabaseName = "ZBMYunDB1";
     config.UserName = "******";
     config.Password = "******";
     config.Port = "1433";
     database.ConfigDatabase(config);
 }
Пример #7
0
        public override void Test(Action<Task[]> callBack)
        {
            Console.WriteLine("************************Begin调用自己的源码**************************");
            ISqlHelper sqlHelper = new SqlServerHelper();
            sqlHelper.Add();
            sqlHelper.Delete();
            sqlHelper.Update();
            sqlHelper.Search();

            ISqlHelper mysqlHelper = new MySQLHelper();
            mysqlHelper.Add();
            mysqlHelper.Delete();
            mysqlHelper.Update();
            mysqlHelper.Search();
            Console.WriteLine("************************End调用自己的源码**************************");

            Console.WriteLine("************************Begin通过适配器调用其他代码-类适配器**************************");
            ISqlHelper myLuceneAdapter = new MyLuceneAdapter();
            myLuceneAdapter.Add();
            myLuceneAdapter.Delete();
            myLuceneAdapter.Search();
            myLuceneAdapter.Update();
            Console.WriteLine("************************End通过适配器调用其他代码**************************");

            Console.WriteLine("************************Begin对象适配器PhoneApdapter**************************");
            XiaoMi xiaomi = new XiaoMi();
            xiaomi.Call();
            xiaomi.Message();

            Console.WriteLine("使用适配器,xiaomi丢失原有Message功能");
            var phoneApdapter = new PhoneApdapter(xiaomi);
            phoneApdapter.Call();
            phoneApdapter.Message();

            Console.WriteLine("使用适配器,dageda拥有适配器的Message功能");
            Dageda dageda = new Dageda();
            phoneApdapter = new PhoneApdapter(dageda);
            phoneApdapter.Call();
            phoneApdapter.Message();

            Console.WriteLine("************************End对象适配器PhoneApdapter**************************");

            callBack.Invoke(null);
        }
Пример #8
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!IsNameValid())
            {
                MessageBox.Show("用户名不能为空或空格!");

                return;
            }
            string sql = "SELECT COUNT(*) FROM [User] WHERE [Name] = '{0}' and [Password] = '{1}'";
            sql = string.Format(sql, tbXM.Text, tbMM.Text);
            using (SqlServerHelper ssh = new SqlServerHelper(DataConst.dataBase, DataConst.userName, DataConst.password))
            {
                object o = ssh.ExecuteScalar(sql);

                if ((int)o == 0)
                {
                    MessageBox.Show(string.Format("用户 {0} 不存在\r\n或密码错误!",
                        tbXM.Text), "用户登录信息出错提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                    this.DialogResult = DialogResult.OK;
            }
        }
Пример #9
0
 public OperationLogBll(SqlServerHelper _helper)
 {
     helper = _helper;
 }
Пример #10
0
 public Department_BLL(SqlServerHelper _helper) : base(_helper)
 {
     helper = _helper;
 }
Пример #11
0
        static void Main(string[] args)
        {
            SqlServerHelper sqlServer = new SqlServerHelper();
            //作业1.1
            {
                //作业一:提供两个泛型的数据库访问方法,用 BaseModel约束,一个是用id去查询单个实体,(只有这一个参数)
                //User user = new User();
                //user = SqlServerHelper.Find<User>(1);
                //user = SqlServerHelper.Find<User>(100);
            }

            //作业1.2 查询出数据表的全部数据列表查询(没有参数)
            {
                //List<User> userlist = new List<User>();
                //userlist = sqlServer.Query<User>();
            }

            //作业2 封装一个方法,能控制台输出任意实体的全部属性和属性值;
            {
                //User user = new User(){
                //    Id = 1,
                //    Name = "cc",
                //    Account = "cc"
                //};
                //GetProptyNameAndValue(user);
                //void GetProptyNameAndValue<T>(T t)
                //{
                //    Type type = t.GetType();
                //    foreach (PropertyInfo prop in type.GetProperties())
                //    {
                //        Console.WriteLine($"{prop.Name} = {prop.GetValue(t,null)}");
                //    }
                //}
            }

            //作业3.1 提供泛型的数据库实体插入
            {
                //User user = new User()
                //{
                //    Id = 1,
                //    Name = "cc",
                //    Account = "cc",
                //    Password = "******",
                //    State = 1,
                //    UserType = 2,
                //    CreateTime = DateTime.Now,
                //    CreatorId = 1
                //};
                //if (sqlServer.Insert(user))
                //{
                //    Console.WriteLine("插入成功");
                //}
            }

            //作业3.2 提供泛型的数据库实体更新
            {
                //User user = new User()
                //{
                //    Id = 1,
                //    Name = "cc",
                //    Account = "cc",
                //    Password = "******",
                //    State = 1,
                //    UserType = 2,
                //    CreateTime = DateTime.Now,
                //    CreatorId = 1
                //};
                //if (sqlServer.Update(user))
                //{
                //    Console.WriteLine("更新成功");
                //}
            }

            //作业3.3 提供泛型的数据库实体删除
            {
                //User user = new User()
                //{
                //    Id = 1
                //};
                //if (sqlServer.Delete(user))
                //{
                //    Console.WriteLine("删除成功");
                //}
            }

            //作业4 将数据访问层抽象,使用简单工厂+配置文件+反射的方式,来提供对数据访问层的使用
            {
                //IDBHelper dBHelper = SimpleFactory.CreateInstance();
                //if (dBHelper.Delete(new User() { Id = 8 }))
                //{
                //    Console.WriteLine("删除成功");
                //}
            }

            //作业5 每个实体类的基础增删改查SQL语句是不变的,用泛型缓存试试!
            {
                //User user1 = sqlServer.Find<User>(1);
                //User user2 = sqlServer.Find<User>(2);
                //List<User> userList = sqlServer.Query<User>();
            }
        }
Пример #12
0
        private void InitView()
        {
            Hashtable ht = new SqlServerHelper().GetHashtableById("Meter_WorkResolve", "ResolveID", ResolveID);

            if (ht != null)
            {
                UserOpinion.Text = ht["USEROPINION"].ToString().Trim();

                if (ht["MAKESKIP"] != null && ht["MAKEPOINTID"] != null)//是否显示跳转
                {
                    skip = (bool)ht["MAKESKIP"];
                    if (skip)
                    {
                        IsSkip.Visible       = true;
                        LB_GoPointID.Visible = true;
                        CB_GoPointID.Visible = true;
                        string    sqlstr = string.Format("SELECT PointName,PointSort  FROM Meter_WorkPoint WHERE WorkFlowID='{0}' AND PointSort IN ({1}) ORDER BY PointSort", ht["WORKFLOWID"].ToString(), ht["GOPOINTID"].ToString());
                        DataTable dt     = new SqlServerHelper().GetDateTableBySql(sqlstr);
                        ControlBindHelper.BindComboBoxData(this.CB_GoPointID, dt, "PointName", "PointSort");
                    }
                }
                if (!string.IsNullOrEmpty(ht["ISVOIDED"].ToString()))//是否显示报废
                {
                    bool isvisable = false;
                    if (bool.TryParse(ht["ISVOIDED"].ToString(), out isvisable))
                    {
                        Btn_Voided.Visible = isvisable;
                    }
                }

                if (!string.IsNullOrEmpty(ht["ISCHARGE"].ToString()))
                {
                    if (bool.TryParse(ht["ISCHARGE"].ToString(), out IsCharge))
                    {
                        FP_Fee.Visible = IsCharge;
                        //添加收费项目
                        if (IsCharge)
                        {
                            FP_Fee.Controls.Clear();
                            ApproveDispose.BindFeeItemTextBox(this.FP_Fee, ResolveID);

                            if (sysidal.IsHaveLastFeeItems(TaskID, PointSort))
                            {
                                //默认值传递
                                //=======================
                                Btn_More.Visible = true;
                                Btn_More.Left    = FP_Fee.Left;
                                Btn_More.Top     = FP_Fee.Top + FP_Fee.Height + 10;
                                DepartementID    = ht["DEPARTEMENTID"].ToString();
                                Btn_More.Click  += new EventHandler(Btn_More_Click);
                            }
                        }
                    }
                }
                if (!string.IsNullOrEmpty(ht["ISVIEWCHARGE"].ToString()))
                {
                    bool IsViewCharge = false;
                    if (bool.TryParse(ht["ISVIEWCHARGE"].ToString(), out IsViewCharge))
                    {
                        if (!FP_Fee.Visible)
                        {
                            FP_Items.Left    = FP_Fee.Left;
                            FP_Items.Top     = FP_Fee.Top;
                            FP_Items.Height += FP_Fee.Height;
                        }
                        FP_Items.Visible = IsViewCharge;

                        if (IsViewCharge)
                        {
                            FP_Items.Controls.Clear();
                            //查看所有收费项目
                            ApproveDispose.BindFeeItemLabel(this.FP_Items, TaskID, PointSort);
                        }
                    }
                }
                else
                {
                    if (FP_Fee.Visible)
                    {
                        FP_Fee.Height += FP_Items.Height;
                    }
                }
            }
        }
Пример #13
0
        private void Btn_Submit_Click(object sender, EventArgs e)
        {
            Hashtable ht = new Hashtable();

            if (string.IsNullOrEmpty(waterUserName.Text) || string.IsNullOrEmpty(waterUserAddress.Text) || string.IsNullOrEmpty(waterPhone.Text))
            {
                MessageBox.Show("信息不完整!");
                return;
            }

            ht = new SqlServerHelper().GetHashTableByControl(this.groupBox6.Controls);

            string newKey = Guid.NewGuid().ToString();
            string SDNO   = new SqlServerHelper().GetSDByTable("Meter_Install_Single");

            ht["ACCEPTID"] = SDNO;
            ht["LOGINID"]  = strLogID;
            ht["SD"]       = SDNO;

            AcceptID.Text = SDNO;

            if (string.IsNullOrEmpty(key))
            {
                ht["SingleID"] = newKey;
            }
            else
            {
                ht["SingleID"] = key;
            }

            if (new SqlServerHelper().Submit_AddOrEdit("Meter_Install_Single", "SingleID", key, ht))
            {
                AcceptID.Text      = ht["ACCEPTID"].ToString();
                Btn_Submit.Enabled = true;

                if (string.IsNullOrEmpty(key) || state.Equals("0"))
                {
                    //根据用水性质来确定审批流程==============================================================================================================
                    //  SELECT * FROM WaterUserType_Approve WHERE WaterUserTypeId=''===waterUserTypeId
                    //string sqlstr = string.Format("SELECT WorkCode FROM WaterUserType_Approve WHERE WaterUserTypeId='{0}'", waterUserTypeId.SelectedValue);
                    //DataTable dt = new SqlServerHelper().GetDateTableBySql(sqlstr);
                    //bool result = false;
                    //if (DataTableHelper.IsExistRows(dt))
                    //{
                    //    string taskcode = dt.Rows[0][0].ToString();
                    //    result = new SqlServerHelper().CreateWorkTask(ht["SingleID"].ToString(), SDNO, "Meter_Install_Single", "SingleID", "用户报装", taskcode);
                    //}
                    //else
                    //{
                    bool result = new SqlServerHelper().CreateWorkTask(ht["SingleID"].ToString(), SDNO, "Meter_Install_Single", "SingleID", "用户报装");
                    // }
                    if (result)
                    {
                        MessageBox.Show("任务创建成功!");
                        new SqlServerHelper().ClearControls(groupBox6.Controls);
                    }
                    else
                    {
                        MessageBox.Show("任务创建失败!");
                    }
                }
                if (!string.IsNullOrEmpty(key))
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
        }
Пример #14
0
 public VacuumRetestDAO()
 {
     _sqlServerDefault = new SqlServerHelper();
 }
        /// <summary>
        /// 根据公司Code取得CostCenter集合
        /// </summary>
        /// <param name="companyCode"></param>
        /// <returns></returns>
        public List <Model.Common.SingleField> GetActCostCenter(Model.Common.SingleField param)
        {
            List <Model.Common.SingleField> lstCostCenter = new List <Model.Common.SingleField>();
            List <Model.Common.SingleField> lstCCOrder    = new List <Model.Common.SingleField>();
            List <Model.Common.SingleField> lstCCWhs      = new List <Model.Common.SingleField>();

            // 当前时间
            string strDateTime = DateTime.Now.ToString("yyyy-MM-dd");
            // Sql文(SalesOrderLine)
            string strSqlOrder = " SELECT DISTINCT L.COSTCENTERCODE AS CODE " +
                                 " FROM SALESORDERITEM (nolock) AS L " +
                                 " INNER JOIN SALESORDERHEAD (nolock) AS H " +
                                 " ON L.HEADGUID = H.HEADGUID " +
                                 " AND H.OWNERCOMPANYCODE = '{0}' " +
                                 " AND H.STATUS <> '0' " +
                                 " AND L.STATUS <> '0' " +
                                 " INNER JOIN PRODUCTTYPEDATA AS P " +
                                 " ON L.PRODUCTCODE = P.ID " +
                                 " AND P.PRODUCTTYPE = 'SalesMeals' " +
                                 " WHERE H.VALIDDATE <= '{1}' AND H.STARTDATE <= '{1}' " +
                                 " AND ISNULL(H.EXPIRYDATE, H.ENDDATE) >= '{1}' " +
                                 " AND L.STARTDATE <= '{1}' " +
                                 " AND L.ENDDATE >= '{1}' " +
                                 " AND ISNULL(L.EXPIRYDATE,'2222-12-12') >= '{1}' ";

            lstCCOrder = SqlServerHelper.GetEntityList <Model.Common.SingleField>(SqlServerHelper.salesorderConn(), string.Format(strSqlOrder,
                                                                                                                                  param.code, strDateTime));

            // Sql文(CCWhs)
            string strSqlCCWhs = " SELECT COSTCENTERCODE AS CODE " +
                                 " FROM CCMast " +
                                 " WHERE DBNAME = '{0}' ";

            lstCCWhs = SqlServerHelper.GetEntityList <Model.Common.SingleField>(SqlServerHelper.salesorderConn(), string.Format(strSqlCCWhs,
                                                                                                                                param.code));

            //lstCostCenter = lstCCOrder.Concat(lstCCWhs).ToList();
            //lstCostCenter = lstCostCenter.Distinct().ToList();

            lstCostCenter = (from so in lstCCOrder
                             join wh in lstCCWhs
                             on so.code equals wh.code into cc
                             select new Model.Common.SingleField()
            {
                code = so.code
            }).ToList();

            if (lstCostCenter.Count == 0)
            {
                return(lstCostCenter);
            }

            // 如果Flag不为空则继续获取中/英文名称
            if (string.IsNullOrWhiteSpace(param.flag))
            {
                // 成本中心主档
                CompanyAddress addr = new CompanyAddress();
                addr.ip      = GetCompanyInfoByCode(param.code).ip;
                addr.erpCode = param.code;
                List <CostCenter> lstCCMastData = (new MastDataFactory()).GetCostCenter(addr);

                lstCostCenter.GroupJoin(lstCCMastData,
                                        cc => new { code = cc.code },
                                        ma => new { code = ma.costCenterCode },
                                        (cc, ma) =>
                {
                    var first  = ma.FirstOrDefault();
                    bool check = first != null;
                    cc.name1   = check ? first.costCenterName_ZH : string.Empty;
                    cc.name2   = check ? first.costCenterName_EN : string.Empty;

                    return(cc);
                }).ToList();
            }

            lstCostCenter = lstCostCenter.OrderBy(r => r.code).ToList();

            return(lstCostCenter);
        }
Пример #16
0
 public DoctorLog_BLL(SqlServerHelper _helper) : base(_helper)
 {
     helper = _helper;
 }
Пример #17
0
        public void TeardownTests()
        {
            string naming = "TestTeardown4";
            SqlTableDependency <TeardownTestSqlserver4Model> tableDependency = null;
            string dataBaseObjectsNamingConvention = null;

            var mapper = new ModelToTableMapper <TeardownTestSqlserver4Model>();

            mapper.AddMapping(c => c.Description, "Long Description");

            ////////////////////////////////////////////////////////
            // First Round
            ////////////////////////////////////////////////////////
            try
            {
                tableDependency            = new SqlTableDependency <TeardownTestSqlserver4Model>(ConnectionString, mapper: mapper, teardown: false, namingForObjectsAlreadyExisting: naming);
                tableDependency.OnChanged += TableDependency_Changed;
                tableDependency.Start();
                dataBaseObjectsNamingConvention = tableDependency.DataBaseObjectsNamingConvention;
                Assert.AreEqual(dataBaseObjectsNamingConvention, naming);

                Thread.Sleep(5000);

                var t = new Task(ModifyTableContent);
                t.Start();
                t.Wait(10000);
            }
            finally
            {
                tableDependency?.Dispose();
            }

            Assert.AreEqual(_notifiedValues.Count, 3);
            Assert.AreEqual(_insertedValues[0].Id, _notifiedValues[0].Id);
            Assert.AreEqual(_insertedValues[0].Name, _notifiedValues[0].Name);
            Assert.AreEqual(_insertedValues[0].Description, _notifiedValues[0].Description);
            Assert.AreEqual(_insertedValues[1].Id, _notifiedValues[1].Id);
            Assert.AreEqual(_insertedValues[1].Name, _notifiedValues[1].Name);
            Assert.AreEqual(_insertedValues[1].Description, _notifiedValues[1].Description);
            Assert.AreEqual(_insertedValues[2].Id, _notifiedValues[2].Id);
            Assert.AreEqual(_insertedValues[2].Name, _notifiedValues[2].Name);
            Assert.AreEqual(_insertedValues[2].Description, _notifiedValues[2].Description);
            Assert.IsFalse(SqlServerHelper.AreAllDbObjectDisposed(ConnectionString, naming));

            ////////////////////////////////////////////////////////
            // Inserd data while sql table dependency is not running
            ////////////////////////////////////////////////////////

            ModifyTableContent();

            ////////////////////////////////////////////////////////
            // Second Round
            ////////////////////////////////////////////////////////

            try
            {
                tableDependency.Start();
                dataBaseObjectsNamingConvention = tableDependency.DataBaseObjectsNamingConvention;
                Assert.AreEqual(dataBaseObjectsNamingConvention, naming);

                Thread.Sleep(5000);

                var t = new Task(ModifyTableContent);
                t.Start();
                t.Wait(10000);
            }
            finally
            {
                tableDependency.Stop();
            }

            Assert.AreEqual(_notifiedValues.Count, 9);

            Assert.AreEqual(_insertedValues[3].Id, _notifiedValues[3].Id);
            Assert.AreEqual(_insertedValues[3].Name, _notifiedValues[3].Name);
            Assert.AreEqual(_insertedValues[3].Description, _notifiedValues[3].Description);
            Assert.AreEqual(_insertedValues[4].Id, _notifiedValues[4].Id);
            Assert.AreEqual(_insertedValues[4].Name, _notifiedValues[4].Name);
            Assert.AreEqual(_insertedValues[4].Description, _notifiedValues[4].Description);
            Assert.AreEqual(_insertedValues[5].Id, _notifiedValues[5].Id);
            Assert.AreEqual(_insertedValues[5].Name, _notifiedValues[5].Name);
            Assert.AreEqual(_insertedValues[5].Description, _notifiedValues[5].Description);

            Assert.AreEqual(_insertedValues[6].Id, _notifiedValues[6].Id);
            Assert.AreEqual(_insertedValues[6].Name, _notifiedValues[6].Name);
            Assert.AreEqual(_insertedValues[6].Description, _notifiedValues[6].Description);
            Assert.AreEqual(_insertedValues[7].Id, _notifiedValues[7].Id);
            Assert.AreEqual(_insertedValues[7].Name, _notifiedValues[7].Name);
            Assert.AreEqual(_insertedValues[7].Description, _notifiedValues[7].Description);
            Assert.AreEqual(_insertedValues[8].Id, _notifiedValues[8].Id);
            Assert.AreEqual(_insertedValues[8].Name, _notifiedValues[8].Name);
            Assert.AreEqual(_insertedValues[8].Description, _notifiedValues[8].Description);

            Assert.IsFalse(SqlServerHelper.AreAllDbObjectDisposed(ConnectionString, naming));

            tableDependency            = new SqlTableDependency <TeardownTestSqlserver4Model>(ConnectionString, mapper: mapper, teardown: true, namingForObjectsAlreadyExisting: naming);
            tableDependency.OnChanged += TableDependency_Changed;
            tableDependency.Start();
            Thread.Sleep(500);
            tableDependency.Stop();
            Thread.Sleep(5000);
            Assert.IsTrue(SqlServerHelper.AreAllDbObjectDisposed(ConnectionString, naming));
        }
Пример #18
0
        public SmartCampus.Entity.BASE_ARTICLE GetEntity(int articleid)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("select ARTICLEID, QUOTE, MENUID, PHOTOID, FILEID, VERSION, STATUS, ICON, TITLE, CONTENT, SDATE, EDATE, READ, COMMENT, COPYRIGHT, AUTHOR  ");
            strSql.Append("  from BASE_ARTICLE ");
            strSql.Append(" where ARTICLEID=@ARTICLEID ");
            SqlParameter[] parameters =
            {
                new SqlParameter("@ARTICLEID", SqlDbType.Int, 4)
            };
            parameters[0].Value = articleid;


            SmartCampus.Entity.BASE_ARTICLE model = new SmartCampus.Entity.BASE_ARTICLE();
            DataSet ds = SqlServerHelper.Query(strSql.ToString(), parameters);

            if (ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["ARTICLEID"].ToString() != "")
                {
                    model.ARTICLEID = int.Parse(ds.Tables[0].Rows[0]["ARTICLEID"].ToString());
                }
                model.QUOTE   = ds.Tables[0].Rows[0]["QUOTE"].ToString();
                model.MENUID  = ds.Tables[0].Rows[0]["MENUID"].ToString();
                model.PHOTOID = ds.Tables[0].Rows[0]["PHOTOID"].ToString();
                model.FILEID  = ds.Tables[0].Rows[0]["FILEID"].ToString();
                model.VERSION = ds.Tables[0].Rows[0]["VERSION"].ToString();
                if (ds.Tables[0].Rows[0]["STATUS"].ToString() != "")
                {
                    model.STATUS = int.Parse(ds.Tables[0].Rows[0]["STATUS"].ToString());
                }
                model.ICON    = ds.Tables[0].Rows[0]["ICON"].ToString();
                model.TITLE   = ds.Tables[0].Rows[0]["TITLE"].ToString();
                model.CONTENT = ds.Tables[0].Rows[0]["CONTENT"].ToString();
                if (ds.Tables[0].Rows[0]["SDATE"].ToString() != "")
                {
                    model.SDATE = DateTime.Parse(ds.Tables[0].Rows[0]["SDATE"].ToString());
                }
                if (ds.Tables[0].Rows[0]["EDATE"].ToString() != "")
                {
                    model.EDATE = DateTime.Parse(ds.Tables[0].Rows[0]["EDATE"].ToString());
                }
                if (ds.Tables[0].Rows[0]["READ"].ToString() != "")
                {
                    model.READ = int.Parse(ds.Tables[0].Rows[0]["READ"].ToString());
                }
                if (ds.Tables[0].Rows[0]["COMMENT"].ToString() != "")
                {
                    model.COMMENT = int.Parse(ds.Tables[0].Rows[0]["COMMENT"].ToString());
                }
                model.COPYRIGHT = ds.Tables[0].Rows[0]["COPYRIGHT"].ToString();
                model.AUTHOR    = ds.Tables[0].Rows[0]["AUTHOR"].ToString();

                return(model);
            }
            else
            {
                return(null);
            }
        }
Пример #19
0
        private void Tools_Clicked(object tag)
        {
            if (tag != null)
            {
                switch (tag.ToString())
                {
                    case "1":
                        #region 添加学生
                        using (frmAddStudent frm = new frmAddStudent(null))
                        {
                            if (frm.ShowDialog() == DialogResult.OK)
                            {
                                string sql = "INSERT INTO [Students] " +
                                            "([XH], [XM], [MM], [XB], [NJ], [DH], [DZ], [CSRQ], [Email]) VALUES " +
                                            "('{0}', '{1}', '{2}', {3}, {4}, '{5}', '{6}', '{7}', '{8}')";

                                sql = string.Format(sql, frm.XH, frm.XM,
                                    frm.MM, frm.XB, frm.NJ, frm.DH,
                                    frm.DZ, frm.CSRQ, frm.Email);

                                using (SqlServerHelper ssh = new SqlServerHelper(
                                    DataConst.dataBase, DataConst.userName, DataConst.password))
                                {
                                    object o = ssh.ExecuteScalar(string.Format("Select count(*) from Students where xh = '{0}'",
                                        frm.XH));

                                    if ((int)o != 0)
                                    {
                                        MessageBox.Show(string.Format("学号为 {0} 的学生已经存在,请重新分配学号!",
                                            frm.XH), "添加学生出错提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                    else
                                    {
                                        if (ssh.ExecuteNonQuery(sql) > 0)
                                        {
                                            this.DialogResult = DialogResult.OK;
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                        break;
                    case "2":
                        #region 修改学生

                        if (lvStudents.SelectedItems.Count > 0)
                        {
                            ListViewItem lvi = lvStudents.SelectedItems[0];
                            if (lvi != null && lvi.Tag is DataRow)
                            {
                                using (frmAddStudent frm =
                                    new frmAddStudent(lvi.Tag as DataRow, true))
                                {
                                    if (frm.ShowDialog() == DialogResult.OK)
                                    {
                                    }
                                }
                            }
                            else
                                MessageBox.Show("选中的学生信息不正确!");
                        }
                        else
                            MessageBox.Show("请先选中需要修改的学生!");
                        #endregion
                        break;
                    case "3":
                        #region 修改密码
                        using (frmAlterPwd frm = new frmAlterPwd(m_UserName))
                        {
                            if (frm.ShowDialog() == DialogResult.OK)
                            {
                            }
                        }
                        #endregion
                        break;
                    case "4":
                        #region 查询学生
                        using (frmEnquiry frm = new frmEnquiry("Students"))
                        {
                            if (frm.ShowDialog() == DialogResult.OK)
                            {
                            }
                        }
                        #endregion
                        break;

                    case "9":
                        this.Close();
                        break;
                }
            }
        }
Пример #20
0
 private void lvStudents_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.KeyValue == 46)
     {
         if (_selectedDataRow != null)
         {
             if (MessageBox.Show("是否确认删除当前选中的信息!", "删除提示",
                 MessageBoxButtons.OKCancel,
                 MessageBoxIcon.Warning) == DialogResult.OK)
             {
                 string sql = "DELETE FROM Students WHERE XH = '{0}'";
                 sql = string.Format(sql, _selectedDataRow.Field<object>("XH"));
                 using (SqlServerHelper ssh = new SqlServerHelper(
                                 DataConst.dataBase, DataConst.userName, DataConst.password))
                 {
                     if (ssh.ExecuteNonQuery(sql) > 0)
                     {
                         _selectedDataRow = null;
                         lvStudents.Items.Remove(lvStudents.SelectedItems[0]);
                     }
                 }
             }
         }
         else
             MessageBox.Show("请先选中需要修改的学生!");
     }
 }
Пример #21
0
        private DataTable DoEnquiry()
        {
            ComboBoxItem cbi = (ComboBoxItem)cbFieldNames.SelectedItem;

            string sql = "Select * from " + _tableName;

            if (!chkEnquiry.Checked)
            {
                string filter = GetOption(cbi.Text, cbi.Xtype,
                    cbOption.SelectedIndex, tbMinValue.Text,
                    tbMaxValue.Text);

                sql += " WHERE ";

                sql += filter;
            }

            DataTable dt = null;
            using (SqlServerHelper ssh = new SqlServerHelper(
                DataConst.dataBase, DataConst.userName, DataConst.password))
            {
                DataSet ds = ssh.ExecuteQuery(sql);

                if (ds != null && ds.Tables.Count > 0)
                {
                    dt = ds.Tables[0];
                }
            }

            return dt;
        }
Пример #22
0
        private void frmEnquiry_Load(object sender, EventArgs e)
        {
            string sql = "Select Name, Xtype FROM SysColumns Where id=Object_Id('{0}')";
            sql = string.Format(sql, _tableName);

            using (SqlServerHelper ssh = new SqlServerHelper(
                DataConst.dataBase, DataConst.userName, DataConst.password))
            {
                DbDataReader ddr = ssh.ExecuteReader(sql);

                while (ddr.Read())
                {
                    cbFieldNames.Items.Add(new ComboBoxItem()
                    {
                        Text = ddr["name"].ToString(),
                        Xtype = int.Parse(ddr["Xtype"].ToString())
                    });
                }

                cbFieldNames.SelectedIndex =
                    cbFieldNames.Items.Count > 0 ? 0 : -1;
            }

            cbOption.SelectedIndex = 0;
        }
Пример #23
0
        public bool Update(SmartCampus.Entity.BASE_ARTICLE entity)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("update BASE_ARTICLE set ");

            strSql.Append(" ARTICLEID = @ARTICLEID , ");
            strSql.Append(" QUOTE = @QUOTE , ");
            strSql.Append(" MENUID = @MENUID , ");
            strSql.Append(" PHOTOID = @PHOTOID , ");
            strSql.Append(" FILEID = @FILEID , ");
            strSql.Append(" VERSION = @VERSION , ");
            strSql.Append(" STATUS = @STATUS , ");
            strSql.Append(" ICON = @ICON , ");
            strSql.Append(" TITLE = @TITLE , ");
            strSql.Append(" CONTENT = @CONTENT , ");
            strSql.Append(" SDATE = @SDATE , ");
            strSql.Append(" EDATE = @EDATE , ");
            strSql.Append(" READ = @READ , ");
            strSql.Append(" COMMENT = @COMMENT , ");
            strSql.Append(" COPYRIGHT = @COPYRIGHT , ");
            strSql.Append(" AUTHOR = @AUTHOR  ");
            strSql.Append(" where ARTICLEID=@ARTICLEID  ");

            SqlParameter[] parameters =
            {
                new SqlParameter("@ARTICLEID", SqlDbType.Int,          4),
                new SqlParameter("@QUOTE",     SqlDbType.VarChar,    200),
                new SqlParameter("@MENUID",    SqlDbType.VarChar,    200),
                new SqlParameter("@PHOTOID",   SqlDbType.VarChar,    200),
                new SqlParameter("@FILEID",    SqlDbType.VarChar,    200),
                new SqlParameter("@VERSION",   SqlDbType.VarChar,     10),
                new SqlParameter("@STATUS",    SqlDbType.Int,          4),
                new SqlParameter("@ICON",      SqlDbType.VarChar,    200),
                new SqlParameter("@TITLE",     SqlDbType.VarChar,    200),
                new SqlParameter("@CONTENT",   SqlDbType.Text),
                new SqlParameter("@SDATE",     SqlDbType.DateTime),
                new SqlParameter("@EDATE",     SqlDbType.DateTime),
                new SqlParameter("@READ",      SqlDbType.Int,          4),
                new SqlParameter("@COMMENT",   SqlDbType.Int,          4),
                new SqlParameter("@COPYRIGHT", SqlDbType.VarChar,   2000),
                new SqlParameter("@AUTHOR",    SqlDbType.VarChar, 20)
            };

            parameters[16].Value = entity.ARTICLEID;
            parameters[17].Value = entity.QUOTE;
            parameters[18].Value = entity.MENUID;
            parameters[19].Value = entity.PHOTOID;
            parameters[20].Value = entity.FILEID;
            parameters[21].Value = entity.VERSION;
            parameters[22].Value = entity.STATUS;
            parameters[23].Value = entity.ICON;
            parameters[24].Value = entity.TITLE;
            parameters[25].Value = entity.CONTENT;
            parameters[26].Value = entity.SDATE;
            parameters[27].Value = entity.EDATE;
            parameters[28].Value = entity.READ;
            parameters[29].Value = entity.COMMENT;
            parameters[30].Value = entity.COPYRIGHT;
            parameters[31].Value = entity.AUTHOR;
            int rows = SqlServerHelper.ExecuteSql(strSql.ToString(), parameters);

            if (rows > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #24
0
        private void bntInThongBao_Click(object sender, EventArgs e)
        {
            epInThongBao.Clear();
            if (txtNoiLamViec.Text.Length == 0)
            {
                epInThongBao.SetError(txtNoiLamViec, "Nơi làm việc không được bỏ trống!");
                txtNoiLamViec.Focus();
                return;
            }
            ;
            if (txtYeuCauKyThuat.Text.Length == 0)
            {
                epInThongBao.SetError(txtYeuCauKyThuat, "Yêu cầu kĩ thuật không được bỏ trống!");
                txtYeuCauKyThuat.Focus();
                return;
            }
            if (cbbViTriTuyen.Text.Length == 0)
            {
                epInThongBao.SetError(cbbViTriTuyen, "Vị trí tuyển không được bỏ trống!");
                cbbViTriTuyen.Focus();
                return;
            }
            ;
            if (txtLuongCB.Text.Length == 0)
            {
                epInThongBao.SetError(txtLuongCB, "Lương cơ bản không được bỏ trống!");
                txtLuongCB.Focus();
                return;
            }
            if (txtThoiGianLam.Text.Length == 0)
            {
                epInThongBao.SetError(txtThoiGianLam, "Thời gian làm không được bỏ trống!");
                txtThoiGianLam.Focus();
                return;
            }
            if (cbbTuoiTu.Text.Length == 0)
            {
                epInThongBao.SetError(cbbTuoiTu, "Tuổi không được bỏ trống!");
                cbbTuoiTu.Focus();
                return;
            }
            if (cbbTuoiDen.Text.Length == 0)
            {
                epInThongBao.SetError(cbbTuoiDen, "Tuổi không được bỏ trống!");
                cbbTuoiDen.Focus();
                return;
            }
            if (cbbViTriTuyen.Text != dtCongViec.Rows[indexSelected][1].ToString())
            {
                epInThongBao.SetError(cbbViTriTuyen, "Không tìm thấy công việc!");
                cbbViTriTuyen.Focus();
                return;
            }
            print();
            DialogResult result = MessageBox.Show("Bạn có muốn lưu lại mẫu không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    string sql = String.Format("Insert into tbl_MauThongBao values(@NoiLamViec, @YeuCauKyThuat, @SoLuongThamGia, @SoNguoiCanTuyen, @MaCV, @YeuCauKhac, @YeuCauNgoaiNgu, @TuoiTu, @TuoiDen, @MucLuong, @ThoiGianLamViec, @TinhTrangHonNhan, @HinhThucTuyen, @NgayDuKienXuatCanh, @NgayTaoMau)");
                    SqlServerHelper.ExecuteNonQuery(sql, CommandType.Text,
                                                    "@NoiLamViec", SqlDbType.NVarChar, txtNoiLamViec.Text,
                                                    "@YeuCauKyThuat", SqlDbType.NVarChar, txtYeuCauKyThuat.Text,
                                                    "@SoLuongThamGia", SqlDbType.NVarChar, txtSLThamGia.Text,
                                                    "@SoNguoiCanTuyen", SqlDbType.NVarChar, txtSoNguoiCanTuyen.Text,
                                                    "@MaCV", SqlDbType.Int, Convert.ToInt32(dtCongViec.Rows[indexSelected][0]),
                                                    "@YeuCauKhac", SqlDbType.NVarChar, txtYeuCauKhac.Text,
                                                    "@YeuCauNgoaiNgu", SqlDbType.NVarChar, txtNgoaiNgu.Text,
                                                    "@TuoiTu", SqlDbType.Int, Convert.ToInt32(cbbTuoiTu.Text),
                                                    "@TuoiDen", SqlDbType.Int, Convert.ToInt32(cbbTuoiDen.Text),
                                                    "@MucLuong", SqlDbType.NVarChar, txtLuongCB.Text,
                                                    "@ThoiGianLamViec", SqlDbType.NVarChar, txtThoiGianLam.Text,
                                                    "@TinhTrangHonNhan", SqlDbType.NVarChar, (radioDocThan.Checked ? 1 : radioDaKetHon.Checked ? 2 : 0),
                                                    "@HinhThucTuyen", SqlDbType.NVarChar, txtHinhThucTuyen.Text,
                                                    "@NgayDuKienXuatCanh", SqlDbType.NVarChar, txtXuatCanh.Text,
                                                    "@NgayTaoMau", SqlDbType.Date, DateTime.Now);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Lưu bị lỗi", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    MessageBox.Show(ex.ToString());
                }
            }
            this.Close();
        }
Пример #25
0
        private void OpenExcel()
        {
            DataTable dt = ExcelToDataSet.Load(TB_File.Text).Tables[0];

            if (DataTableHelper.IsExistRows(dt))
            {
                dgList.DataSource = dt;
                LB_Count.Text     = dt.Rows.Count.ToString();
                foreach (DataRow dr in dt.Rows)
                {
                    Hashtable ht = new Hashtable();
                    //Meter_Model md = new Meter_Model();
                    int SerialNumber = 0;
                    if (int.TryParse(dr[0].ToString(), out SerialNumber))
                    {
                        // md.waterMeterSerialNumber = SerialNumber.ToString();
                        ht["waterMeterSerialNumber"] = SerialNumber;
                    }
                    else
                    {
                        MessageBox.Show("出厂编号格式不正确,请重新编辑Excel");
                        return;
                    }

                    DataTable dtSize = new SqlServerHelper().GetDataTable("waterMeterSize", " waterMeterSizeValue LIKE '%" + dr[1].ToString() + "%' ", " waterMeterSizeId ");
                    if (DataTableHelper.IsExistRows(dtSize))
                    {
                        //md.waterMeterSizeId = dtSize.Rows[0][0].ToString();
                        ht["waterMeterSizeId"] = dtSize.Rows[0][0].ToString();
                    }
                    else
                    {
                        MessageBox.Show("未检测到口径'" + dr[1].ToString() + "',请重新编辑Excel");
                        return;
                    }

                    int StartNumber = 0;
                    if (int.TryParse(dr[2].ToString(), out StartNumber))
                    {
                        // md.waterMeterStartNumber = StartNumber;
                        ht["waterMeterStartNumber"] = StartNumber;
                    }
                    else
                    {
                        MessageBox.Show("初始读数格式不正确,请重新编辑Excel");
                        return;
                    }

                    int MaxRange = 0;
                    if (int.TryParse(dr[3].ToString(), out MaxRange))
                    {
                        //md.waterMeterMaxRange = MaxRange;
                        ht["waterMeterMaxRange"] = MaxRange;
                    }
                    else
                    {
                        MessageBox.Show("最大量程格式不正确,请重新编辑Excel");
                        return;
                    }

                    //md.waterMeterProduct = dr[4].ToString();
                    //md.waterMeterMode = dr[5].ToString();
                    ht["waterMeterProduct"] = dr[4].ToString();
                    ht["waterMeterMode"]    = dr[5].ToString();

                    DateTime dtime = DateTime.Now;
                    if (DateTime.TryParse(dr[6].ToString(), out dtime))
                    {
                        //md.waterMeterProofreadingDate = dtime;
                        ht["waterMeterProofreadingDate"] = dtime;
                    }
                    else
                    {
                        MessageBox.Show("鉴定日期格式不正确,请输入例如'2016-11-01'格式数据,请重新编辑Excel");
                        return;
                    }

                    //md.MEMO = dr[8].ToString();

                    //md.MeterID = Guid.NewGuid().ToString();
                    //md.CreateDate = DateTime.Now;
                    ht["waterMeteProofreadingPeriod"] = dr[7].ToString();
                    ht["MEMO"] = dr[8].ToString();

                    ht["MeterID"]    = Guid.NewGuid().ToString();
                    ht["CreateDate"] = DateTime.Now.ToString();

                    //MM.MeterModelItem.Add(md);
                    Lht.Add(ht);
                }
                Btn_Import.Enabled = true;
            }
            // LB_Vaild.Text = MM.MeterModelItem.Count.ToString();
            LB_Vaild.Text = Lht.Count.ToString();
        }
        public List <CountsLine> GetCountsLines(string erpCode, string ip, string warehouseCode, DateTime date, string langCode)
        {
            string stockSql = "select b1.itemCode,b1.itemName,b1.assortName,b1.diviable,b1.unit,round(sum(b1.qty),4) stockQty,"
                              + "round(case when sum(b1.qty) = 0 then 0 else sum(b1.amt) / sum(b1.qty) end, 4) price from "
                              + "(select a2.itemcode,case when 'zh-CN' = 'zh-CN' then case when isnull(a2.description_1,'')= '' then a2.description "
                              + "else a2.description_1 end else case when isnull(a2.description_0,'')= '' then a2.description "
                              + "else a2.description_0 end end itemName,case when '{0}' = 'zh-CN' then case when isnull(a3.description_1,'')= '' "
                              + "then a3.description else a3.description_1 end else case when isnull(a3.description_0,'')= '' "
                              + "then a3.description else a3.description_0 end end assortName, a2.isfractionalloweditem diviable,"
                              + "upper(ltrim(a2.packagedescription)) unit,a1.aantal qty, a1.bdr_hfl amt from gbkmut (nolock)a1,items(nolock) a2,"
                              + "itemassortment(nolock) a3,grtbk(nolock) a4,amutak(nolock) a5 where a1.artcode = a2.itemcode "
                              + "and a2.assortment=a3.assortment and a1.dagbknr = a5.dagbknr and a1.bkstnr = a5.bkstnr "
                              + "and a1.entryguid = a5.sysguid and a5.status <> 'V' and a4.reknr = a1.reknr and a4.omzrek = 'G' "
                              + "and a1.transtype in ('X', 'N', 'C', 'P') and a1.datum <='{1}' and a1.warehouse = '{2}') b1 "
                              + "group by b1.itemCode,b1.itemName,b1.assortName,b1.diviable,b1.unit having round(sum(b1.qty), 4) > 0 "
                              + "order by b1.assortName,b1.itemCode";
            DataTable data = SqlServerHelper.GetDataTable(string.Format(SqlServerHelper.customerConn(), ip, erpCode),
                                                          string.Format(stockSql, langCode, date.ToString("yyyy-MM-dd"), warehouseCode));

            if (data == null || data.Rows.Count == 0)
            {
                return(null);
            }
            DataTable taxData = null;
            Task      task    = new Task(() =>
            {
                string taxSql = "select a1.artcode itemCode,max(a2.btwper) taxRate from orsrg (nolock) a1,btwtrs (nolock) a2 "
                                + "where a1.btw_code=a2.btwtrans and a1.afldat between '{0}' and '{1}'" + " and a1.artcode in ({2}) "
                                + "and a1.btw_code<>'0' and a1.magcode='{3}' group by a1.artcode";
                taxData = SqlServerHelper.GetDataTable(string.Format(SqlServerHelper.customerConn(), ip, erpCode),
                                                       string.Format(taxSql, date.AddMonths(-1).ToString("yyyy-MM-dd"), date.ToString("yyyy-MM-dd"),
                                                                     string.Join(",", data.AsEnumerable().Select(dr => "'" + dr.Field <string>("ItemCode").ToStringTrim() + "'").ToArray()), warehouseCode));
                if (taxData == null)
                {
                    taxData = new DataTable();
                }
            });

            task.Start();
            ItemCostFactory costFactory = new ItemCostFactory(erpCode, ip, warehouseCode, date);

            task.Wait();
            List <CountsLine> query = (from dr in data.AsEnumerable()
                                       join tr in taxData.AsEnumerable()
                                       on dr.Field <string>("itemCode").ToStringTrim() equals tr.Field <string>("itemCode").ToStringTrim() into ldr
                                       from lr in ldr.DefaultIfEmpty()
                                       select new CountsLine()
            {
                assortment = dr.Field <string>("assortName").ToStringTrim(),
                itemCode = dr.Field <string>("itemCode").ToStringTrim(),
                itemName = dr.Field <string>("itemName").ToStringTrim(),
                inputType = dr.Field <bool>("diviable") ? "+decimal" : "+int",
                unit = dr.Field <string>("unit").ToStringTrim(),
                stockQty = dr.Field <double>("stockQty").ToString("0.###"),
                price = dr.Field <double>("price").ToString("0.####"),
                rate = lr == null ? 0 : Math.Round((lr.Field <double>("taxRate") / 100), 2),
                itemCosts = costFactory.GetCostArray(dr.Field <string>("itemCode").ToStringTrim(), date)
            }).ToList();

            return(query);
        }
Пример #27
0
 public BaseBLL(SqlServerHelper _helper)
 {
     helper = _helper;
 }
Пример #28
0
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Entity.BASE_USER GetEntity(int UserID)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("select UserID, UserName, Password, Email, Question, Answer, RoleID, UserGroup, CreateTime, LastLoginTime, Status, IsOnline, IsLimit  ");
            strSql.Append("  from Base_User ");
            strSql.Append(" where UserID=@UserID");
            SqlParameter[] parameters =
            {
                new SqlParameter("@UserID", SqlDbType.Int, 4)
            };
            parameters[0].Value = UserID;


            Entity.BASE_USER entity = new Entity.BASE_USER();
            DataSet          ds     = SqlServerHelper.Query(strSql.ToString(), parameters);

            if (ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["UserID"].ToString() != "")
                {
                    entity.UserID = int.Parse(ds.Tables[0].Rows[0]["UserID"].ToString());
                }
                entity.UserName = ds.Tables[0].Rows[0]["UserName"].ToString();
                entity.Password = ds.Tables[0].Rows[0]["Password"].ToString();
                entity.Email    = ds.Tables[0].Rows[0]["Email"].ToString();
                entity.Question = ds.Tables[0].Rows[0]["Question"].ToString();
                entity.Answer   = ds.Tables[0].Rows[0]["Answer"].ToString();
                if (ds.Tables[0].Rows[0]["UserGroup"].ToString() != "")
                {
                    entity.UserGroup = int.Parse(ds.Tables[0].Rows[0]["UserGroup"].ToString());
                }
                if (ds.Tables[0].Rows[0]["CreateTime"].ToString() != "")
                {
                    entity.CreateTime = DateTime.Parse(ds.Tables[0].Rows[0]["CreateTime"].ToString());
                }
                if (ds.Tables[0].Rows[0]["LastLoginTime"].ToString() != "")
                {
                    entity.LastLoginTime = DateTime.Parse(ds.Tables[0].Rows[0]["LastLoginTime"].ToString());
                }
                if (ds.Tables[0].Rows[0]["Status"].ToString() != "")
                {
                    entity.Status = int.Parse(ds.Tables[0].Rows[0]["Status"].ToString());
                }
                if (ds.Tables[0].Rows[0]["IsOnline"].ToString() != "")
                {
                    if ((ds.Tables[0].Rows[0]["IsOnline"].ToString() == "1") || (ds.Tables[0].Rows[0]["IsOnline"].ToString().ToLower() == "true"))
                    {
                        entity.IsOnline = true;
                    }
                    else
                    {
                        entity.IsOnline = false;
                    }
                }
                if (ds.Tables[0].Rows[0]["IsLimit"].ToString() != "")
                {
                    if ((ds.Tables[0].Rows[0]["IsLimit"].ToString() == "1") || (ds.Tables[0].Rows[0]["IsLimit"].ToString().ToLower() == "true"))
                    {
                        entity.IsLimit = true;
                    }
                    else
                    {
                        entity.IsLimit = false;
                    }
                }

                //读取角色
                entity.RoleID = GetUserRoleArray(entity.UserID);

                return(entity);
            }
            else
            {
                return(null);
            }
        }
Пример #29
0
 public void SetupOnce()
 {
     SetupLog4Net();
     SqlServerHelper.CreateDatabaseFiles();
 }
Пример #30
0
        /// <summary>
        /// 根据用户名得到用户对象实体
        /// </summary>
        public Entity.BASE_USER GetUserModel(string UserName)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("select top 1 * from Base_User ");
            strSql.Append(" where UserName=@UserName ");
            SqlParameter[] parameters =
            {
                new SqlParameter("@UserName", SqlDbType.NVarChar, 128)
            };
            parameters[0].Value = UserName;

            Entity.BASE_USER model = new Entity.BASE_USER();
            DataSet          ds    = SqlServerHelper.Query(strSql.ToString(), parameters);

            if (ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["UserID"].ToString() != "")
                {
                    model.UserID = int.Parse(ds.Tables[0].Rows[0]["UserID"].ToString());
                }
                model.UserName = ds.Tables[0].Rows[0]["UserName"].ToString();
                model.Password = ds.Tables[0].Rows[0]["Password"].ToString();
                model.Email    = ds.Tables[0].Rows[0]["Email"].ToString();
                model.Question = ds.Tables[0].Rows[0]["Question"].ToString();
                model.Answer   = ds.Tables[0].Rows[0]["Answer"].ToString();

                if (ds.Tables[0].Rows[0]["UserGroup"].ToString() != "")
                {
                    model.UserGroup = int.Parse(ds.Tables[0].Rows[0]["UserGroup"].ToString());
                }
                if (ds.Tables[0].Rows[0]["CreateTime"].ToString() != "")
                {
                    model.CreateTime = DateTime.Parse(ds.Tables[0].Rows[0]["CreateTime"].ToString());
                }
                if (ds.Tables[0].Rows[0]["LastLoginTime"].ToString() != "")
                {
                    model.LastLoginTime = DateTime.Parse(ds.Tables[0].Rows[0]["LastLoginTime"].ToString());
                }
                if (ds.Tables[0].Rows[0]["Status"].ToString() != "")
                {
                    model.Status = int.Parse(ds.Tables[0].Rows[0]["Status"].ToString());
                }
                if (ds.Tables[0].Rows[0]["IsOnline"].ToString() != "")
                {
                    if ((ds.Tables[0].Rows[0]["IsOnline"].ToString() == "1") || (ds.Tables[0].Rows[0]["IsOnline"].ToString().ToLower() == "true"))
                    {
                        model.IsOnline = true;
                    }
                    else
                    {
                        model.IsOnline = false;
                    }
                }
                if (ds.Tables[0].Rows[0]["IsLimit"].ToString() != "")
                {
                    if ((ds.Tables[0].Rows[0]["IsLimit"].ToString() == "1") || (ds.Tables[0].Rows[0]["IsLimit"].ToString().ToLower() == "true"))
                    {
                        model.IsLimit = true;
                    }
                    else
                    {
                        model.IsLimit = false;
                    }
                }

                //读取角色
                model.RoleID = GetUserRoleArray(model.UserID);

                return(model);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Sets up the sql database for SonarQube service.
        /// </summary>
        void SetupSonarQubeDatabaseForExpressInstallation()
        {
            string databaseName = BootstrapperManager.Instance.Bootstrapper.Engine.StringVariables["DATABASENAME"];
            string userName     = BootstrapperManager.Instance.Bootstrapper.Engine.StringVariables["DATABASEUSERNAME"];
            string password     = BootstrapperManager.Instance.Bootstrapper.Engine.StringVariables["DATABASEPASSWORD"];
            string dataSource   = BootstrapperManager.Instance.Bootstrapper.Engine.StringVariables["INSTANCE"];
            string sqlAuthType  = BootstrapperManager.Instance.Bootstrapper.Engine.StringVariables["SQLAUTHTYPE"];
            string installSql   = BootstrapperManager.Instance.Bootstrapper.Engine.StringVariables["INSTALLSQL"];

            // Scenario 1 - Sql New Installation
            //              a) Windows Authentication
            //                 -- Only create db (local user gets permissions by default)
            //              b) Sql Authentication
            //                 -- Create login with given credentials -> create db -> create user with created login -> make user db_owner
            // Scenario 2 - Sql Old Installation
            //              a) Windows Authentication
            //                 -- Create db
            //              b) Sql Authentication
            //                 -- Create db using given login -> create user for given login -> make user db_owner

            if (AuthenticationType.Windows.Equals(sqlAuthType, StringComparison.InvariantCultureIgnoreCase))
            {
                using (SqlConnection connection = SqlServerHelper.CreateSqlConnectionWithWindowsLogin(dataSource))
                {
                    connection.Open();

                    connection.CreateSqlServerDatabase(databaseName);
                }
            }
            else
            {
                // If sql has been installed by our installer and user has chosen the option to have sql authentication,
                // we will have to use windows authentication to create that login.
                if (installSql.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase))
                {
                    using (SqlConnection connection = SqlServerHelper.CreateSqlConnectionWithWindowsLogin(dataSource))
                    {
                        connection.Open();

                        connection.CreateNewSqlServerLogin(userName, password);
                        connection.CreateSqlServerDatabase(databaseName);
                    }

                    using (SqlConnection connection = SqlServerHelper.CreateSqlConnectionWithSqlLogin(dataSource, userName, password, databaseName))
                    {
                        connection.Open();

                        connection.CreateSqlUserFromSqlLogin(userName, userName);
                        connection.ChangeSqlUserDbRole("db_owner", userName);
                    }
                }
                else
                {
                    using (SqlConnection connection = SqlServerHelper.CreateSqlConnectionWithSqlLogin(dataSource, userName, password))
                    {
                        connection.Open();

                        connection.CreateSqlServerDatabase(databaseName);
                    }

                    using (SqlConnection connection = SqlServerHelper.CreateSqlConnectionWithSqlLogin(dataSource, userName, password, databaseName))
                    {
                        connection.Open();

                        connection.CreateSqlUserFromSqlLogin(userName, userName);
                        connection.ChangeSqlUserDbRole("db_owner", userName);
                    }
                }

                // For sql authentication, SonarQube service runs as SYSTEM,
                // We need to give permission to this account in db.
                using (SqlConnection connection = SqlServerHelper.CreateSqlConnectionWithSqlLogin(dataSource, userName, password, databaseName))
                {
                    connection.Open();

                    connection.CreateSqlUserFromSqlLogin("NTSYSTEM", @"NT AUTHORITY\SYSTEM");
                    connection.ChangeSqlUserDbRole("db_owner", "NTSYSTEM");
                }
            }
        }
Пример #32
0
 /// <summary>
 /// 读取角色名称
 /// </summary>
 /// <param name="roleid"></param>
 /// <returns></returns>
 public object GetRoleName(int roleid)
 {
     return(SqlServerHelper.GetSingle("select RoleName from Base_Role where RoleID=" + roleid));
 }
Пример #33
0
        static void Main(string[] args)
        {
            try
            {
                #region 创建连接
                {
                    Console.WriteLine("==========创建连接=============");
                    //IDBHelper iDBHelper = new MySqlHelper();
                    IDBHelper iDBHelper = new SqlServerHelper();

                    //当MySqlHelper换成SqlServerHelper 就必学修改现有的代码,重新编译然后发布,为了提高效率我们可以利用反射来解决这一问题。
                }
                #endregion

                #region 加载DLL
                {
                    Console.WriteLine("==========加载DLL==========");
                    //根据名称加载程序集
                    //Assembly assembly = Assembly.Load("Gs.DB.MySql");
                    //根据完整路径加载程序集
                    //Assembly assembly1 = Assembly.LoadFile(@"‪C:\Users\wango\source\repos\Reflection\Gs.DB.MySql\bin\Debug\Gs.DB.MySql.dll");
                    //根据名称加载程序集
                    Assembly assembly2 = Assembly.LoadFrom("Gs.DB.SqlServer.dll");
                    //根据完整路径加载程序集
                    //Assembly assembly3 = Assembly.LoadFrom(@"C:\Users\wango\source\repos\Reflection\Gs.DB.MySql\bin\Debug\Gs.DB.MySql.dll");
                    ///**
                    ///以上四个assembly获取的结果都是一样的
                    ///看起来LoadFile和LoadFrom作用是一样,他们两个有什么区别呢?
                    ///LoadFile加载dll文件时只会加载指定的dll文件,不会加载与指定dll文件相关的dll文件,而LoadFrom则会加载与指定dll文件相关的dll文件
                    ///LoadFrom加载dll文件时会先检查前面是否已经加载过相同名称的dll,如果载入过相同的dll那就不能再载入,而LoadFile不检查,会直接覆盖之前相同名称的dll文件
                    ///

                    ///

                    foreach (var type in assembly2.GetTypes())
                    {
                        Console.WriteLine("类:" + type.Name);
                        foreach (var method in type.GetMethods())
                        {
                            Console.WriteLine(type.Name + "类中的方法:" + method.Name);
                        }
                    }
                }
                #endregion

                #region 加载DLL并创建对象
                {
                    Console.WriteLine("*****************加载DLL并创建对象、调用方法********************");
                    Assembly assembly = Assembly.Load("Gs.DB.SqlServer");                    //1 动态加载
                    Type     type     = assembly.GetType("Gs.DB.SqlServer.SqlServerHelper"); //2 获取程序集下的指定类
                    foreach (var member in type.GetMembers())
                    {
                        //遍历类中的方法
                        Console.WriteLine("方法名:" + member.Name);
                    }
                    //object oDBHelper = Activator.CreateInstance(type); //创建对象
                    //oDBHelper.Say(); //调用方法,实际上oDBHelper是有SqlServerHelper()这个方法,只不过编译器不通过,解决这个问题可以用dynamic来收
                    dynamic dDBHelper = Activator.CreateInstance(type);
                    dDBHelper.Say(); //dynamic编译器不检查,方法拼写一定要写对

                    //不使用dynamic,转换类型也可以
                    object    oDBHelper       = Activator.CreateInstance(type); //创建对象
                    IDBHelper SqlServerHelper = oDBHelper as IDBHelper;
                    SqlServerHelper.Say();                                      //调用方法,实际上oDBHelper是有SqlServerHelper()这个方法,只不过编译器不通过,解决这个问题可以用dynamic来收
                }
                #endregion 封装之后
                {
                    Console.WriteLine("*****************封装之后********************");
                    IDBHelper iDBHelper = SimpleFactory.CreateInstance();
                    iDBHelper.Say();
                    //程序的可配置,通过修改配置文件就可以自动切换,实现类必须是事先已有的,而且在目录下面,没有写死类型,而是通过配置文件执行,反射创建的
                    //可扩展:完全不修改原有代码,只是增加新的实现,copy,修改配置文件,就可以支持新功能
                    //反射的动态加载和动态创建对象  以及配置文件结合
                }

                #region 调用带参方法
                {
                    //Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                    //Type type = assembly.GetType("Ruanmou.DB.SqlServer.ReflectionTest");
                    //foreach (ConstructorInfo ctor in type.GetConstructors())
                    //{
                    //    Console.WriteLine(ctor.Name);
                    //    foreach (var parameter in ctor.GetParameters())
                    //    {
                    //        Console.WriteLine(parameter.ParameterType);
                    //    }
                    //}
                    //object oTest1 = Activator.CreateInstance(type);
                    //object oTest2 = Activator.CreateInstance(type, new object[] { 123 });
                    //object oTest3 = Activator.CreateInstance(type, new object[] { "陌殇" });

                    Console.WriteLine("*****************调用带参方法********************");
                    Assembly assembly = Assembly.Load("Gs.DB.SqlServer");
                    Type     type     = assembly.GetType("Gs.DB.SqlServer.ReflectionTest");
                    foreach (ConstructorInfo ctor in type.GetConstructors())
                    {
                        //获取类中的构造方法
                        Console.WriteLine("111:" + ctor.Name);
                        foreach (var parameter in ctor.GetParameters())
                        {
                            //返回构造方法的参数
                            Console.WriteLine("222:" + parameter.ParameterType);
                        }
                    }
                    object oTest1 = Activator.CreateInstance(type);
                    object oTest2 = Activator.CreateInstance(type, new object[] { 960927 });
                    object oTest3 = Activator.CreateInstance(type, new object[] { "调用带参方法" });
                }
                #endregion

                #region 反射破坏单例
                {
                    Console.WriteLine("********************反射破坏单例********************");
                    Singleton singleton1 = Singleton.GetInstance(); //new Singleton();
                    Singleton singleton2 = Singleton.GetInstance();
                    Singleton singleton3 = Singleton.GetInstance();
                    Singleton singleton4 = Singleton.GetInstance();
                    Singleton singleton5 = Singleton.GetInstance();
                    Console.WriteLine($"{object.ReferenceEquals(singleton1, singleton5)}");

                    //反射破坏单例---因为构造方法是用private修饰的,防止外部调用,但是反射不受限制
                    Assembly  assembly   = Assembly.Load("Gs.DB.SqlServer");
                    Type      type       = assembly.GetType("Gs.DB.SqlServer.Singleton");
                    Singleton singletonA = (Singleton)Activator.CreateInstance(type, true);
                    Singleton singletonB = (Singleton)Activator.CreateInstance(type, true);
                    Singleton singletonC = (Singleton)Activator.CreateInstance(type, true);
                    Singleton singletonD = (Singleton)Activator.CreateInstance(type, true);
                    Console.WriteLine($"{object.ReferenceEquals(singletonA, singletonD)}");
                }

                #endregion 反射调用泛型
                {
                    Console.WriteLine("********************反射调用泛型********************");
                    Assembly assembly = Assembly.Load("Gs.DB.SqlServer");
                    Type     type     = assembly.GetType("Gs.DB.SqlServer.GenericClass`3"); //3表示GenericClass有3个参数

                    Type    typeMake = type.MakeGenericType(new Type[] { typeof(string), typeof(int), typeof(DateTime) });
                    dynamic oGeneric = Activator.CreateInstance(typeMake);
                    oGeneric.ShowA();
                    //MethodInfo method = type.GetMethod("Show").MakeGenericMethod(typeof(string), typeof(string), typeof(string));
                    //method.Invoke(oGeneric, new object[] { "123","456","789" });
                }
                #region   做类型转换调用
                {
                    //如果反射创建对象之后,知道方法名称,怎么样不做类型转换,直接调用方法?
                    //反射创建了对象实例---有方法的名称--反射调用方法
                    //dll名称---类型名称---方法名称---我们就能调用方法
                    //MVC就是靠的这一招---调用Action
                    //http://localhost:9099/home/index  经过路由解析---会调用--HomeController--Index方法
                    //浏览器输入时只告诉了服务器类型名称和方法名称,肯定是反射的
                    //MVC在启动时会先加载--扫描全部的dll--找到全部的Controller--存起来--请求来的时候,用Controller来匹配的---dll+类型名称
                    //1 MVC局限性的--Action重载--反射是无法区分---只能通过HttpMethod+特性httpget/httppost
                    //2 AOP--反射调用方法,可以在前后插入逻辑
                    Console.WriteLine("********************不做类型转换调用********************");
                    Assembly assembly = Assembly.Load("Gs.DB.SqlServer");
                    Type     type     = assembly.GetType("Gs.DB.SqlServer.ReflectionTest");
                    object   oTest    = Activator.CreateInstance(type);

                    foreach (var method in type.GetMethods())
                    {
                        //获取类中的方法名
                        Console.WriteLine("方法名:" + method.Name);
                        foreach (var parameter in method.GetParameters())
                        {
                            //获取方法中的参数
                            Console.WriteLine(method.Name + "方法中的参数:" + parameter.Name + "===" + parameter.ParameterType);
                        }
                    }
                    {
                        ReflectionTest reflection = new ReflectionTest();
                        Console.WriteLine("普通调用");
                        reflection.Show1();
                    }
                    {
                        MethodInfo method = type.GetMethod("Show1");
                        Console.WriteLine("反射调用");
                        method.Invoke(oTest, null);
                    }
                    {
                        MethodInfo method = type.GetMethod("Show2");
                        Console.WriteLine("反射调用有参方法");
                        method.Invoke(oTest, new object[] { 123 });
                    }
                    {
                        MethodInfo method = type.GetMethod("Show3", new Type[] { });
                        Console.WriteLine("反射调用重载无参方法Show3");
                        method.Invoke(oTest, null);
                    }
                    {
                        MethodInfo method = type.GetMethod("Show3", new Type[] { typeof(int) });
                        method.Invoke(oTest, new object[] { 1700 });
                    }
                    {
                        MethodInfo method = type.GetMethod("Show3", new Type[] { typeof(string) });
                        method.Invoke(oTest, new object[] { "2020年2月23日17:02:00" });
                    }
                    {
                        MethodInfo method = type.GetMethod("Show3", new Type[] { typeof(int), typeof(string) });
                        method.Invoke(oTest, new object[] { 1702, "2020年2月23日17:02:38" });
                    }
                    {
                        MethodInfo method = type.GetMethod("Show3", new Type[] { typeof(string), typeof(int) });
                        method.Invoke(oTest, new object[] { "2020年2月23日17:04:02", 1704 });
                    }
                    {
                        MethodInfo method = type.GetMethod("Show5");
                        method.Invoke(oTest, new object[] { "2020年2月23日17:04:32" });
                    }
                }
                #endregion 调用私有方法
                {
                    //调用私有方法
                    Console.WriteLine("&&&&&&&&&&&&&&&&&&&&私有方法&&&&&&&&&&&&&&&&&&&");
                    Assembly assembly = Assembly.Load("Gs.DB.SqlServer");
                    Type     type     = assembly.GetType("Gs.DB.SqlServer.ReflectionTest");
                    object   oTest    = Activator.CreateInstance(type);
                    var      method   = type.GetMethod("Show4", BindingFlags.Instance | BindingFlags.NonPublic);
                    //var method = type.GetMethod("Show4");
                    method.Invoke(oTest, new object[] { "2020年2月23日17:13:08" });
                }
                #region
                {
                    Console.WriteLine("********************调用泛型方法********************");
                    Assembly assembly = Assembly.Load("Gs.DB.SqlServer");
                    Type     type     = assembly.GetType("Gs.DB.SqlServer.GenericMethod");
                    object   oGeneric = Activator.CreateInstance(type);
                    foreach (var item in type.GetMethods())
                    {
                        //获取类中的方法
                        Console.WriteLine("类中的方法:" + item.Name);
                    }
                    MethodInfo method    = type.GetMethod("Show"); //获取方法
                    var        methodNew = method.MakeGenericMethod(new Type[] { typeof(int), typeof(string), typeof(DateTime) });
                    object     oReturn   = methodNew.Invoke(oGeneric, new object[] { 1920, "2020年2月23日19:20:25", DateTime.Now });
                }
                #endregion
                {
                    Console.WriteLine("********************调用泛型类中的泛型方法********************");
                    Assembly   assembly = Assembly.Load("Gs.DB.SqlServer");
                    Type       type     = assembly.GetType("Gs.DB.SqlServer.GenericDouble`1").MakeGenericType(typeof(int));
                    object     oObject  = Activator.CreateInstance(type);
                    MethodInfo method   = type.GetMethod("Show").MakeGenericMethod(typeof(string), typeof(DateTime));
                    method.Invoke(oObject, new object[] { 1927, "2020年2月23日19:42:22", DateTime.Now });
                }
                #region
                {
                    Console.WriteLine("*****************Common*******************");
                    People people = new People();
                    people.Id          = 001;
                    people.Name        = "孙悟空";
                    people.Description = "我是齐天大圣";
                    Console.WriteLine($"people.Id={people.Id}");
                    Console.WriteLine($"people.Name={people.Name}");
                    Console.WriteLine($"people.Description={people.Description}");
                }
                #endregion 反射赋值
                {
                    //1 get 反射展示是有意义的--反射遍历,可以不用改代码
                    //2 set 感觉好像没啥用
                    Console.WriteLine("*****************反射赋值*******************");
                    Type   type    = typeof(People);
                    object oPeople = Activator.CreateInstance(type);
                    foreach (var prop in type.GetProperties())
                    {
                        Console.WriteLine("类:" + type.Name + ";属性:" + prop.Name + ";值:" + prop.GetValue(oPeople));
                        Console.WriteLine($"{type.Name}.{prop.Name}={prop.GetValue(oPeople)}");
                        if (prop.Name.Equals("Id"))
                        {
                            prop.SetValue(oPeople, 234);
                        }
                        else if (prop.Name.Equals("Name"))
                        {
                            prop.SetValue(oPeople, "猪八戒");
                        }
                        Console.WriteLine($"{type.Name}.{prop.Name}={prop.GetValue(oPeople)}");
                    }
                    foreach (var field in type.GetFields())
                    {
                        Console.WriteLine($"{type.Name}.{field.Name}={field.GetValue(oPeople)}");
                        if (field.Name.Equals("Description"))
                        {
                            field.SetValue(oPeople, "我是天蓬元帅");
                        }
                        Console.WriteLine($"{type.Name}.{field.Name}={field.GetValue(oPeople)}");
                    }
                }
                #region 动态查询数据库
                {
                    Console.WriteLine("******************动态查询数据库*********************");
                    SqlServerHelper helper  = new SqlServerHelper();
                    Company         company = helper.Find <Company>(1);
                    User            user    = helper.Find <User>(1);
                }
                #endregion 测试性能
                {
                    Console.WriteLine("*******************测试性能*******************");
                    Monitor.Show();
                }
                #region

                #endregion
            }
            catch (Exception e)
            {
                Console.WriteLine("错误信息:" + e.Message);
            }
            Console.WriteLine("运行完毕");
            Console.ReadLine();
        }
Пример #34
0
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Entity.BASE_USER entity)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("update Base_User set ");

            strSql.Append(" UserName = @UserName , ");
            strSql.Append(" Password = @Password , ");
            strSql.Append(" Email = @Email , ");
            strSql.Append(" Question = @Question , ");
            strSql.Append(" Answer = @Answer , ");
            strSql.Append(" RoleID = @RoleID , ");
            strSql.Append(" UserGroup = @UserGroup , ");
            strSql.Append(" CreateTime = @CreateTime , ");
            strSql.Append(" LastLoginTime = @LastLoginTime , ");
            strSql.Append(" Status = @Status , ");
            strSql.Append(" IsOnline = @IsOnline , ");
            strSql.Append(" IsLimit = @IsLimit  ");
            strSql.Append(" where UserID=@UserID ");

            SqlParameter[] parameters =
            {
                new SqlParameter("@UserID",        SqlDbType.Int,         4),
                new SqlParameter("@UserName",      SqlDbType.NVarChar,  128),
                new SqlParameter("@Password",      SqlDbType.NVarChar,  128),
                new SqlParameter("@Email",         SqlDbType.NVarChar,  100),
                new SqlParameter("@Question",      SqlDbType.NVarChar,  100),
                new SqlParameter("@Answer",        SqlDbType.NVarChar,  100),
                new SqlParameter("@RoleID",        SqlDbType.Int,         4),
                new SqlParameter("@UserGroup",     SqlDbType.Int,         4),
                new SqlParameter("@CreateTime",    SqlDbType.DateTime),
                new SqlParameter("@LastLoginTime", SqlDbType.DateTime),
                new SqlParameter("@Status",        SqlDbType.Int,         4),
                new SqlParameter("@IsOnline",      SqlDbType.Bit,         1),
                new SqlParameter("@IsLimit",       SqlDbType.Bit, 1)
            };

            parameters[12].Value = entity.UserID;
            parameters[13].Value = entity.UserName;
            parameters[14].Value = entity.Password;
            parameters[15].Value = entity.Email;
            parameters[16].Value = entity.Question;
            parameters[17].Value = entity.Answer;
            parameters[18].Value = entity.RoleID;
            parameters[19].Value = entity.UserGroup;
            parameters[20].Value = entity.CreateTime;
            parameters[21].Value = entity.LastLoginTime;
            parameters[22].Value = entity.Status;
            parameters[23].Value = entity.IsOnline;
            parameters[24].Value = entity.IsLimit;
            int rows = SqlServerHelper.ExecuteSql(strSql.ToString(), parameters);

            if (rows > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #35
0
        /// <summary>
        /// 根据用户名得到用户对象实体
        /// </summary>
        public RedGlovePermission.Model.Users GetUserModel(string UserName)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("select  top 1 UserID,UserName,Password,Question,Answer,RoleID,UserGroup,CreateTime,LastLoginTime,Status,IsOnline,IsLimit from Users ");
            strSql.Append(" where UserName=@UserName ");
            SqlParameter[] parameters =
            {
                new SqlParameter("@UserName", SqlDbType.NVarChar, 128)
            };
            parameters[0].Value = UserName;

            RedGlovePermission.Model.Users model = new RedGlovePermission.Model.Users();
            DataSet ds = SqlServerHelper.Query(strSql.ToString(), parameters);

            if (ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["UserID"].ToString() != "")
                {
                    model.UserID = int.Parse(ds.Tables[0].Rows[0]["UserID"].ToString());
                }
                model.UserName = ds.Tables[0].Rows[0]["UserName"].ToString();
                model.Password = ds.Tables[0].Rows[0]["Password"].ToString();
                model.Question = ds.Tables[0].Rows[0]["Question"].ToString();
                model.Answer   = ds.Tables[0].Rows[0]["Answer"].ToString();
                if (ds.Tables[0].Rows[0]["RoleID"].ToString() != "")
                {
                    model.RoleID = int.Parse(ds.Tables[0].Rows[0]["RoleID"].ToString());
                }
                if (ds.Tables[0].Rows[0]["UserGroup"].ToString() != "")
                {
                    model.UserGroup = int.Parse(ds.Tables[0].Rows[0]["UserGroup"].ToString());
                }
                if (ds.Tables[0].Rows[0]["CreateTime"].ToString() != "")
                {
                    model.CreateTime = DateTime.Parse(ds.Tables[0].Rows[0]["CreateTime"].ToString());
                }
                if (ds.Tables[0].Rows[0]["LastLoginTime"].ToString() != "")
                {
                    model.LastLoginTime = DateTime.Parse(ds.Tables[0].Rows[0]["LastLoginTime"].ToString());
                }
                if (ds.Tables[0].Rows[0]["Status"].ToString() != "")
                {
                    model.Status = int.Parse(ds.Tables[0].Rows[0]["Status"].ToString());
                }
                if (ds.Tables[0].Rows[0]["IsOnline"].ToString() != "")
                {
                    if ((ds.Tables[0].Rows[0]["IsOnline"].ToString() == "1") || (ds.Tables[0].Rows[0]["IsOnline"].ToString().ToLower() == "true"))
                    {
                        model.IsOnline = true;
                    }
                    else
                    {
                        model.IsOnline = false;
                    }
                }
                if (ds.Tables[0].Rows[0]["IsLimit"].ToString() != "")
                {
                    if ((ds.Tables[0].Rows[0]["IsLimit"].ToString() == "1") || (ds.Tables[0].Rows[0]["IsLimit"].ToString().ToLower() == "true"))
                    {
                        model.IsLimit = true;
                    }
                    else
                    {
                        model.IsLimit = false;
                    }
                }
                return(model);
            }
            else
            {
                return(null);
            }
        }
Пример #36
0
 public Doctor_money_BLL(SqlServerHelper _helper) : base(_helper)
 {
     helper = _helper;
 }
 public HighPressureAgingDAO()
 {
     _sqlServerEq      = new SqlServerHelper();
     _sqlServerEq.conn = ConfigurationHelper.GetLocalConfigValue("HighVoltageDB");
 }
Пример #38
0
        public int Retrieve(login login)
        {
            int __rowsAffected = 1;

            // Create command
            using (SqlCommand sqlCommand = new SqlCommand("loginGet"))
            {
                // Set command type
                sqlCommand.CommandType = CommandType.StoredProcedure;

                try
                {
                    // Attach command
                    AttachCommand(sqlCommand);

                    // Add command parameters
                    SqlParameter vid = new SqlParameter("@id", SqlDbType.Int);
                    vid.Direction = ParameterDirection.InputOutput;
                    sqlCommand.Parameters.Add(vid);
                    SqlParameter vname = new SqlParameter("@name", SqlDbType.NVarChar, 50);
                    vname.Direction = ParameterDirection.Output;
                    sqlCommand.Parameters.Add(vname);
                    SqlParameter vemail = new SqlParameter("@email", SqlDbType.NVarChar, 50);
                    vemail.Direction = ParameterDirection.Output;
                    sqlCommand.Parameters.Add(vemail);
                    SqlParameter vpassword = new SqlParameter("@password", SqlDbType.NVarChar, 25);
                    vpassword.Direction = ParameterDirection.Output;
                    sqlCommand.Parameters.Add(vpassword);

                    // Set input parameter values
                    SqlServerHelper.SetParameterValue(vid, login.id);

                    // Execute command
                    sqlCommand.ExecuteNonQuery();

                    try
                    {
                        // Get output parameter values
                        login.id       = SqlServerHelper.ToInt32(vid);
                        login.name     = SqlServerHelper.ToString(vname);
                        login.email    = SqlServerHelper.ToString(vemail);
                        login.password = SqlServerHelper.ToString(vpassword);
                    }
                    catch (Exception ex)
                    {
                        if (ex is System.NullReferenceException)
                        {
                            __rowsAffected = 0;
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }
                finally
                {
                    // Detach command
                    DetachCommand(sqlCommand);
                }
            }

            return(__rowsAffected);
        }
        /// <summary>
        /// 根据公司的Guid返回唯一一条公司地址对象
        /// </summary>
        /// <param name="companyGuid"></param>
        /// <returns></returns>
        public CompanyAddress GetCompanyAddress(string companyGuid)
        {
            string sql = "select top 1 erpCode, ip from tblCompany where guid = '" + companyGuid +"'";

            return SqlServerHelper.GetEntity<CompanyAddress>(SqlServerHelper.baseConn(), sql);
        }
Пример #40
0
 public RentBll(SqlServerHelper _DB)
 {
     DB = _DB;
 }
Пример #41
0
 public NhCategoryDal(SqlServerHelper sqlServerHelper) : base(sqlServerHelper)
 {
     _sqlServerHelper = sqlServerHelper;
 }
Пример #42
0
        protected override void ExecuteMain()
        {
            try
            {
                this.Status = StepStatusEnum.Executing;

                Dictionary <string, DataStructure.Package <string, string> > packages = DataStructure.Package <string, string> .FromStringArray(
                    Properties.Settings.Default.BackedUpDatabasesWhenApplyingChanges.ToArray(), "\\");

                if (packages.Count > 0)
                {
                    int          success      = 0;
                    int          failed       = 0;
                    Impersonator impersonator = null;
                    string[]     parts        = Properties.Settings.Default.Environment.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (string server in packages.Keys)
                    {
                        if (parts[0].Equals("OneBox", StringComparison.InvariantCultureIgnoreCase) && parts.Length > 1 && parts[1].Equals(SqlServerHelper.ConnectionString.Server, StringComparison.InvariantCultureIgnoreCase))
                        {
                            impersonator = new Impersonator();
                        }

                        SqlServerHelper.ConnectionString.Server = server;
                        foreach (string bakInfo in packages[server].Items)
                        {
                            string database = bakInfo.Split(':')[0];
                            string bakFile  = bakInfo.Split(':')[1];

                            try
                            {
                                Log.Info("Restoring database {0} from {1} on server {2}...".FormatWith(database, bakFile, server));
                                if (SqlServerHelper.RestoreDatabase(database, bakFile))
                                {
                                    success++;
                                    Log.Info("Restored database {0} from {1} on server {2}.".FormatWith(database, bakFile, server));
                                }
                                else
                                {
                                    failed++;
                                    Log.Info("Restoring database {0} from {1} on server {2} failed!".FormatWith(database, bakFile, server));
                                }
                            }
                            catch
                            {
                                failed++;
                                continue;
                            }
                        }
                    }

                    if (impersonator != null)
                    {
                        impersonator.Undo();
                    }

                    if (failed == 0)
                    {
                        this.Status       = StepStatusEnum.Pass;
                        this.ResultDetail = new StepResultDetail("Rollback change groups succeded.");
                    }
                    else
                    {
                        throw new Exception("Restoring database status: success = {0}; failed = {1}".FormatWith(success, failed));
                    }
                }
                else
                {
                    this.Status       = StepStatusEnum.Cancelled;
                    this.ResultDetail = new StepResultDetail("Rollback change groups cancelled due to no bak files generated by ApplyChangeGroupsStep are found for RiMEConfig database. That means the ApplyChangeGroupStep may not have been run before this step.");
                }
            }
            catch (Exception ex)
            {
                this.Status       = StepStatusEnum.Failed;
                this.ResultDetail = new StepResultDetail("Error has occurred, please check log.", ExceptionHelper.CentralProcessSingle2(ex));
            }
            finally
            {
                if (this.ResultDetail != null)
                {
                    Log.Info(this.ResultDetail.Message);
                }
            }
        }