Наследование: IdentityDbContext
Пример #1
0
        protected string clearLine()
        {
            bool result = false;
            string line = Request.Form["line"];

            if (!string.IsNullOrEmpty(line) && line != "all")
            {
                using (DB db = new DB())
                {
                    List<DowntimeData> list = (from o in db.DowntimeDataSet
                                               where o.Client == "admin"
                                               && o.Line == line
                                               select o).ToList();

                    if (list.Count() > 0)
                    {
                        foreach (DowntimeData dt in list)
                        {
                            db.DeleteObject(dt);
                        }
                    }

                    result = db.SaveChanges() > 0;
                }
            }

            return result.ToString();
        }
Пример #2
0
    protected int DoUpdate(int finished)
    {
        int i = 0;
        using (SqlConnection conn = new DB().GetConnection())
        {
            string sql = "Update Shows set Title=@Title,Abs=@Abs,Catalog=@Catalog,CatalogID=@CatalogID,CoverPhotoURL=@CoverPhotoURL,CDT=@CDT,Status=@Status,Orders=@Orders,Finished=@Finished where ID=@ID";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@Title", TitleTB.Text);
            cmd.Parameters.AddWithValue("@Abs", AbsTextBox.Text);
            cmd.Parameters.AddWithValue("@Catalog", CatalogsDDL.SelectedItem.Text);
            cmd.Parameters.AddWithValue("@CatalogID", CatalogsDDL.SelectedValue);
            cmd.Parameters.AddWithValue("@CoverPhotoURL", CoverPhoto.ImageUrl);
            cmd.Parameters.AddWithValue("@CDT", CDT_TextBox.Text);
            // RoleID={1,Administrator},{2,Editor},{3,Contributor},{4,Author}
            int RoleID = Convert.ToInt16(Session["RoleID"].ToString());
            if (RoleID > 2)
            {
                cmd.Parameters.AddWithValue("@Status", 0); //状态:新投稿/待审核=0,审核已过=1,审核未过=2

            }
            else
            {
                cmd.Parameters.AddWithValue("@Status", 1); //状态:新投稿/待审核=0,审核已过=1,审核未过=2
            }
            cmd.Parameters.AddWithValue("@Orders", Orders.Text);
            cmd.Parameters.AddWithValue("@Finished", finished);
            cmd.Parameters.AddWithValue("@ID",IDLabel.Text);

            conn.Open();
            i = cmd.ExecuteNonQuery();
        }
        return i;
    }
Пример #3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int RoleID = Convert.ToInt16(Session["RoleID"].ToString());

            if (Session["RoleID"] == null || Session["UserID"] == null)
            {
                Util.ShowMessage("用户登录超时,请重新登录!", "Login2.aspx");
            }
            else if (RoleID > 1)
            {
                Util.ShowMessage("您没有访问该页面的权限!", "Login2.aspx");
            }
          else
          {
          UserName.Focus();
          using (SqlConnection conn = new DB().GetConnection())
          {
            string sql1 = "select * from Roles order by ID asc";
            SqlCommand cmd1 = new SqlCommand(sql1, conn);
            conn.Open();
            SqlDataReader rd1 = cmd1.ExecuteReader();
            Role.DataSource = rd1;
            Role.DataTextField = "RoleName";
            Role.DataValueField = "ID";
            Role.DataBind();
            rd1.Close();
          }
            }

        }
    }
Пример #4
0
 public string GetJobName(object jobskyerID)             //把jobskyerID转化为jobName输出
 {
     DB db = new DB();
     SqlDataReader dr = db.reDr("SELECT jobName FROM jobskyer WHERE jobskyerID='" + jobskyerID + "'");
     dr.Read();
     return dr.GetValue(0).ToString();
 }
Пример #5
0
    //在数据表Resources插入一条记录操作
    protected bool InsertDataBase()
    {
        bool result = false;

        using (SqlConnection conn = new DB().GetConnection())
        {
            //向resources插入一条记录操作
            StringBuilder sb = new StringBuilder("Insert into Resources (ResourceName,FileName,FilePath,FileSizeInKB,FileType,Extentsion,FolderID,FolderName,UserID,CDT,Status,UserName)");
            sb.Append(" values(@ResourceName,@FileName,@FilePath,@FileSize,@FileType,@Extentsion,@FolderID,@FolderName,@UserID,@CDT,@Status,@UserName)");
            SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
            //cmd.Parameters.AddWithValue("@ResourceName", TextBox1.Text);
            cmd.Parameters.AddWithValue("@ResourceName", TextBox1.Text.Trim());
            cmd.Parameters.AddWithValue("@FileName", FN.Text);
            cmd.Parameters.AddWithValue("@FilePath", FP.Text);
            cmd.Parameters.AddWithValue("@FileSize", FS.Text);
            cmd.Parameters.AddWithValue("@FileType", ResourceTypeLabel.Text);
            cmd.Parameters.AddWithValue("@Extentsion", FET.Text);
            cmd.Parameters.AddWithValue("@FolderID", 0);
            cmd.Parameters.AddWithValue("@FolderName", "");
            cmd.Parameters.AddWithValue("@UserID", Session["UserID"].ToString());
            cmd.Parameters.AddWithValue("@UserName", Session["UserName"].ToString());
            cmd.Parameters.AddWithValue("@CDT", DateTime.Now);
            cmd.Parameters.AddWithValue("@Status", 0);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
            //插入成功
            result = true;
        }
        return result;
    }
Пример #6
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        int i = 0;
        using (SqlConnection conn = new DB().GetConnection())
        {
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "Delete from SubMenu where ID in (" + IDSLabel.Text + ") ";
            conn.Open();
            i = cmd.ExecuteNonQuery();
            cmd.Dispose();

            cmd.CommandText = "select * from SubMenu where ID in (" + IDSLabel.Text + ") order by ID desc";
            SqlDataReader rd = cmd.ExecuteReader();
            GridView1.DataSource = rd;
            GridView1.DataBind();
            rd.Close();
            conn.Close();

        }
        if (i > 0)
        {
            ResultLabel.Text = "成功删除!";
            ResultLabel.ForeColor = System.Drawing.Color.Green;

        }
        else
        {
            ResultLabel.Text = "操作失败,请重试!";
            ResultLabel.ForeColor = System.Drawing.Color.Red;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["username"] == null)
        {
            Response.Write("<script>alert('用户登录超时,请重新登录。');location='../Default.aspx'</script>");
            return;
        } 
        DB  db=new DB();
       
        if (teacherName.Text == "")
        {


            this.GridView1.Visible =false;
            this.GridView2.Visible = true;
        }
        else
        {
         
            this.GridView1.Visible = true;
            this.GridView2.Visible = false;
        }


    }
		/**
		 * Fetches info needed from the database.
		 */
		private RevisionWorkInfo getWorkInfo(DB db, int revisionWorkID, int workID) {
			using (var cmd = db.CreateCommand ()) {
				cmd.CommandText = @"
					SELECT revision.revision, lane.id, lane.repository, lane.lane
					FROM revisionwork
					INNER JOIN revision ON revision.id = revisionwork.revision_id
					INNER JOIN lane ON lane.id = revision.lane_id
					WHERE revisionwork.id = @rwID;

					SELECT command.command
					FROM work
					INNER JOIN command ON command.id = work.command_id
					WHERE work.id = @wID
				";
				DB.CreateParameter (cmd, "rwID", revisionWorkID);
				DB.CreateParameter (cmd, "wID", workID);
				using (var reader = cmd.ExecuteReader ()) {
					RevisionWorkInfo info;

					reader.Read ();

					info.hash = reader.GetString (0);
					info.laneID = reader.GetInt32 (1);
					info.repoURL = reader.GetString (2);
					info.laneName = reader.GetString (3);

					reader.NextResult ();
					reader.Read ();

					info.command = reader.GetString (0);

					return info;
				}
			}
		}
Пример #9
0
    // 判断fileextension是否合法
    protected bool CheckExtension(string extension)
    {
        bool result = false;
        // 如果Dictionary的键值数<1,即没有元素,则先读取数据表
        if (ResourceTypes.Keys.Count < 1)
        {
            using (SqlConnection conn = new DB().GetConnection())
            {
                SqlDataReader rd;
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "select * from ResourceTypes";
                conn.Open();
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    ResourceTypes.Add(rd["Extension"].ToString(), rd["TypeName"].ToString());
                }
                rd.Close();
                conn.Close();
            }

        }
        // 判断是否含有指定的后缀名
        if (ResourceTypes.ContainsKey(extension))
        {
            result = true;
            ResourceTypeLabel.Text = ResourceTypes[extension];
        }
        return result;
    }
Пример #10
0
        public bool Save(DB.Stru.福利中心.老人费用退费管理 stru)
        {
            string strID =  Orm.Save(stru);
            stru.ID = strID;

            return ! String.IsNullOrEmpty(strID);
        }
        private void Get_Attendence_Info()
        {
            try
            {
                DB db2 = new DB("Attendence");

                db2.SelectedColumns.Add("*");

                db2.AddCondition("Att_id", Attendence_Id);

                DataRow DR = db2.SelectRow();

                Employees_CB.SelectedValue = DR["att_emp_id"];

                Date_DTP.Value = DateTime.Parse(DR["att_date"].ToString());

                Attend_DTP.Value = new DateTime(TimeSpan.Parse(DR["att_attend"].ToString()).Ticks);

                Leave_DTP.Value = DR["att_leave"].ToString() != "" ? new DateTime(TimeSpan.Parse(DR["att_leave"].ToString()).Ticks) : Leave_DTP.Value;

            }
            catch
            {


            }
        }
 public bool Update_DutyTime()///如果选择了安排过值班的人,就更新值班安排数据
 {
     DB db = new DB();
     string dutyInTime = chooseWeekday.SelectedValue + chooseSignInTime.SelectedValue;
     string dutyOutTime = chooseWeekday.SelectedValue + chooseSignOutTime.SelectedValue;
     string str = "UPDATE dutyTimeTable SET dutyInTime=@dutyInTime,dutyOutTime=@dutyOutTime WHERE jobskyerID=@jobskyerID";
     SqlConnection con = new SqlConnection();
     con = db.GetCon();
     SqlCommand com = new SqlCommand(str, con);
     com.Parameters.Add("@dutyInTime", SqlDbType.DateTime, 0).Value = dutyInTime;
     com.Parameters.Add("@dutyOutTime", SqlDbType.DateTime, 0).Value = dutyOutTime;
     com.Parameters.Add("@jobskyerID", SqlDbType.DateTime, 0).Value = chooseName.SelectedValue;
     try
     {
         com.ExecuteNonQuery();
         Sign_Result.Text = "更新值班成功!";
     }
     catch (Exception ex)
     {
         Sign_Result.Text = "更新值班失败!";
         return false;
     }
     finally
     {
         com.Dispose();
         con.Close();
     }
     return true;
 }
    public int year(string student_ID)
    {
        //
        //获取学生毕业学年
        //
        DB db = new DB();
        string selec = "select * from student where student_ID='" + student_ID + "'";
        DataSet ds = db.Select(selec, db.DBconn());
        int year;
        try
        {
            //如果读取到数据并装载数据
            string grade = ds.Tables[0].Rows[0][15].ToString();
            year = Convert.ToInt32(grade) + 4;


        }
        catch
        {
            year = DateTime.Now.Year;
        }
        finally
        {
            ds.Clear();
        }
       
        return year;

    }
 protected void confirm_Click(object sender, EventArgs e)///首先判断该人员是否已经安排过值班
 {
     DB db = new DB();
     string str = "SELECT jobskyerID FROM dutyTimeTable";
     string jobskyerID = chooseName.SelectedValue;
     SqlConnection con = new SqlConnection();
     con = db.GetCon();
     SqlCommand com = new SqlCommand(str, con);
     SqlDataAdapter da = new SqlDataAdapter(com);
     DataSet ds = new DataSet();
     da.Fill(ds);
     ///SqlDataReader dr = com.ExecuteReader();
     int k = ds.Tables[0].Rows.Count;
     for (int i = 0; i < k; ++i)
     {
         if (jobskyerID == ds.Tables[0].Rows[i]["jobskyerID"].ToString())
         {
             Update_DutyTime();
         }
         if (i == k)
         {
             Insert_DutyTime();
         }
     }
 }
 public bool Insert_DutyTime()///如果选择了没有安排过值班的人,就插入值班安排数据
 {
     string dutyInTime = chooseWeekday.SelectedValue + chooseSignInTime.SelectedValue;
     string dutyOutTime = chooseWeekday.SelectedValue + chooseSignOutTime.SelectedValue;
     string InsertStr = "INSERT INTO dutyTimeTable(dutyInTime,dutyOutTime,jobskyerID)VALUES(@dutyInTime,@dutyOutTime,@jobskyerID)";
     DB db = new DB();
     SqlConnection con = new SqlConnection();
     con = db.GetCon();
     con.Open();
     SqlCommand com = new SqlCommand(InsertStr, con);
     com.Parameters.Add("@dutyInTime", SqlDbType.DateTime, 0).Value = Convert.ToDateTime(dutyInTime);
     com.Parameters.Add("@dutyOutTime", SqlDbType.DateTime, 0).Value = Convert.ToDateTime(dutyOutTime);
     com.Parameters.Add("@jobskyerID", SqlDbType.NChar, 0).Value = chooseName.SelectedValue;
     try
     {
         com.ExecuteNonQuery();
         Sign_Result.Text = "安排值班成功!";
     }
     catch (Exception ex)
     {
         Sign_Result.Text = "安排值班失败!";
         return false;
     }
     finally
     {
         com.Dispose();
         con.Close();
     }
     return true;
 }
Пример #16
0
    public bool ScoreRankList_Bind()///下拉列表绑定数据
    {
        DB db = new DB();
        string sql_game = "SELECT * FROM GAME ";
        SqlConnection con = new SqlConnection();
        con = db.GetCon();
        con.Open();
        SqlCommand cmd = new SqlCommand(sql_game, con);
        SqlDataReader sqlRead_Game = cmd.ExecuteReader();
        try
        {
            ScoreRankList.DataSource = sqlRead_Game;
            ScoreRankList.DataTextField = "gamName";
            ScoreRankList.DataValueField = "gameID";
            ScoreRankList.DataBind();
            ScoreRankList.Items.Add(new ListItem("请选择","-1"));
            ScoreRankList.SelectedValue = "-1";

        }
        catch (Exception ex)
        {
            return false;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
        }
        return true;
    }
Пример #17
0
 public bool ScoreRank_Bind()///分数排行绑定数据
 {
     DB db = new DB();
     string scoreRankstr = "SELECT GAME_RECORD.jobskyerID,gamScore,jobName FROM GAME_RECORD,JOBSKYER WHERE GAME_RECORD.jobskyerID=JOBSKYER.jobskyerID ORDER BY gamScore desc";
     SqlConnection con = new SqlConnection();
     con = db.GetCon();
     con.Open();
     SqlCommand com = new SqlCommand(scoreRankstr, con);
     SqlDataReader dr = com.ExecuteReader();
     try
     {
         ScoreRank.DataSource = dr;
         ScoreRank.DataBind();
     }  
     catch(Exception ex)
     {
         return false;
     }  
     finally
     {
         com.Dispose();
         con.Close();
     }
     return true;
 }
Пример #18
0
 public int SelectMyScore(string username, string gameID)
 {
     int myscore = 0;
     SqlConnection conn = new SqlConnection();
     string sqlstr = "select gamScore from GAME_RECORD where jobskyerID ='" + username + "' and gameID='" + gameID + "' ";
     DB db = new DB();
     conn = db.GetCon();
     conn.Open();
     SqlCommand cmd = new SqlCommand(sqlstr, conn);
     try
     {
         myscore=Int32.Parse(cmd.ExecuteScalar().ToString());
         return myscore;//获取个人纪录并返回
     }
     catch (Exception ex)
     {
         return 0;
     }
     finally
     {
         cmd.Dispose();
         conn.Close();
     }
     //return myscore;
 }
Пример #19
0
    public static string GetConfig(string param_name)
    {
        DB db = new DB();
        db.Connect ();

        string sqlQuery = "SELECT valor FROM configuraciones WHERE evento_id = "+Evento.GetActivoID()+" AND denominacion = '"+param_name+"'";
        db.dbcmd.CommandText = sqlQuery;
        db.reader = db.dbcmd.ExecuteReader();
        string value = "";
        while (db.reader.Read()) {
            if(!db.reader.IsDBNull(0)){
                value = db.reader.GetString(0);
            }
        }
        db.reader.Close();

        if (value == "") {
            sqlQuery = "SELECT valor FROM configuraciones WHERE evento_id = 0 AND denominacion = '"+param_name+"'";
            db.dbcmd.CommandText = sqlQuery;
            db.reader = db.dbcmd.ExecuteReader();
            while (db.reader.Read()) {
                value = db.reader.GetString(0);
            }
            db.reader.Close();
        }

        db.reader = null;
        db.Disconnect ();

        return value;
    }
Пример #20
0
        public Menu(int UserID)
        {
            Size MinButtonSize = new System.Drawing.Size(290, 30);

            InitializeComponent();
            if (UserID <= 0)
            {
                Login l = new Login();
                l.Show();
                this.Hide();
            }
            else
            {
                _userID = UserID;

                DB db = new DB();
                db.AddParam("@UserID", UserID);
                DataTable dtMenu = db.SQLResults("usp_MenuGet");

                foreach (DataRow dr in dtMenu.Rows)
                {
                    Button btn = new Button();
                    btn.AutoSize = true;
                    btn.BackColor = Color.Azure;
                    btn.MinimumSize = MinButtonSize;
                    btn.Text = dr["DisplayName"].ToString();
                    btn.Name = dr["MenuID"].ToString();
                    btn.Margin = new Padding(3,0,0,0);
                    btn.Click += new EventHandler(btnMenu_Click);

                    flpMenu.Controls.Add(btn);
                }
            }
        }
Пример #21
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (State == null || State.Count <= 2) { Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "timeOut('../Default.aspx');", true); return; }

        DB db = new DB();
        string sql = "SELECT * FROM stock_images WHERE ";
        if (State["SelectedAppType"].ToString() == Constants.WEB_APP_TYPE || State["SelectedAppType"].ToString() == Constants.HYBRID_APP_TYPE)
            sql += "type='jquery_buttons' or type='blank_buttons'";
        else
            sql += "type='blank_buttons'";
        DataRow[] rows = db.ViziAppsExecuteSql(State, sql);
        DataSet paramsDS = new DataSet("ParameterDataSet");
        DataTable paramTable = paramsDS.Tables.Add("ParamTable");
        DataColumn paramCol = paramTable.Columns.Add("image_url", typeof(String));

        foreach (DataRow row in rows)
        {
            string type = row["type"].ToString();
            string url = row["image_url"].ToString();

            DataRow paramRow = paramTable.NewRow();
            string[] row_array = new string[1];
            row_array[0] = url;
            paramRow.ItemArray = row_array;
            paramTable.Rows.Add(paramRow);
        }

        ParamRepeater.DataSource = paramsDS;
        ParamRepeater.DataBind();
        db.CloseViziAppsDatabase((Hashtable)HttpRuntime.Cache[Session.SessionID]);
    }
Пример #22
0
    void ProcessResponse(string response)
    {
        if (response != "[]") {
            response = response.Trim (new Char[] { '{', '}' });
            string[] response_exploded = response.Split (',');

            DB db = new DB ();
            db.Connect ();

            foreach (string pair in response_exploded) {
                string[] key_value = pair.Split (':');
                string ext_id = key_value [1].Trim (new Char[]{'"'});
                string id = key_value [0].Trim (new Char[]{'"'});
                string query = "UPDATE participantes SET external_id = " + ext_id + " WHERE id = " + id;
                db.dbcmd.CommandText = query;
                if (db.dbcmd.ExecuteNonQuery () == 1) {
                    Debug.Log ("Exportado participante id local " + id + " a la id externa " + ext_id);
                }
            }

            db.Disconnect ();
        } else {
            Debug.Log ("No se exportó ningun participante nuevo");
        }

        GameObject.Find ("Button Export").GetComponent<Button> ().interactable = true;
    }
        public void SetData( DB.Stru.优抚科.优抚对象.伤残人员.基本信息 stru )
        {
            txt行政区划.Text = stru.行政区划;
            txt身份证号码.Text = stru.身份证号码 ;
            dat出生日期.strDate = stru.出生日期 ;
            cmb伤残等级.Text = stru.伤残等级 ;
            cmb伤残属别.Text = stru.伤残属别 ;
            dat参加工作时间.Text = stru.入伍时间 ;
            cmb劳动能力.Text = stru.劳动能力 ;
            cmb就业情况.Text = stru.就业情况 ;
            cmb户口簿住址类别.Text = stru.户口簿住址类别 ;

            txt姓名.Text = stru.姓名;
            cmb民族.Text = stru.民族;
            cmb性别.Text = stru.性别 ;
            cmb伤残性质.Text = stru.伤残性质;
            cmb婚姻状况.Text = stru.婚姻状况;
            dat退伍时间.strDate = stru.退伍时间 ;
            cmb生活能力.Text = stru.生活能力 ;
            cmb户口类别.Text = stru.户口类别 ;
            txt联系电话.Text = stru.联系电话 ;

            txt工作单位.Text = stru.工作单位 ;
            txt户口簿地址.Text = stru.户口簿住址 ;
            txt实际居住地地址.Text = stru.实际居住地址 ;
            txt备注.Text = stru.备注 ;
        }
        public bool GetData( ref DB.Stru.优抚科.优抚对象.伤残人员.基本信息 stru )
        {
            if ( !CheckBeforeSave() )
                return false;

            stru.行政区划 = txt行政区划.Text.Trim();
            stru.身份证号码 = txt身份证号码.Text.Trim();
            stru.出生日期 = dat出生日期.strDate;
            stru.伤残等级 = cmb伤残等级.Text.Trim();
            stru.伤残属别 = cmb伤残属别.Text.Trim();
            stru.入伍时间 = dat参加工作时间.Text.Trim();
            stru.劳动能力 = cmb劳动能力.Text.Trim();
            stru.就业情况 = cmb就业情况.Text.Trim();
            stru.户口簿住址类别 = cmb户口簿住址类别.Text.Trim();

            stru.姓名 = txt姓名.Text.Trim();
            stru.民族 = cmb民族.Text.Trim();
            stru.性别 = cmb性别.Text.Trim();
            stru.伤残性质 = cmb伤残性质.Text.Trim();
            stru.婚姻状况 = cmb婚姻状况.Text.Trim();
            stru.退伍时间 = dat退伍时间.strDate;
            stru.生活能力 = cmb生活能力.Text.Trim();
            stru.户口类别 = cmb户口类别.Text.Trim();
            stru.联系电话 = txt联系电话.Text.Trim();

            stru.工作单位 = txt工作单位.Text.Trim();
            stru.户口簿住址 = txt户口簿地址.Text.Trim();
            stru.实际居住地址 = txt实际居住地地址.Text.Trim();
            stru.备注 = txt备注.Text.Trim();

            return true;
        }
Пример #25
0
        private bool Add_Update()
        {
            try
            {

                DB DataBase = new DB("Categories");

                DataBase.AddColumn("cat_name", Category_TB.Text.Trim());

                if(Category_Id == null)
                {
                    if(DataBase.IsNotExist("cat_id", "cat_name"))
                    {
                        return Confirm.Check(DataBase.Insert());
                    }
                    else
                    {
                        Message.Show("لقد تم تسجيل هذه الفئة من قبل", MessageBoxButton.OK, 5);
                        return false;
                    }


                }
                else
                {
                    DataBase.AddCondition("cat_id", this.Category_Id);
                    return Confirm.Check(DataBase.Update());
                }
            }
            catch
            {
                //MessageBox.Show("kiki_method");
                return false;
            }
        }
Пример #26
0
 public bool SelectScore(string username,string gameID){
     SqlConnection conn = new SqlConnection();
     string sqlstr = "select count(*) from GAME_RECORD where jobskyerID ='" + username + "' and gameID='" + gameID + "' ";
     DB db = new DB();
     conn = db.GetCon();
     conn.Open();
     SqlCommand cmd = new SqlCommand(sqlstr, conn);
     try
     {
         if (Int32.Parse( cmd.ExecuteScalar().ToString()) == 0)
         {
             return false;
         }
     }
     catch (Exception ex)
     {
         return false;
     }
     finally
     {
         cmd.Dispose();
         conn.Close();
     }
     return true;//本来就有记录,就返回true
 }
Пример #27
0
 public static int SInsert(string sql, params object[] parameter)
 {
     using (DB db = new DB())
     {
         return db.Insert(sql, parameter);
     }
 }
        public bool Save(DB.Stru.事务科.专项救助_低保边缘户 stru)
        {
            string strID =  Orm.Save(stru);
            stru.ID = strID;

            return ! String.IsNullOrEmpty(strID);
        }
Пример #29
0
 public static object SExecuteScalar(string sql, params object[] parameter)
 {
     using (DB db = new DB())
     {
         return db.ExecuteScalar(sql, parameter);
     }
 }
Пример #30
0
 public static List<object[]> SExecuteReader(string sql, params object[] parameter)
 {
     using (DB db = new DB())
     {
         return db.ExecuteReader(sql, parameter);
     }
 }
Пример #31
0
		/// <exception cref="System.IO.IOException"/>
		protected internal override void StartStorage()
		{
			Path storeRoot = CreateStorageDir(GetConfig());
			Options options = new Options();
			options.CreateIfMissing(false);
			options.Logger(new HistoryServerLeveldbStateStoreService.LeveldbLogger());
			Log.Info("Using state database at " + storeRoot + " for recovery");
			FilePath dbfile = new FilePath(storeRoot.ToString());
			try
			{
				db = JniDBFactory.factory.Open(dbfile, options);
			}
			catch (NativeDB.DBException e)
			{
				if (e.IsNotFound() || e.Message.Contains(" does not exist "))
				{
					Log.Info("Creating state database at " + dbfile);
					options.CreateIfMissing(true);
					try
					{
						db = JniDBFactory.factory.Open(dbfile, options);
						// store version
						StoreVersion();
					}
					catch (DBException dbErr)
					{
						throw new IOException(dbErr.Message, dbErr);
					}
				}
				else
				{
					throw;
				}
			}
			CheckVersion();
		}
Пример #32
0
        public static bool ModulYetkileri(int fkKullanicilar, string Kod)
        {
            string sql = @"select m.ModulAdi,my.Yetki from Moduller m with(nolock) 
            left join ModullerYetki  my with(nolock) on my.Kod=m.Kod
            where fkKullanicilar=" + fkKullanicilar + " and m.Kod='" + Kod + "'";

            DataTable dt = DB.GetData(sql);

            if (dt.Rows.Count == 0)
            {
                return(false);
            }
            else
            {
                if (dt.Rows[0]["Yetki"].ToString() == "0")
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
        }
Пример #33
0
        // Reduce hp of the deck card in database, maybe also update the object
        public void TakeDamage(int damageAmount)
        {
            this.HP -= damageAmount;
            if (this.HP < 0)
            {
                this.HP = 0;
            }

            SqlConnection conn = DB.Connection();

            conn.Open();

            SqlCommand cmd = new SqlCommand("UPDATE decks SET HP = @DeckHP WHERE id = @DeckId;", conn);

            cmd.Parameters.AddWithValue("@DeckHP", this.HP);
            cmd.Parameters.AddWithValue("@DeckId", this.Id);

            cmd.ExecuteNonQuery();

            if (conn != null)
            {
                conn.Close();
            }
        }
Пример #34
0
        public List <Flight> GetFlights()
        {
            SqlConnection conn = DB.Connection();

            conn.Open();

            SqlCommand   cmd         = new SqlCommand("SELECT flight_id FROM flights_cities WHERE city_id = @CityId;", conn);
            SqlParameter cityIdParam = new SqlParameter("@CityId", this.GetId());

            cmd.Parameters.Add(cityIdParam);

            SqlDataReader rdr = cmd.ExecuteReader();

            List <int> flightIds = new List <int> {
            };

            while (rdr.Read())
            {
                int flightId = rdr.GetInt32(0)
                               flightIds.Add(flightId);
            }
            if (rdr != null)
            {
                rdr.Close();
            }

            List <Flight> FlightList = new List <Flight> {
            };

            foreach (int flightId in flightIds)
            {
                SqlCommand flightQuery = new SqlCommand("SELECT * FROM flights WHERE id = @FlightId;", conn);

                SqlParameter flightIdParam = SqlParameter
            }
        }
Пример #35
0
        /**
         *  Get Material Allocations from shipment which is not returned
         *	@param ctx context
         *	@param M_InOutLine_ID line
         *	@param trxName trx
         *	@return allocations
         */
        public static MInOutLineMA[] getNonReturned(Ctx ctx, int M_InOutLine_ID, Trx trxName)
        {
            List <MInOutLineMA> list = new List <MInOutLineMA>();
            String  sql = "SELECT * FROM M_InOutLineMA WHERE M_InOutLine_ID=" + M_InOutLine_ID + " ORDER BY MMPolicyDate ASC";
            DataSet ds  = null;

            try
            {
                ds = DB.ExecuteDataset(sql, null, trxName);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow dr = ds.Tables[0].Rows[i];
                    list.Add(new MInOutLineMA(ctx, dr, trxName));
                }
                ds = null;
            }
            catch (Exception e)
            {
                _log.Log(Level.SEVERE, sql, e);
            }
            MInOutLineMA[] retValue = new MInOutLineMA[list.Count];
            retValue = list.ToArray();
            return(retValue);
        }
Пример #36
0
        public static List <Deck> GetAll()
        {
            SqlConnection conn = DB.Connection();

            conn.Open();

            SqlCommand cmd = new SqlCommand("SELECT * FROM decks;", conn);

            SqlDataReader rdr = cmd.ExecuteReader();

            List <Deck> wholeDecks = new List <Deck> {
            };

            while (rdr.Read())
            {
                int  deckId       = rdr.GetInt32(0);
                int  deckCardId   = rdr.GetInt32(1);
                int  deckPlayerId = rdr.GetInt32(2);
                bool deckInHand   = rdr.GetBoolean(3);
                bool deckInPlay   = rdr.GetBoolean(4);
                bool deckDiscard  = rdr.GetBoolean(5);
                int  deckHP       = rdr.GetInt32(6);

                Deck newDeck = new Deck(deckCardId, deckPlayerId, deckHP, deckInHand, deckInPlay, deckDiscard, deckId);
                wholeDecks.Add(newDeck);
            }
            if (rdr != null)
            {
                rdr.Close();
            }
            if (conn != null)
            {
                conn.Close();
            }
            return(wholeDecks);
        }
Пример #37
0
        /// <summary>
        /// Protected method to nullify a foreign key
        /// </summary>
        /// <param name="dbp">Secondary DB Handle</param>
        /// <param name="keyp">Primary Key</param>
        /// <param name="datap">Primary Data</param>
        /// <param name="fkeyp">Foreign Key</param>
        /// <param name="changed">Whether the foreign key has changed</param>
        /// <returns>0 on success, !0 on failure</returns>
        protected static int doNullify(IntPtr dbp,
                                       IntPtr keyp, IntPtr datap, IntPtr fkeyp, ref int changed)
        {
            DB  db   = new DB(dbp, false);
            DBT key  = new DBT(keyp, false);
            DBT data = new DBT(datap, false);
            DBT fkey = new DBT(fkeyp, false);

            DatabaseEntry d = ((SecondaryDatabase)db.api_internal).Nullifier(
                DatabaseEntry.fromDBT(key),
                DatabaseEntry.fromDBT(data), DatabaseEntry.fromDBT(fkey));

            if (d == null)
            {
                changed = 0;
            }
            else
            {
                changed   = 1;
                data.data = d.Data;
            }

            return(0);
        }
Пример #38
0
 protected void _Save(object sender, EventArgs e)
 {
     this.xQueryParameters.Clear();
     this.xQueryValues.Clear();
     this.xQueryParameters.Add((object)"@RECORDID");
     this.xQueryValues.Add((object)this.RECORDID);
     this.xQueryParameters.Add((object)"@ESTATUS");
     this.xQueryValues.Add((object)this.ESTATUS);
     this.xQueryParameters.Add((object)"@MOTIVOESTATUS");
     this.xQueryValues.Add((object)this.MOTIVOESTATUS);
     this.xQueryParameters.Add((object)"@ROWGUID");
     this.xQueryValues.Add((object)this.ROWGUID);
     this.xQueryParameters.Add((object)"@ROWUSERID");
     this.xQueryValues.Add((object)this.ROWUSERID);
     this.xQueryParameters.Add((object)"@ROWSGXID");
     this.xQueryValues.Add((object)this.ROWSGXID);
     this.xQuery = this.xBase + "SI";
     if (!DB.ExecuteNonQuery(this.xQuery, this.xQueryParameters, this.xQueryValues, CommandType.StoredProcedure))
     {
         return;
     }
     ((Site_Master)this.Master)._Notify("Estatus actualizado!");
     this._Show((object)null, (EventArgs)null);
 }
Пример #39
0
//============================================
        public void Save()
        {
            SqlConnection conn = DB.Connection();

            conn.Open();

            SqlCommand cmd = new SqlCommand("INSERT INTO clients (name, stylist_id) OUTPUT INSERTED.id VALUES (@ClientName, @ClientStylistId);", conn);

            SqlParameter nameParameter = new SqlParameter();

            nameParameter.ParameterName = "@ClientName";
            nameParameter.Value         = this.GetName();

            SqlParameter stylistIdParameter = new SqlParameter();

            stylistIdParameter.ParameterName = "@ClientStylistId";
            stylistIdParameter.Value         = this.GetStylistId();

            cmd.Parameters.Add(nameParameter);
            cmd.Parameters.Add(stylistIdParameter);

            SqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                this._id = rdr.GetInt32(0);
            }
            if (rdr != null)
            {
                rdr.Close();
            }
            if (conn != null)
            {
                conn.Close();
            }
        }
Пример #40
0
    public void pagebind()
    {
        string          ContId  = Request["ContId"];
        int             curpage = Convert.ToInt32(this.lblPage.Text);
        PagedDataSource ps      = new PagedDataSource();
        SqlConnection   con     = DB.createDB();

        con.Open();
        SqlDataAdapter sda = new SqlDataAdapter("select a.*,b.* from tb_Users as a join tb_hf as b on a.UserName=b.hfname where b.ContId='" + ContId + "'", con);
        DataSet        ds  = new DataSet();

        sda.Fill(ds, "tb_hf");
        ps.DataSource           = ds.Tables["tb_hf"].DefaultView;
        ps.AllowPaging          = true;
        ps.PageSize             = 2;
        ps.CurrentPageIndex     = curpage - 1;
        this.lnkbtnUp.Enabled   = true;
        this.lnkbtnNext.Enabled = true;
        this.lnkbtnLast.Enabled = true;
        this.lnkbtnOne.Enabled  = true;
        if (curpage == 1)
        {
            this.lnkbtnOne.Enabled = false; //不显示第一页按钮
            this.lnkbtnUp.Enabled  = false; //不显示上一页按钮
        }
        if (curpage == ps.PageCount)
        {
            this.lnkbtnNext.Enabled = false; //不显示下一页
            this.lnkbtnLast.Enabled = false; //不显示最后一页
        }
        this.lblBackPage.Text       = Convert.ToString(ps.PageCount);
        this.DataList2.DataSource   = ps;
        this.DataList2.DataKeyField = "hfId";
        this.DataList2.DataBind();
        con.Close();
    }
Пример #41
0
        public object Active(string id,string isactive)
        {
            object rtn = null;

            id = ComFunc.nvl(id);
            isactive = ComFunc.nvl(isactive);
            BeginTrans();
            var up = DB.NewDefaultDBUnitParameter<SqliteAccess>();
            UnitDataCollection re = DB.Excute(up, FrameDLRObject.CreateInstanceFromat(@"{
$acttype : 'Query',
$table : 'LoginInfo',
$where : {
		LoginID:{0}
}
}", id));
            if (IsValidBy("账号不存在", () => re.QueryTable.RowLength > 0))
            {
                DB.Excute(up, FrameDLRObject.CreateInstanceFromat(@"{
$acttype : 'Update',
$table : 'LoginInfo',
IsActive:{1},
$where:{
    LoginID:{0}
}
}", id, isactive.ToLower()=="true"?"true":"false"));

                rtn = new
                {
                    id = id
                };

            }
            CommitTrans();
            SetRefreshCacheRoute($"/user/{id}");
            return rtn;
        }
Пример #42
0
//============================================
        public static Client Find(int id)
        {
            SqlConnection conn = DB.Connection();

            conn.Open();

            SqlCommand   cmd = new SqlCommand("SELECT * FROM clients WHERE id = @clientId;", conn);
            SqlParameter clientIdParameter = new SqlParameter();

            clientIdParameter.ParameterName = "@clientId";
            clientIdParameter.Value         = id.ToString();
            cmd.Parameters.Add(clientIdParameter);
            SqlDataReader rdr = cmd.ExecuteReader();

            int    foundClientId        = 0;
            string foundClientName      = null;
            int    foundClientStylistId = 0;

            while (rdr.Read())
            {
                foundClientId        = rdr.GetInt32(0);
                foundClientName      = rdr.GetString(1);
                foundClientStylistId = rdr.GetInt32(2);
            }
            Client foundClient = new Client(foundClientName, foundClientStylistId, foundClientId);

            if (rdr != null)
            {
                rdr.Close();
            }
            if (conn != null)
            {
                conn.Close();
            }
            return(foundClient);
        }
Пример #43
0
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                string Images = string.Empty;
                Images = ToBase64(Request.Files["images"]);

                var db  = new DB();
                var Sql = db.Category.SingleOrDefault(x => x.Id == id);
                if (Images != string.Empty)
                {
                    Sql.image  = Sql.category_num + ".png";
                    Sql.images = Images;
                }

                UpdateModel(Sql, collection.ToValueProvider());
                db.SubmitChanges();
                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Пример #44
0
        public bool Login(LoginInfo LoginInfo)
        {
            bool result = false;

            if (SYS_MODEL == SysModel.T8)
            {
                string f1 = @"SELECT TOP 1 
	                                compno,
	                                usr,
	                                name
                                FROM TbrSystem.dbo.PSWD 
                                Where compno='{0}' and UPPER(usr)=UPPER('{1}') and PWD_GAO='{2}' ";

                var list = DB.SqlQueryable <EmployeeModel>(f1.FormatOrg(LoginInfo.db_no,
                                                                        LoginInfo.username, ToPassWordMD5(LoginInfo.password))).ToList();
                result = list.Count > 0;
            }
            else
            {
                result = false;
            }

            return(result);
        }
Пример #45
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        int i = 0;

        using (SqlConnection conn = new DB().GetConnection())
        {
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "Delete from ArticleTags where ID in (" + IDSLabel.Text + ") ";
            SqlCommand cmd1 = conn.CreateCommand();
            cmd1.CommandText = "Delete from Articles_ArticleTags where ArticleTagID in (" + IDSLabel.Text + ") ";


            conn.Open();
            cmd1.ExecuteNonQuery();
            i = cmd.ExecuteNonQuery();
            cmd.Dispose();
            cmd1.Dispose();

            cmd.CommandText = "select * from ArticleTags where ID in (" + IDSLabel.Text + ") order by ID desc";
            SqlDataReader rd = cmd.ExecuteReader();
            GridView1.DataSource = rd;
            GridView1.DataBind();
            rd.Close();
            conn.Close();
        }
        if (i > 0)
        {
            ResultLabel.Text      = "成功删除" + i + "个标签!";
            ResultLabel.ForeColor = System.Drawing.Color.Green;
        }
        else
        {
            ResultLabel.Text      = "操作失败,请重试!";
            ResultLabel.ForeColor = System.Drawing.Color.Red;
        }
    }
Пример #46
0
    public async Task <int> SaveSubsAsync(ForceSubscription forceSubscription)
    {
        int affectedRows = 0;
        var chatId       = forceSubscription.ChatId;
        var channelId    = forceSubscription.ChannelId;

        await DB.Find <ForceSubscription>()
        .ManyAsync(
            subscription =>
            subscription.ChatId == chatId &&
            subscription.ChannelId == channelId
            )
        .ContinueWith(
            async task => {
            affectedRows = task.Result.Count;
            if (task.Result.Count == 0)
            {
                await DB.InsertAsync <ForceSubscription>(forceSubscription);
            }
        }
            );

        return(affectedRows);
    }
Пример #47
0
        public ActionResult Business(AssessmentViewModel model)
        {
            DB             db     = new DB();
            BusinessRecord record = db.BusinessRecords.Find(model.Id);

            if (model.quarter == "first")
            {
                record.isAssessed = 1;
            }
            else if (model.quarter == "second")
            {
                record.isAssessed = 2;
            }
            else if (model.quarter == "third")
            {
                record.isAssessed = 3;
            }
            else if (model.quarter == "fourth")
            {
                record.isAssessed = 4;
            }
            db.SaveChanges();
            return(Redirect("/Collection/Business/" + record.UniqueId));
        }
Пример #48
0
        public IActionResult EditAnnouncementIllegal(Announcement AIllegal, int id)
        {
            var Illegal = DB.Announcement
                          .Where(x => x.Id == id && x.TypeCS.NameType == "I")
                          .SingleOrDefault();

            if (Illegal == null)
            {
                return(Content("不存在该记录"));
            }
            else
            {
                var UserCurrent = DB.Users
                                  .Where(x => x.UserName == HttpContext.User.Identity.Name)
                                  .SingleOrDefault();
                var b = DB.BaseInfo
                        .Where(x => x.RegisteNumber == AIllegal.RegisteNumber)
                        .SingleOrDefault();
                if (b != null)
                {
                    Illegal.WriteTime     = DateTime.Now;
                    Illegal.Writer        = UserCurrent.UserName;
                    Illegal.Title         = AIllegal.Title;
                    Illegal.Content       = AIllegal.Content;
                    Illegal.PublicTime    = AIllegal.PublicTime;
                    Illegal.PublicUnit    = AIllegal.PublicUnit;
                    Illegal.RegisteNumber = AIllegal.RegisteNumber;
                    DB.SaveChanges();
                    return(Content("success"));
                }
                else
                {
                    return(Content("nobase"));
                }
            }
        }
Пример #49
0
        public IActionResult Upload(IFormFile file)
        {
            if (HttpContext.Session.GetString("Admin") != "true")
            {
                return(Json(new
                {
                    code = 403,
                    msg = "Forbidden"
                }));
            }

            if (file == null)
            {
                return(Json(new
                {
                    code = 400,
                    msg = "File not found"
                }));
            }

            var _file = new Blob();

            _file.FileName      = file.GetFileName();
            _file.Time          = DateTime.Now;
            _file.Id            = Guid.NewGuid();
            _file.ContentLength = file.Length;
            _file.ContentType   = file.ContentType;
            _file.File          = file.ReadAllBytes();
            DB.Blobs.Add(_file);
            DB.SaveChanges();
            return(Json(new
            {
                code = 200,
                fileId = _file.Id.ToString()
            }));
        }
        private void MainPageInit(DialogPage page)
        {
            var model           = GetDataModel <Model>();
            var dbHouse         = DB.Get <PlayerHouse>(model.OwnerUUID);
            var houseDetail     = Housing.GetHouseTypeDetail(dbHouse.HouseType);
            var furnitureDetail = Housing.GetFurnitureDetail(model.FurnitureType);

            page.Header = ColorToken.Green("Furniture: ") + furnitureDetail.Name + "\n" +
                          ColorToken.Green("Furniture Limit: ") + dbHouse.Furnitures.Count + " / " + houseDetail.FurnitureLimit + "\n\n" +
                          "Please select an action to take.";

            // Furniture has been placed. Only give options to adjust positioning/rotation
            if (model.HasBeenPlaced)
            {
                page.AddResponse("Pick Up", PickUpFurniture);
                page.AddResponse("Move", () => ChangePage(MovePageId));
                page.AddResponse("Rotate", () => ChangePage(RotatePageId));
            }
            // Furniture hasn't been placed yet.
            else
            {
                page.AddResponse("Place", PlaceFurniture);
            }
        }
 public void CallNutritionApi(string NDBNo, int ProductID)
 {
     try
     {
         HttpClient client = new HttpClient();
         client.BaseAddress = new Uri("http://api.nal.usda.gov/ndb/reports/?format=json&type=b&api_key=HBS3lRZUgBIxXOSF1DQBKW7GJw6M6e2J4cFMzSSP&ndbno=" + NDBNo + "");
         client.DefaultRequestHeaders.Accept.Add(
             new MediaTypeWithQualityHeaderValue("application/json"));
         HttpResponseMessage response = client.GetAsync(client.BaseAddress).Result;
         if (response.IsSuccessStatusCode)
         {
             var dataObject = response.Content.ReadAsAsync <rootObject>().Result;
             foreach (nutrients nutrient in dataObject.report.food.nutrients)
             {
                 int    TblPrimaryKey = 0;
                 object objNT         = DB.ExecuteScalar("select va019_nutrition_id from va019_nutrition where m_product_id=" + ProductID + " and va019_nutrition_key=" + nutrient.nutrient_id + "");
                 if (objNT != null && objNT != DBNull.Value)
                 {
                     TblPrimaryKey = Convert.ToInt32(objNT);
                 }
                 var             Dll = Assembly.Load("VA019Svc");
                 var             X_VA019_Nutrition = Dll.GetType("ViennaAdvantage.Model.MVA019Nutrition");
                 ConstructorInfo conInfo           = X_VA019_Nutrition.GetConstructor(new[] { typeof(Ctx), typeof(int), typeof(Trx), typeof(int), typeof(string), typeof(int), typeof(string), typeof(decimal) });
                 conInfo.Invoke(new object[] { p_ctx, TblPrimaryKey, null, ProductID, nutrient.name, nutrient.nutrient_id, nutrient.unit, nutrient.value });
             }
         }
         else
         {
             log.SaveError("Nutretion API Response Falier", "");
         }
     }
     catch (Exception e)
     {
         log.SaveError("Nutretion API Error", e);
     }
 }
Пример #52
0
        public IActionResult Base64String(string file)
        {
            if (HttpContext.Session.GetString("Admin") != "true")
            {
                return(Json(new
                {
                    code = 403,
                    msg = "Forbidden"
                }));
            }

            if (file == null)
            {
                return(Json(new
                {
                    code = 400,
                    msg = "File not found"
                }));
            }
            var img   = new Base64StringImage(file);
            var _file = new Blob();

            _file.FileName      = "file";
            _file.Time          = DateTime.Now;
            _file.Id            = Guid.NewGuid();
            _file.ContentType   = img.ContentType;
            _file.File          = img.AllBytes;
            _file.ContentLength = _file.File.Length;
            DB.Blobs.Add(_file);
            DB.SaveChanges();
            return(Json(new
            {
                code = 200,
                fileId = _file.Id.ToString()
            }));
        }
Пример #53
0
        protected void _SaveNotasPX(object sender, EventArgs e)
        {
            if (txtnotaspx.Value.Trim() == "")
            {
                txtnotaspx.Focus();
                Notify("Debe especificar un comentario", "error");
                return;
            }
            if (Request.QueryString["PROCESO"].ToString() == "NotasPX")
            {
                xsucursal = Request.QueryString["SUCURSAL"].ToString();
                xpaciente = Request.QueryString["PACIENTE"].ToString();

                if (DB.ExecuteNonQuery(string.Format("[PR_PAX00000_NotasGuardar] '{0}','{1}','{2}'", (object)xpaciente.ToString().Trim(), (object)xsucursal.ToString().Trim(), txtnotaspx.Value.Trim())))
                {
                    lblnotaspx.Text      = "Cambio realizado con exito";
                    lblnotaspx.ForeColor = System.Drawing.Color.Blue;
                }
                else
                {
                    lblnotaspx.ForeColor = System.Drawing.Color.Blue;
                }
            }
        }
Пример #54
0
        /// <summary>
        /// Summary for calculation ShippingByTotalByPercent
        /// </summary>
        /// <returns>Return a collection of ShippingMethod based on the computation of ShippingByTotalByPercent</returns>
        public override ShippingMethodCollection GetShippingMethods(int storeId)
        {
            ShippingMethodCollection availableShippingMethods = new ShippingMethodCollection();

            bool shippingMethodToStateMapIsEmpty   = Shipping.ShippingMethodToStateMapIsEmpty();
            bool shippingMethodToCountryMapIsEmpty = Shipping.ShippingMethodToCountryMapIsEmpty();

            decimal extraFee = AppLogic.AppConfigUSDecimal("ShippingHandlingExtraFee");

            string shipsql = GenerateShippingMethodsQuery(storeId, false);
            //shipsql.Append("select * from ShippingMethod  with (NOLOCK)  where IsRTShipping=0 ");

            //if (!shippingMethodToStateMapIsEmpty && !ThisCustomer.IsRegistered)
            //{
            //    shipsql.Append(" and ShippingMethodID in (select ShippingMethodID from ShippingMethodToStateMap  with (NOLOCK))");
            //}

            //if (!shippingMethodToStateMapIsEmpty && ThisCustomer.IsRegistered)
            //{
            //    shipsql.Append(" and ShippingMethodID in (select ShippingMethodID from ShippingMethodToStateMap  with (NOLOCK)  where StateID=" + AppLogic.GetStateID(this.ShippingAddress.State).ToString() + ")");
            //}

            //if (!shippingMethodToCountryMapIsEmpty)
            //{
            //    shipsql.Append(" and ShippingMethodID in (select ShippingMethodID from ShippingMethodToCountryMap  with (NOLOCK)  where CountryID=" + AppLogic.GetCountryID(this.ShippingAddress.Country).ToString() + ")");
            //}
            //shipsql.Append(" order by Displayorder");

            decimal SubTotalWithoutDownload = this.Cart.SubTotal(true, false, false, true, true, false, 0, true);

            using (SqlConnection dbconn = new SqlConnection(DB.GetDBConn()))
            {
                dbconn.Open();
                using (IDataReader reader = DB.GetRS(shipsql.ToString(), dbconn))
                {
                    while (reader.Read())
                    {
                        ShippingMethod thisMethod = new ShippingMethod();
                        thisMethod.Id     = DB.RSFieldInt(reader, "ShippingMethodID");
                        thisMethod.Name   = DB.RSFieldByLocale(reader, "Name", ThisCustomer.LocaleSetting);
                        thisMethod.IsFree = this.ShippingIsFreeIfIncludedInFreeList && Shipping.ShippingMethodIsInFreeList(thisMethod.Id);

                        if (thisMethod.IsFree)
                        {
                            thisMethod.Freight        = decimal.Zero;
                            thisMethod.ShippingIsFree = true;
                        }
                        else
                        {
                            decimal freight = Shipping.GetShipByTotalByPercentCharge(thisMethod.Id, SubTotalWithoutDownload); // exclude download items!

                            if (extraFee > System.Decimal.Zero)
                            {
                                freight += extraFee;
                            }
                            else if (freight > System.Decimal.Zero && extraFee > System.Decimal.Zero)
                            {
                                freight += extraFee;
                            }
                            if (freight < 0)
                            {
                                freight = 0;
                            }
                            thisMethod.Freight = freight;
                        }

                        bool include = !(this.ExcludeZeroFreightCosts == true && (thisMethod.Freight == decimal.Zero && !thisMethod.IsFree));

                        if (include)
                        {
                            availableShippingMethods.Add(thisMethod);
                        }
                    }
                }
            }


            return(availableShippingMethods);
        }
Пример #55
0
 private void frmDetailOrder_Load(object sender, EventArgs e)
 {
     OrderPath1 = DB.GetSettingS("OrderPath1");
     OrderPath2 = DB.GetSettingS("OrderPath2");
 }
        void BindShippingCalculationTable(bool addInsertRow)
        {
            //clear the columns to prevent duplicates
            ShippingGrid.Columns.Clear();

            //We're going to assemble the datasource that we need by putting it together manually here.
            using (DataTable gridData = new DataTable())
            {
                //We'll need shipping method shipping charge amounts to work with in building the data source
                using (DataTable methodAmountsData = new DataTable())
                {
                    //Populate shipping methods data
                    using (SqlConnection sqlConnection = new SqlConnection(DB.GetDBConn()))
                    {
                        sqlConnection.Open();

                        string getShippingMethodMapping       = "exec aspdnsf_GetStoreShippingMethodMapping @StoreID = @StoreId, @IsRTShipping = 0, @OnlyMapped = @FilterByStore";
                        var    getShippingMethodMappingParams = new[]
                        {
                            new SqlParameter("@StoreId", SelectedStoreId),
                            new SqlParameter("@FilterByStore", FilterShipping),
                        };

                        using (IDataReader rs = DB.GetRS(getShippingMethodMapping, getShippingMethodMappingParams, sqlConnection))
                            methodAmountsData.Load(rs);
                    }

                    if (methodAmountsData.Rows.Count == 0)
                    {
                        AlertMessage.PushAlertMessage(String.Format("You do not have any shipping methods setup for the selected store. Please <a href=\"{0}\">click here</a> to set them up.", AppLogic.AdminLinkUrl("shippingmethods.aspx")), AspDotNetStorefrontControls.AlertMessage.AlertType.Error);
                        ShippingRatePanel.Visible = false;
                        return;
                    }

                    using (DataTable shippingRangeData = new DataTable())
                    {
                        using (SqlConnection sqlConnection = new SqlConnection(DB.GetDBConn()))
                        {
                            //populate the shipping range data
                            var sqlShipping = @"SELECT DISTINCT stp.RowGuid,stp.LowValue,stp.HighValue,stp.MinimumCharge,stp.SurCharge 
												FROM ShippingByTotalByPercent stp with (NOLOCK) 
												INNER JOIN ShippingMethod sm WITH (NOLOCK) ON sm.ShippingMethodid = stp.ShippingMethodId AND (@FilterByStore = 0 or @StoreId = stp.StoreID)
												order by LowValue"                                                ;

                            var shippingRangeParams = new[]
                            {
                                new SqlParameter("@StoreId", SelectedStoreId),
                                new SqlParameter("@FilterByStore", FilterShipping),
                            };

                            sqlConnection.Open();
                            using (IDataReader rs = DB.GetRS(sqlShipping, shippingRangeParams, sqlConnection))
                                shippingRangeData.Load(rs);
                        }

                        //Add the data columns we'll need on our table and add grid columns to match
                        gridData.Columns.Add(new DataColumn("RowGuid", typeof(string)));

                        gridData.Columns.Add(new DataColumn("LowValue", typeof(string)));
                        BoundField boundField = new BoundField();
                        boundField.DataField             = "LowValue";
                        boundField.HeaderText            = "Low";
                        boundField.ControlStyle.CssClass = "text-4";
                        ShippingGrid.Columns.Add(boundField);

                        gridData.Columns.Add(new DataColumn("HighValue", typeof(string)));
                        boundField                       = new BoundField();
                        boundField.DataField             = "HighValue";
                        boundField.HeaderText            = "High";
                        boundField.ControlStyle.CssClass = "text-4";
                        ShippingGrid.Columns.Add(boundField);

                        gridData.Columns.Add(new DataColumn("MinimumCharge", typeof(string)));
                        boundField                       = new BoundField();
                        boundField.DataField             = "MinimumCharge";
                        boundField.HeaderText            = "Minimum Dollar Amount";
                        boundField.ControlStyle.CssClass = "text-4";
                        ShippingGrid.Columns.Add(boundField);

                        gridData.Columns.Add(new DataColumn("SurCharge", typeof(string)));
                        boundField                       = new BoundField();
                        boundField.DataField             = "SurCharge";
                        boundField.HeaderText            = "Base Dollar Amount";
                        boundField.ControlStyle.CssClass = "text-4";
                        ShippingGrid.Columns.Add(boundField);

                        //Add shipping method columns to our grid data
                        foreach (DataRow methodAmountsRow in methodAmountsData.Rows)
                        {
                            var columnName = String.Format("MethodAmount_{0}", DB.RowField(methodAmountsRow, "ShippingMethodID"));
                            gridData.Columns.Add(new DataColumn(columnName, typeof(string)));
                            //add a column to the gridview to hold the data
                            boundField                       = new BoundField();
                            boundField.DataField             = columnName;
                            boundField.HeaderText            = DB.RowFieldByLocale(methodAmountsRow, "Name", LocaleSetting);
                            boundField.ControlStyle.CssClass = "text-4";
                            ShippingGrid.Columns.Add(boundField);
                        }

                        //now that our columns are setup add rows to our table
                        foreach (DataRow rangeRow in shippingRangeData.Rows)
                        {
                            var newRow = gridData.NewRow();
                            //add the range data
                            newRow["RowGuid"]       = rangeRow["RowGuid"];
                            newRow["LowValue"]      = rangeRow["LowValue"];
                            newRow["HighValue"]     = rangeRow["HighValue"];
                            newRow["MinimumCharge"] = rangeRow["MinimumCharge"];
                            newRow["SurCharge"]     = rangeRow["SurCharge"];
                            //add shipping method amounts to our grid data
                            foreach (DataRow methodAmountsRow in methodAmountsData.Rows)
                            {
                                var     shippingMethodId  = DB.RowFieldInt(methodAmountsRow, "ShippingMethodID");
                                var     shippingRangeGuid = DB.RowFieldGUID(rangeRow, "RowGUID");
                                Decimal surCharge;                                 // not used here
                                Decimal minimumCharge;                             // not used here
                                var     amount          = Shipping.GetShipByTotalByPercentCharge(shippingMethodId, shippingRangeGuid, out minimumCharge, out surCharge);
                                var     localizedAmount = Localization.CurrencyStringForDBWithoutExchangeRate(amount);

                                var colName = String.Format("MethodAmount_{0}", shippingMethodId);
                                newRow[colName] = localizedAmount;
                            }

                            gridData.Rows.Add(newRow);
                        }

                        //if we're inserting, add an empty row to the end of the table
                        if (addInsertRow)
                        {
                            var newRow = gridData.NewRow();
                            //add the range data
                            newRow["RowGuid"]       = 0;
                            newRow["LowValue"]      = 0;
                            newRow["HighValue"]     = 0;
                            newRow["MinimumCharge"] = 0;
                            newRow["SurCharge"]     = 0;
                            //add shipping method columns to our insert row
                            foreach (DataRow methodAmountsRow in methodAmountsData.Rows)
                            {
                                var shippingMethodId = DB.RowFieldInt(methodAmountsRow, "ShippingMethodID");
                                var amount           = 0;
                                var localizedAmount  = Localization.CurrencyStringForDBWithoutExchangeRate(amount);

                                var colName = String.Format("MethodAmount_{0}", shippingMethodId);
                                newRow[colName] = localizedAmount;
                            }
                            gridData.Rows.Add(newRow);
                            //if we're inserting than we'll want to make the insert row editable
                            ShippingGrid.EditIndex = gridData.Rows.Count - 1;
                        }


                        //add the delete button column
                        ButtonField deleteField = new ButtonField();
                        deleteField.ButtonType            = ButtonType.Link;
                        deleteField.Text                  = "<i class=\"fa fa-times\"></i> Delete";
                        deleteField.CommandName           = "Delete";
                        deleteField.ControlStyle.CssClass = "delete-link";
                        deleteField.ItemStyle.Width       = 94;
                        ShippingGrid.Columns.Add(deleteField);

                        //add the edit button column
                        CommandField commandField = new CommandField();
                        commandField.ButtonType            = ButtonType.Link;
                        commandField.ShowEditButton        = true;
                        commandField.ShowDeleteButton      = false;
                        commandField.ShowCancelButton      = true;
                        commandField.ControlStyle.CssClass = "edit-link";
                        commandField.EditText        = "<i class=\"fa fa-share\"></i> Edit";
                        commandField.CancelText      = "<i class=\"fa fa-reply\"></i> Cancel";
                        commandField.UpdateText      = "<i class=\"fa fa-floppy-o\"></i> Save";
                        commandField.ItemStyle.Width = 84;
                        ShippingGrid.Columns.Add(commandField);

                        ShippingGrid.DataSource = gridData;
                        ShippingGrid.DataBind();
                    }
                }
            }

            btnInsert.Visible = !addInsertRow;              //Hide the 'add new row' button while editing/inserting to avoid confusion and lost data
        }
        bool TryUpdateShippingRow(GridViewRow row, string guid)
        {
            var newGuid = DB.GetNewGUID();
            //loop through the colums and update each shipping method with the appropriate value
            var indexCounter = 0;

            foreach (var column in ShippingGrid.Columns)
            {
                //skip past the low and high value columns and make sure we've got a bound field
                if (indexCounter > 3 && column.GetType() == typeof(BoundField))
                {
                    var field = (BoundField)column;
                    if (field.DataField.Contains("MethodAmount_"))
                    {
                        var     methodId = field.DataField.Replace("MethodAmount_", String.Empty);
                        decimal lowValue = 0;
                        if (!decimal.TryParse(((TextBox)(row.Cells[0].Controls[0])).Text, out lowValue))
                        {
                            AlertMessage.PushAlertMessage("Your low value is not in the correct format.", AspDotNetStorefrontControls.AlertMessage.AlertType.Error);
                            return(false);
                        }
                        decimal highValue = 0;
                        if (!decimal.TryParse(((TextBox)(row.Cells[1].Controls[0])).Text, out highValue))
                        {
                            AlertMessage.PushAlertMessage("Your high value is not in the correct format.", AspDotNetStorefrontControls.AlertMessage.AlertType.Error);
                            return(false);
                        }
                        decimal minimumChargeAmount = 0;
                        if (!decimal.TryParse(((TextBox)(row.Cells[2].Controls[0])).Text, out minimumChargeAmount))
                        {
                            AlertMessage.PushAlertMessage("The minimum amount you entered is not in the correct format.", AspDotNetStorefrontControls.AlertMessage.AlertType.Error);
                            return(false);
                        }
                        decimal surChargeAmount = 0;
                        if (!decimal.TryParse(((TextBox)(row.Cells[3].Controls[0])).Text, out surChargeAmount))
                        {
                            AlertMessage.PushAlertMessage("The base amount you entered is not in the correct format.", AspDotNetStorefrontControls.AlertMessage.AlertType.Error);
                            return(false);
                        }
                        decimal percentOfTotal = 0;
                        if (!decimal.TryParse(((TextBox)(row.Cells[indexCounter].Controls[0])).Text, out percentOfTotal))
                        {
                            AlertMessage.PushAlertMessage("The percentage you entered for one of your shipping methods is not in the correct format.", AspDotNetStorefrontControls.AlertMessage.AlertType.Error);
                            return(false);
                        }
                        if (lowValue >= highValue)
                        {
                            AlertMessage.PushAlertMessage("Please enter a valid range for your low and high values", AspDotNetStorefrontControls.AlertMessage.AlertType.Error);
                            return(false);
                        }
                        //passed validation. delete the old row and create a new one.
                        if (guid != "0")
                        {
                            DB.ExecuteSQL("delete from ShippingByTotalByPercent where RowGUID = @Guid ", new[] { new SqlParameter("Guid", guid) });
                        }

                        var parameters = new[] {
                            new SqlParameter("@ShippingGuid", newGuid),
                            new SqlParameter("@LowAmount", lowValue),
                            new SqlParameter("@HighAmount", highValue),
                            new SqlParameter("@ShippingMethodId", methodId),
                            new SqlParameter("@MinimumCharge", minimumChargeAmount),
                            new SqlParameter("@SurCharge", surChargeAmount),
                            new SqlParameter("@PercentOfTotal", percentOfTotal),
                            new SqlParameter("@StoreId", SelectedStoreId),
                        };

                        var insertSql = @"insert into ShippingByTotalByPercent(RowGUID, LowValue, HighValue, ShippingMethodID, MinimumCharge, SurCharge, PercentOfTotal, StoreID) 
										values(@ShippingGuid, @LowAmount, @HighAmount, @ShippingMethodId, @MinimumCharge, @SurCharge, @PercentOfTotal, @StoreId)"                                        ;

                        DB.ExecuteSQL(insertSql, parameters);
                    }
                }
                indexCounter++;
            }
            return(true);
        }
        public static bool InsertForeignCostMatchOrder(Ctx ctx, MOrderLine orderLine, decimal matchQty, int ASI, Trx trx)
        {
            int                  acctSchema_ID    = 0;
            int                  M_CostElement_ID = 0;
            int                  AD_Org_ID        = 0;
            int                  M_ASI_ID         = 0;
            MProduct             product          = null;
            MAcctSchema          acctSchema       = null;
            MCostForeignCurrency foreignCost      = null;
            dynamic              pc    = null;
            String               cl    = null;
            MOrder               order = null;

            try
            {
                order = new MOrder(ctx, orderLine.GetC_Order_ID(), trx);

                if (!order.IsSOTrx() && !order.IsReturnTrx())
                {
                    acctSchema_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT asch.c_acctschema_id FROM c_acctschema asch INNER JOIN ad_clientinfo ci
                                    ON ci.c_acctschema1_id = asch.c_acctschema_id WHERE ci.ad_client_id  = " + order.GetAD_Client_ID()));
                    acctSchema    = new MAcctSchema(ctx, acctSchema_ID, trx);

                    if (acctSchema.GetC_Currency_ID() != order.GetC_Currency_ID())
                    {
                        // Get Costing Element of Av. PO
                        M_CostElement_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT M_CostElement_ID FROM M_CostElement WHERE AD_Client_ID = "
                                                                               + order.GetAD_Client_ID() + " AND IsActive = 'Y' AND CostingMethod = 'A'"));

                        product = new MProduct(ctx, orderLine.GetM_Product_ID(), trx);

                        if (product != null && product.GetProductType() == "I" && product.GetM_Product_ID() > 0) // for Item Type product
                        {
                            pc = MProductCategory.Get(product.GetCtx(), product.GetM_Product_Category_ID());

                            // Get Costing Level
                            if (pc != null)
                            {
                                cl = pc.GetCostingLevel();
                            }
                            if (cl == null)
                            {
                                cl = acctSchema.GetCostingLevel();
                            }

                            if (cl == "C" || cl == "B")
                            {
                                AD_Org_ID = 0;
                            }
                            else
                            {
                                AD_Org_ID = order.GetAD_Org_ID();
                            }
                            if (cl != "B")
                            {
                                M_ASI_ID = 0;
                            }
                            else
                            {
                                M_ASI_ID = ASI;
                            }

                            foreignCost = MCostForeignCurrency.Get(product, M_ASI_ID, AD_Org_ID, M_CostElement_ID, order.GetC_BPartner_ID(), order.GetC_Currency_ID());
                            foreignCost.SetC_Order_ID(order.GetC_Order_ID());
                            foreignCost.SetCumulatedQty(Decimal.Add(foreignCost.GetCumulatedQty(), matchQty));
                            foreignCost.SetCumulatedAmt(Decimal.Add(foreignCost.GetCumulatedAmt(), Decimal.Multiply(orderLine.GetPriceActual(), matchQty)));
                            if (foreignCost.GetCumulatedQty() != 0)
                            {
                                foreignCost.SetCostPerUnit(Decimal.Round(Decimal.Divide(foreignCost.GetCumulatedAmt(), foreignCost.GetCumulatedQty()), acctSchema.GetCostingPrecision()));
                            }
                            else
                            {
                                foreignCost.SetCostPerUnit(0);
                            }
                            if (!foreignCost.Save(trx))
                            {
                                ValueNamePair pp = VLogger.RetrieveError();
                                _log.Severe("Error occured during updating M_Cost_ForeignCurrency. Error name : " + pp.GetName() +
                                            " AND Error Value : " + pp.GetValue() + " , For Invoice line : " + orderLine.GetC_OrderLine_ID() +
                                            " , AND Ad_Client_ID : " + orderLine.GetAD_Client_ID());
                                return(false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Log(Level.SEVERE, "", ex);
                return(false);
            }
            return(true);
        }
        public static bool InsertForeignCostAverageInvoice(Ctx ctx, MInvoice invoice, MInvoiceLine invoiceLine, Trx trx)
        {
            int                  acctSchema_ID    = 0;
            int                  M_CostElement_ID = 0;
            int                  AD_Org_ID        = 0;
            int                  M_ASI_ID         = 0;
            MProduct             product          = null;
            MAcctSchema          acctSchema       = null;
            MCostForeignCurrency foreignCost      = null;
            dynamic              pc = null;
            String               cl = null;

            try
            {
                // if cost is calculated then not to calculate again
                if (invoiceLine.IsFutureCostCalculated())
                {
                    return(true);
                }

                acctSchema_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT asch.c_acctschema_id FROM c_acctschema asch INNER JOIN ad_clientinfo ci
                                    ON ci.c_acctschema1_id = asch.c_acctschema_id WHERE ci.ad_client_id  = " + invoice.GetAD_Client_ID()));
                acctSchema    = new MAcctSchema(ctx, acctSchema_ID, trx);

                if (acctSchema.GetC_Currency_ID() != invoice.GetC_Currency_ID())
                {
                    // Get Costing Element of Av. Invoice
                    M_CostElement_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT M_CostElement_ID FROM M_CostElement WHERE AD_Client_ID = "
                                                                           + invoice.GetAD_Client_ID() + " AND IsActive = 'Y' AND CostingMethod = 'I'"));

                    product = new MProduct(ctx, invoiceLine.GetM_Product_ID(), trx);

                    if (product != null && product.GetProductType() == "I" && product.GetM_Product_ID() > 0) // for Item Type product
                    {
                        pc = MProductCategory.Get(product.GetCtx(), product.GetM_Product_Category_ID());

                        // Get Costing Level
                        if (pc != null)
                        {
                            cl = pc.GetCostingLevel();
                        }
                        if (cl == null)
                        {
                            cl = acctSchema.GetCostingLevel();
                        }

                        if (cl == "C" || cl == "B")
                        {
                            AD_Org_ID = 0;
                        }
                        else
                        {
                            AD_Org_ID = invoice.GetAD_Org_ID();
                        }
                        if (cl != "B")
                        {
                            M_ASI_ID = 0;
                        }
                        else
                        {
                            M_ASI_ID = invoiceLine.GetM_AttributeSetInstance_ID();
                        }

                        foreignCost = MCostForeignCurrency.Get(product, M_ASI_ID, AD_Org_ID, M_CostElement_ID, invoice.GetC_BPartner_ID(), invoice.GetC_Currency_ID());
                        foreignCost.SetC_Invoice_ID(invoice.GetC_Invoice_ID());
                        foreignCost.SetCumulatedQty(Decimal.Add(foreignCost.GetCumulatedQty(), invoiceLine.GetQtyInvoiced()));
                        foreignCost.SetCumulatedAmt(Decimal.Add(foreignCost.GetCumulatedAmt(), invoiceLine.GetLineNetAmt()));
                        if (foreignCost.GetCumulatedQty() != 0)
                        {
                            foreignCost.SetCostPerUnit(Decimal.Round(Decimal.Divide(foreignCost.GetCumulatedAmt(), foreignCost.GetCumulatedQty()), acctSchema.GetCostingPrecision()));
                        }
                        else
                        {
                            foreignCost.SetCostPerUnit(0);
                        }
                        if (!foreignCost.Save(trx))
                        {
                            ValueNamePair pp = VLogger.RetrieveError();
                            _log.Severe("Error occured during updating M_Cost_ForeignCurrency. Error name : " + pp.GetName() +
                                        " AND Error Value : " + pp.GetValue() + " , For Invoice line : " + invoiceLine.GetC_InvoiceLine_ID() +
                                        " , AND Ad_Client_ID : " + invoiceLine.GetAD_Client_ID());
                            return(false);
                        }
                        else
                        {
                            invoiceLine.SetIsFutureCostCalculated(true);
                            if (!invoiceLine.Save(trx))
                            {
                                ValueNamePair pp = VLogger.RetrieveError();
                                _log.Severe("Error occured during updating Is Foreign Cost On C_invoice. Error name : " + pp.GetName() +
                                            " AND Error Value : " + pp.GetValue() + " , For Invoice line : " + invoiceLine.GetC_InvoiceLine_ID() +
                                            " , AND Ad_Client_ID : " + invoiceLine.GetAD_Client_ID());
                                return(false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Log(Level.SEVERE, "", ex);
                return(false);
            }
            return(true);
        }
Пример #60
0
        protected override String DoIt()
        {
            string sql          = "Select ad_table_id from ad_table where tablename='C_Lead'";
            int    leadTable_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql));

            sql = "Select ad_table_id from ad_table where tablename='C_BPartner'";
            int BPartnerTable_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql));

            VAdvantage.Model.X_C_TargetList TList = new VAdvantage.Model.X_C_TargetList(GetCtx(), 0, null);

            if (Table_id == leadTable_ID)// C_Lead
            {
                VAdvantage.Model.X_C_Lead lead = new VAdvantage.Model.X_C_Lead(GetCtx(), Record_ID, null);

                TList.Set_ValueNoCheck("C_MasterTargetList_ID", Campaign_id);
                // TList.SetC_MasterTargetList_ID(Campaign_id);
                TList.SetC_Lead_ID(Record_ID);
                TList.SetAddress1(lead.GetAddress1());
                TList.SetAddress2(lead.GetAddress2());
                TList.SetC_City_ID(lead.GetC_City_ID());
                TList.SetCity(lead.GetCity());
                TList.SetC_Region_ID(lead.GetC_Region_ID());
                TList.SetRegionName(lead.GetRegionName());
                TList.SetC_Country_ID(lead.GetC_Country_ID());
                TList.SetPostal(lead.GetPostal());


                if (TList.Save())
                {
                    return(Msg.GetMsg(GetCtx(), "TargetListCreate"));
                }
                return(Msg.GetMsg(GetCtx(), "TargetListNotCreate"));
            }

            if (Table_id == BPartnerTable_ID) // C_BPartner
            {
                string Query = "select isprospect from c_bpartner where c_bpartner_id=" + Record_ID;
                string P     = Util.GetValueOfString(DB.ExecuteScalar(Query));
                if (P == "Y")
                {
                    // TList.SetC_MasterTargetList_ID(Campaign_id);
                    TList.Set_ValueNoCheck("C_MasterTargetList_ID", Campaign_id);
                    TList.SetRef_BPartner_ID(Record_ID);
                    sql = "Select C_Location_id from c_bpartner_Location where c_bpartner_id=" + Record_ID;
                    object locID = DB.ExecuteScalar(sql);
                    TList.SetC_Location_ID(Util.GetValueOfInt(locID));
                }
                else
                {
                    Query = "select iscustomer from c_bpartner where c_bpartner_id=" + Record_ID;
                    P     = Util.GetValueOfString(DB.ExecuteScalar(Query));
                    if (P == "Y")
                    {
                        //TList.SetC_MasterTargetList_ID(Campaign_id);
                        TList.Set_ValueNoCheck("C_MasterTargetList_ID", Campaign_id);
                        TList.SetC_BPartner_ID(Record_ID);
                        sql = "Select C_Location_id from c_bpartner_Location where c_bpartner_id=" + Record_ID;
                        object locID = DB.ExecuteScalar(sql);
                        TList.SetC_Location_ID(Util.GetValueOfInt(locID));
                    }
                    else
                    {
                        return(Msg.GetMsg(GetCtx(), "TargetListNotCreate"));
                    }
                }
                if (TList.Save())
                {
                    return(Msg.GetMsg(GetCtx(), "TargetListCreate"));
                }

                return(Msg.GetMsg(GetCtx(), "TargetListNotCreate"));
            }


            return(Msg.GetMsg(GetCtx(), "TargetListCreate"));
        }