Exemplo n.º 1
0
		public override void LoadConteudoEEstrutura(DataSet currentDataSet, long CurrentFRDBaseID, IDbConnection conn)
		{
			using (SqlCommand command = SqlSyntax.CreateSelectCommandWithNoDeletedRowsParam((SqlConnection)conn))
            using (SqlDataAdapter da = new SqlDataAdapter(command))
			{
                command.Parameters.AddWithValue("@CurrentFRDBaseID", CurrentFRDBaseID);
                command.Parameters.AddWithValue("@IDTipoNoticiaAut5", 5);
                command.Parameters.AddWithValue("@IDTipoNoticiaAut8", 8);

                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["ControloAut"],
                    "INNER JOIN IndexFRDCA ON IndexFRDCA.IDControloAut = ControloAut.ID " +
                    "WHERE ControloAut.IDTipoNoticiaAut BETWEEN @IDTipoNoticiaAut5 AND @IDTipoNoticiaAut8 AND IndexFRDCA.IDFRDBase=@CurrentFRDBaseID");
                da.Fill(currentDataSet, "ControloAut");

                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["Dicionario"],
                    "INNER JOIN ControloAutDicionario ON ControloAutDicionario.IDDicionario = Dicionario.ID " +
                    "INNER JOIN ControloAut ON ControloAut.ID = ControloAutDicionario.IDControloAut " +
                    "INNER JOIN IndexFRDCA ON IndexFRDCA.IDControloAut = ControloAut.ID " +
                    "WHERE ControloAut.IDTipoNoticiaAut BETWEEN @IDTipoNoticiaAut5 AND @IDTipoNoticiaAut8 AND IDFRDBase=@CurrentFRDBaseID");
                da.Fill(currentDataSet, "Dicionario");

                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["ControloAutDicionario"],
                    "INNER JOIN IndexFRDCA ON IndexFRDCA.IDControloAut = ControloAutDicionario.IDControloAut " +
                    "INNER JOIN ControloAut ON ControloAut.ID = ControloAutDicionario.IDControloAut " +
                    "WHERE ControloAut.IDTipoNoticiaAut BETWEEN @IDTipoNoticiaAut5 AND @IDTipoNoticiaAut8 AND IndexFRDCA.IDFRDBase=@CurrentFRDBaseID");
                da.Fill(currentDataSet, "ControloAutDicionario");

                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["IndexFRDCA"],
                    "INNER JOIN ControloAut ON ControloAut.ID = IndexFRDCA.IDControloAut " +
                    "WHERE ControloAut.IDTipoNoticiaAut BETWEEN @IDTipoNoticiaAut5 AND @IDTipoNoticiaAut8 AND IndexFRDCA.IDFRDBase=@CurrentFRDBaseID");
                da.Fill(currentDataSet, "IndexFRDCA");
			}
		}
Exemplo n.º 2
0
 /// <summary>
 /// 返回数据集,要从外部进行数据集 ( ds = new dataset()) 的传递
 /// </summary>
 /// <param name="commandType"></param>
 /// <param name="commandText"></param>
 /// <param name="commandParameters"></param>
 /// <param name="ds"></param>
 /// <param name="tableName"></param>
 /// <returns></returns>
 public override DataSet ExecuteDataset(CommandType commandType, string commandText,
                                        QueryParameterCollection commandParameters, DataSet ds, string tableName)
 {
     try
     {
         var cmd = new SqlCommand();
         PrepareCommand(cmd, commandType, commandText, commandParameters);
         var adapter = new SqlDataAdapter(cmd);
         if (Equals(tableName, null) || (tableName.Length < 1))
         {
             adapter.Fill(ds);
         }
         else
         {
             adapter.Fill(ds, tableName);
         }
         base.SyncParameter(commandParameters);
         cmd.Parameters.Clear();
         return ds;
     }
     catch
     {
         exceptioned = true;
         throw;
     }
     finally
     {
         Close();
     }
 }
Exemplo n.º 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string strConn = "Server=KHJ; database=PE0503; Integrated Security = true";
                DataSet ds = new DataSet();
                SqlConnection cn = new SqlConnection(strConn);
                SqlCommand cmd = new SqlCommand("select * from AssetTypes order by AssetTypeName", cn);
                SqlCommand cmd2 = new SqlCommand("select * from Companies order by companyName", cn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                DropDownList1.DataSource = ds.Tables[0];
                DropDownList1.DataTextField = "AssetTypeName";
                DropDownList1.DataValueField = "AssetTypeID";
                DropDownList1.DataBind();

                SqlDataAdapter da1 = new SqlDataAdapter(cmd2);
                da.Fill(ds);
                DropDownList2.DataSource = ds.Tables[0];
                DropDownList2.DataTextField = "companyName";
                DropDownList2.DataValueField = "companyID";
              //  DropDownList2.DataBind();

            }
        }
Exemplo n.º 4
0
		public override void LoadUFControloDescricaoData(DataSet currentDataSet, DataSet newDataSet, long CurrentFRDBaseID, IDbConnection conn)
		{
			string WhereQueryFilter = "WHERE IDFRDBase=@CurrentFRDBaseID";

			string WhereUserQueryFilter = "WHERE ID IN " + 
				"(SELECT IDTrusteeOperator FROM FRDBaseDataDeDescricao " + 
				WhereQueryFilter + " UNION " + 
				"SELECT IDTrusteeAuthority FROM FRDBaseDataDeDescricao " + 
				WhereQueryFilter + ")";

            using (SqlCommand command = SqlSyntax.CreateSelectCommandWithNoDeletedRowsParam((SqlConnection)conn))
            using (SqlDataAdapter da = new SqlDataAdapter(command))
			{
                command.Parameters.AddWithValue("@CurrentFRDBaseID", CurrentFRDBaseID);
                command.Parameters.AddWithValue("@IsAuthority", 1);

				// Load Trustee.IsAuthority=1
                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["Trustee"], "WHERE ID IN (SELECT ID FROM TrusteeUser WHERE IsAuthority=@IsAuthority)");
				da.Fill(currentDataSet, "Trustee");
                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["TrusteeUser"], "WHERE IsAuthority=@IsAuthority");
				da.Fill(currentDataSet, "TrusteeUser");

				da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["Trustee"], WhereUserQueryFilter);
				da.Fill(currentDataSet, "Trustee");
				da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["TrusteeUser"], WhereUserQueryFilter);
				da.Fill(currentDataSet, "TrusteeUser");

                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["FRDBaseDataDeDescricao"], WhereQueryFilter);
                da.Fill(currentDataSet, "FRDBaseDataDeDescricao");
			}
		}
Exemplo n.º 5
0
 public void GetData(int direction)
 {
     if ((direction==0 && !mainDS.Tables.Contains("yingshou")) || (direction==1 && !mainDS.Tables.Contains("yingshou")))
     {
         SqlConnection con = new SqlConnection(services.DBservice.strConn);
         SqlDataAdapter sdr = new SqlDataAdapter("select Series 序号,Bill_Num 应收应付源,Sum1 金额,Processor 经办人  from dbo.tb_bills where Direction = @direction", con);
         sdr.SelectCommand.Parameters.AddWithValue("@direction", direction);
         if (direction == 0)
         {
             sdr.Fill(mainDS, "yingshou");
             dataGridView1.DataMember = "yingshou";
         }
         else
         {
             sdr.Fill(mainDS, "yingfu");
             dataGridView1.DataMember = "yingfu";
         }
         dataGridView1.DataSource = mainDS;
     }
     else if (direction == 0 && mainDS.Tables.Contains("yingshou"))
     {
         dataGridView1.DataSource = mainDS;
         dataGridView1.DataMember = "yingshou";
     }
     else if (direction == 1 && mainDS.Tables.Contains("yingshou"))
     {
         dataGridView1.DataSource = mainDS;
         dataGridView1.DataMember = "yingfu";
     }
     else
     {
         return;
     }
 }
Exemplo n.º 6
0
        public static DataSet ExecuteDataset(SqlConnection cn, SqlTransaction trans, string cmdText, string tableName, params SqlParameter[] sqlParams)
        {
            DataSet data = new DataSet();

            try
            {
                SqlCommand cmd = new SqlCommand(cmdText, cn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Transaction = trans;
                if (sqlParams != null)
                {
                    AttachParameters(cmd, sqlParams);
                }
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                if (tableName != null && tableName != string.Empty)
                {
                    adapter.Fill(data, tableName);
                }
                else
                {
                    adapter.Fill(data);
                }
                adapter.Dispose();
                cmd.Parameters.Clear();
                cmd.Dispose();
            }
            catch (Exception err)
            {
                TScope.HandlError(err);
            }

            return data;
        }
Exemplo n.º 7
0
        /// <summary>
        /// Genera un DataAdapter segun un query dado - Solo para grilla paginada.
        /// </summary>
        public SqlDataAdapter executeQueryAdapter(String query, ref DataSet oDs, ref DataTable oDt, 
                                String dataMember, int inicio, int tope)
        {
            SqlConnection conn = new SqlConnection(Singleton.ConnectionString);
            SqlDataAdapter oAdapter = new SqlDataAdapter(query, conn);

            try
            {
                conn.Open();

                try
                {
                    oAdapter.Fill(oDs, inicio, tope, dataMember);
                    oAdapter.Fill(oDt);
                }
                finally
                {
                    conn.Close();
                }

                return oAdapter;
            }
            catch (Exception ex)
            {
                throw new Exception("Se detecto un error en executeQueryAdapter con el Query: " + query + System.Environment.NewLine + "Mensaje de Error: " + ex.Message);
            }
        }
Exemplo n.º 8
0
        public void readsequentialy()
        {
            int iter = 0;
            int currentIndex = 0;
            int pageSize = 3000;

            string sql = ConfigurationManager.ConnectionStrings["t2"].ConnectionString;
            string sqltest = ConfigurationManager.ConnectionStrings["test"].ConnectionString;

            SqlConnection connection = new SqlConnection(sql);

            string orderSQL = "SELECT * FROM [dbo].[TransactionHistory] order by [TransactionID]";
            // Assumes that connection is a valid SqlConnection object.
            SqlDataAdapter adapter = new SqlDataAdapter(orderSQL, connection);

            DataSet dataSet = new DataSet();
            adapter.Fill(dataSet, currentIndex, pageSize, "Orders");
            DataTable dataTable = dataSet.Tables[0];
            while (dataTable.Rows.Count > 0)
            {
                Console.WriteLine("iteration: " + iter++);
                foreach (DataRow row in dataTable.Rows)
                {
                    row.SetAdded();
                }
                //BultInsert(pageSize, sqltest, dataTable);

                currentIndex += pageSize;
                dataSet.Tables["Orders"].Rows.Clear();

                adapter.Fill(dataSet, currentIndex, pageSize, "Orders");
                dataTable = dataSet.Tables[0];
            }
            Console.WriteLine(String.Format("done rows: {0} with iteration: {1}", iter * pageSize, iter));
        }
Exemplo n.º 9
0
 private void Frm_Main_Load(object sender, EventArgs e)
 {
     string ConnectionString = "server=(local); database=db_TomeTwo; uid=sa; pwd=6221131";//声明连接字符串
     using (SqlConnection Conn = new SqlConnection(ConnectionString))//创建数据库连接对象
     {
         string sqlstr = "select * from tb_Register";//定义查询语句
         SqlDataAdapter da = new SqlDataAdapter(sqlstr, Conn);//创建数据桥接器对象
         DataSet ds = new DataSet();//创建数据对象
         da.Fill(ds, "register");//填充第一个数据表数据到DataSet
         sqlstr = "select * from tb_Sale";//定义查询语句
         da.SelectCommand.CommandText = sqlstr;//指定第二条查询语句
         da.Fill(ds, "sale");//填充第二个数据表数据到DataSet
         //查询有销售记录的药品信息
         var result = from r in ds.Tables["register"].AsEnumerable()
                      join s in ds.Tables["sale"].AsEnumerable()
                      on r.Field<string>("药品编号") equals s.Field<string>("药品编号")
                      select new
                      {
                          drug_name = r["药品名称"].ToString(),
                          drug_factory = r["生产厂家"].ToString(),
                          drug_sale = s["销售额"].ToString()
                      };
         foreach (var item in result)			//遍历输出查询结果
         {
             richTextBox1.Text += "药品名称:" + item.drug_name + "******生产厂家:" + item.drug_factory + "******销售额:" + item.drug_sale + "\n";
         }
     }
 }
Exemplo n.º 10
0
        public static DataSet ExecuteDataset(SqlConnection cn, SqlTransaction trans, string cmdText, string tableName, params SqlParameter[] sqlParams)
        {
            DataSet data = new DataSet();

            SqlCommand cmd = new SqlCommand(cmdText, cn);
            cmd.CommandType = CommandType.Text;
            cmd.Transaction = trans;
            if (sqlParams != null)
            {
                AttachParameters(cmd, sqlParams);
            }
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            if (tableName != null && tableName != string.Empty)
            {
                adapter.Fill(data, tableName);
            }
            else
            {
                adapter.Fill(data);
            }
            adapter.Dispose();
            cmd.Parameters.Clear();
            cmd.Dispose();

            return data;
        }
Exemplo n.º 11
0
		public override void LoadDataModuloPermissoes(DataSet CurrentDataSet, Int16 IDTipoFunctionGroup, Int16 IdxTipoFunction, IDbConnection conn)
		{
            using (SqlCommand command = SqlSyntax.CreateSelectCommandWithNoDeletedRowsParam((SqlConnection)conn))
            using (SqlDataAdapter da = new SqlDataAdapter(command))
			{
                command.Parameters.AddWithValue("@IDTipoFunctionGroup", IDTipoFunctionGroup);
                command.Parameters.AddWithValue("@IdxTipoFunction", IdxTipoFunction);

				da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(CurrentDataSet.Tables["Trustee"]);
				da.Fill(CurrentDataSet, "Trustee");

				da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(CurrentDataSet.Tables["TrusteeUser"]);
				da.Fill(CurrentDataSet, "TrusteeUser");

				da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(CurrentDataSet.Tables["TrusteeGroup"]);
				da.Fill(CurrentDataSet, "TrusteeGroup");

                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(CurrentDataSet.Tables["UserGroups"]);
                da.Fill(CurrentDataSet, "UserGroups");

                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(CurrentDataSet.Tables["TrusteePrivilege"],
                    " WHERE TrusteePrivilege.IDTipoFunctionGroup=@IDTipoFunctionGroup AND TrusteePrivilege.IdxTipoFunction=@IdxTipoFunction");
				da.Fill(CurrentDataSet, "TrusteePrivilege");
			}
		}
Exemplo n.º 12
0
 private void buscarP_Click(object sender, EventArgs e)
 {
     if(producto.TextLength>0)
     {
     dtingresos.Clear();
     dtsalidas.Clear();
     using (SqlConnection con = new SqlConnection("Server=localhost; database=INVERSEC_3; integrated security=yes"))
     {
         try
         {
             SqlCommand comando = new SqlCommand("SELECT pro.nombre Proveedor,p.cod_pro Codigo,p.nombre Nombre,p.descripcion Descripcion,b.nombre Bodega, CONVERT(VARCHAR,f.fecha,105) Fecha, sum(fp.cantidad) Cantidad from PRODUCTO p join FACT_PRODUCTO fp on p.cod_pro=fp.cod_pro and p.nombre=@nombre join FACTURA f on f.num_fact=fp.num_fact  join bodega b on p.cod_bodega=b.cod_bodega join PROVEEDOR pro on pro.rut_emp=f.rut_pro group by f.fecha,p.cod_pro,p.nombre,p.descripcion,b.nombre,pro.nombre", con);
             comando.Parameters.AddWithValue("@nombre", producto.Text);
             SqlDataAdapter da = new SqlDataAdapter(comando);
             da.Fill(dtingresos);
             dgvi.DataSource = dtingresos;
             comando.CommandText = "SELECT cli.nombre Cliente,p.cod_pro Codigo,p.nombre Nombre,p.descripcion Descripcion,b.nombre Bodega, CONVERT(VARCHAR,f.fecha,105) Fecha, sum(fp.cantidad) Cantidad from PRODUCTO p join FACT_PRODUCTO fp on p.cod_pro=fp.cod_pro and p.nombre=@nombre join FACTURA f on f.num_fact=fp.num_fact join bodega b on p.cod_bodega=b.cod_bodega join Cliente cli on cli.rut_emp=f.rut_cli group by f.fecha,p.cod_pro,p.nombre,p.descripcion,b.nombre,cli.nombre ";
             da.Fill(dtsalidas);
             dgvs.DataSource = dtsalidas;
         }
         catch (Exception ev)
         {
             MessageBox.Show("Error al intentar consultar la base de datos: " + ev.ToString());
         }
     }
     }
     else
     {
         MessageBox.Show("Debe ingresar un nombre de prodcuto");
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!(bool)Session["logedIn"])
            {
                Response.Redirect("Login.aspx");
            }

            lblKorisnik.Text = (string)Session["userName"];
            lblGrupa.Text = (string)Session["userGroup"];

            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MojaKonekcija"].ConnectionString);

            var cmd = new SqlCommand("SELECT * FROM korisnici WHERE korisnicko_ime LIKE @username", con);

            cmd.Parameters.Add("@username", SqlDbType.NVarChar).Value = lblKorisnik.Text;

            SqlDataAdapter adptr = new SqlDataAdapter();

            adptr.SelectCommand = cmd;

            SqlCommandBuilder cmdBld = new SqlCommandBuilder(adptr);

            DataTable mojDataTable = new DataTable();
            DataSet mojDataSet = new DataSet();

            adptr.Fill(mojDataSet);
            adptr.Fill(mojDataTable);

               var email= (string)mojDataTable.Rows[0]["email"];
               txtMail.Text = email;
        }
    private void LoadPage()
    {
        string pageUrl = this.Page.RouteData.Values["PageUrl"].ToString();
        string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;

        using (SqlConnection sqlConn = new SqlConnection(connString))
        {
            using (SqlCommand sqlCmd = new SqlCommand())
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    sqlCmd.Parameters.AddWithValue("@PageUrl", pageUrl);
                    sqlCmd.Connection = sqlConn;
                    sqlCmd.CommandText = "dbo.GetPageContent";
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    DataSet ds = new DataSet();
                    sda.SelectCommand=sqlCmd;
                    sda.Fill(ds);
                    DataTable dt = ds.Tables[0];
                    sda.Fill(dt);
                    lblTitle.Text = dt.Rows[0]["Title"].ToString();
                    lblContent.Text = dt.Rows[0]["Content"].ToString();
                }
            }
        }
    }
Exemplo n.º 15
0
        public DataTable createChargeTable()
        {
            serviceChargeTable.Clear();
            tablecharge.Clear();
            tablecharge3.Clear();
            DataTable tablecharge2 = new DataTable();
            tablecharge2.Columns.Add("Kodu", typeof(Int32));
            tablecharge2.Columns.Add("Adı", typeof(String));
            tablecharge2.Columns.Add("Soyadı", typeof(String));
            tablecharge2.Columns.Add("Toplam Alacak", typeof(Decimal));
            tablecharge2.Columns.Add("Para Birimi", typeof(String));
            createConnection();
            SqlDataAdapter adapter = new SqlDataAdapter("Select * from chargeLastView", connection);
            adapter.Fill(tablecharge);

            SqlDataAdapter adapterService = new SqlDataAdapter("Select * from serviceChargeView", connection);
            adapter.Fill(serviceChargeTable);

            for (int i = 0; i < tablecharge.Rows.Count; i++)
            {
                if (Convert.ToDecimal(tablecharge.Rows[i][3])-Convert.ToDecimal(tablecharge.Rows[i][4])>0)
                {
                    tablecharge2.Rows.Add(tablecharge.Rows[i][0], tablecharge.Rows[i][1], tablecharge.Rows[i][2], (Convert.ToDecimal(tablecharge.Rows[i][3]) - Convert.ToDecimal(tablecharge.Rows[i][4])), "TL");

                }
            }
            tablecharge3 = tablecharge2;
            return tablecharge2;
        }
Exemplo n.º 16
0
    private void BindGrid()
    {
        string cmd = "SELECT username [UserName],hash [Password Hash], auth_level [Authentication Level] FROM LOGIN";
        DataSet ds = new DataSet();
        SqlConnection = new SqlConnection(ConfigurationManager.AppSettings["SQLAddress"]);
        SqlConnection.Open();
        SqlCommand = new SqlCommand(cmd, SqlConnection);
        SqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter(SqlCommand);

        SqlDataAdapter.Fill(ds, "tblMain");
        int totRecs = ds.Tables["tblMain"].Rows.Count;
        SqlDataAdapter.Fill(ds, startIndex, pageSize, "t1");

        GridView1.DataSource = ds.Tables["t1"];
        GridView1.DataBind();
        SqlDataAdapter.Dispose();
        SqlCommand.Dispose();

        System.Text.StringBuilder sbPager = new System.Text.StringBuilder();
        for (int i = 1; i <= totPages; i++)
        {
            sbPager.Append("<a href=\"About.aspx?pg=").Append(i.ToString()).Append("\">").Append(i.ToString()).Append("</a>");
            sbPager.Append("&nbsp;|&nbsp;");
        }

        divPager.InnerHtml = sbPager.ToString();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Nash"].ConnectionString);
        SqlCommand cmd = new SqlCommand("select * from Categories", con);
        SqlCommand cmd1 = new SqlCommand("select * from Products", con);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = cmd;
        DataSet dataSet = new DataSet();
        con.Open();
        adapter.Fill(dataSet, "Categories");
        adapter.SelectCommand = cmd1;
        adapter.Fill(dataSet, "Products");
        con.Close();
        DataRelation relation = new DataRelation("primary", dataSet.Tables["Categories"].Columns["CategoryID"], dataSet.Tables["Products"].Columns["CategoryID"]);
        dataSet.Relations.Add(relation);

        DataColumn column1 = new DataColumn("no. of products", typeof(int), "Count(Child(primary).CategoryID)");
        dataSet.Tables["Categories"].Columns.Add(column1);
        GridView1.DataSource = dataSet;
        GridView1.DataBind();

        //DataView view = new DataView(dataSet.Tables["Categories"]);
        //view.RowFilter = "Count(Child(primary).CategoryID) > 1";

        //GridView1.DataSource = view;    
        //GridView1.DataBind();

        //GridView1.DataSource = dataSet;
        //GridView1.DataMember = "Categories";
        //GridView1.DataBind();
    }
Exemplo n.º 18
0
        private void AbmCliente_Load(object sender, EventArgs e)
        {
            SqlConnection dbcon = new SqlConnection(GrouponDesktop.Properties.Settings.Default["conStr"].ToString());
            SqlCommand cmd = new SqlCommand(@"Select nombre, idCiudad
                                            from LOSGROSOS_RELOADED.Ciudad", dbcon);
            DataTable dt = new DataTable();
            DataTable dt2 = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);

            try
            {
                dbcon.Open();
                da.Fill(dt);
                da.Fill(dt2);

            }
            catch (Exception ex)
            {
                Support.mostrarError(ex.Message);
            }
            dbcon.Close();
            this.lstCiudadesElegidas.DataSource = dt;
            this.lstCiudadesElegidas.DisplayMember = "nombre";
            this.lstCiudadesElegidas.ValueMember = "idCiudad";
            this.cmbCiudades.DataSource = dt2;
            this.cmbCiudades.DisplayMember = "nombre";
            this.cmbCiudades.ValueMember = "idCiudad";

            DateTime fechaActual = Support.fechaConfig();
            this.monthCalendar1.MaxDate = fechaActual;
            this.monthCalendar1.TodayDate = fechaActual;
        }
Exemplo n.º 19
0
 private void FillDefaultData()
 {
     AccTypesTbl = new DataTable("FalseX");
     FinlAccTbl = new DataTable("FalseX");
     SqlDataAdapter da = new SqlDataAdapter("",FXFW.SqlDB.SqlConStr);
     try
     {
         //Load All Account Types
         da.SelectCommand.CommandText = "SELECT AccNatueID, AccNatueName FROM CDAccountNature";
         da.Fill(AccTypesTbl);
         //Load All Finall Accounts
         da.SelectCommand.CommandText = "SELECT KhtamiaccID, KhtamiaccName FROM CDKHTAMIACOUNT";
         da.Fill(FinlAccTbl);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     LUEAccType.Properties.DataSource = AccTypesTbl;
     LUEAccType.Properties.DisplayMember = "AccNatueName";
     LUEAccType.Properties.ValueMember = "AccNatueID";
     LUEAccEndCount.Properties.DataSource = FinlAccTbl;
     LUEAccEndCount.Properties.DisplayMember = "KhtamiaccName";
     LUEAccEndCount.Properties.ValueMember = "KhtamiaccID";
 }
Exemplo n.º 20
0
        private void Form1_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
            con.Open();
            SqlCommand comm = new SqlCommand("select * from UserData",con);

            DataTable master = new DataTable();
            DataTable child = new DataTable();

            // Fill Table 2 with Data
            SqlDataAdapter da = new SqlDataAdapter(comm);
            da.Fill(master);

               // Fill Table1 with data
            comm = new SqlCommand("select * from UserDetail",con);
            da.Fill(child);

            con.Close();

            DataSet ds = new DataSet();

            //Add two DataTables  in Dataset
            ds.Tables.Add(master);
            ds.Tables.Add(child);

            // Create a Relation in Memory
            DataRelation relation = new DataRelation("",ds.Tables[0].Columns[0],ds.Tables[1].Columns[0],true);
            ds.Relations.Add(relation);
            dataGrid1.DataSource = ds.Tables[0];
        }
Exemplo n.º 21
0
        public override void LoadSelectedData(DataSet currentDataSet, long IDNivel, long IDTipoFRDBase, IDbConnection conn)
		{
            using (SqlCommand command = SqlSyntax.CreateSelectCommandWithNoDeletedRowsParam((SqlConnection)conn))
            using (SqlDataAdapter da = new SqlDataAdapter(command))
			{
                command.Parameters.AddWithValue("@IDNivel", IDNivel);
                command.Parameters.AddWithValue("@IDTipoFRDBase", IDTipoFRDBase);
                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["Nivel"],
                    "WHERE ID=@IDNivel");
                da.Fill(currentDataSet, "Nivel");

				da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["FRDBase"],
                    "WHERE IDNivel=@IDNivel AND IDTipoFRDBase=@IDTipoFRDBase");
				da.Fill(currentDataSet, "FRDBase");

                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["ControloAut"],
                    "INNER JOIN NivelControloAut nca ON nca.IDControloAut = ControloAut.ID " +
                    "WHERE nca.ID=@IDNivel");
                da.Fill(currentDataSet, "ControloAut");

                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["ControloAutDatasExistencia"],
                    "INNER JOIN NivelControloAut nca ON nca.IDControloAut = ControloAutDatasExistencia.IDControloAut " +
                    "WHERE nca.ID=@IDNivel");
                da.Fill(currentDataSet, "ControloAutDatasExistencia");

                da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommandText(currentDataSet.Tables["NivelControloAut"],
                    "WHERE ID=@IDNivel");
                da.Fill(currentDataSet, "NivelControloAut");
			}
		}
Exemplo n.º 22
0
 protected void cvTitle_ServerValidate(object source, ServerValidateEventArgs args)
 {
     SqlDataAdapter da = new SqlDataAdapter("", connection);
     DataTable dt = new DataTable();
     DataTable dl = new DataTable();
     da.SelectCommand.CommandText = "SELECT * FROM Skills WHERE ID = @sxid";
     da.SelectCommand.Parameters.AddWithValue("@sxid", Request.QueryString["Sid"]);
     da.Fill(dl);
     //Consept : Check if TextBox' value has changed or not
     //If This part doesn't Exist -> the page won't be valid Because of the next part of Validation. WHY? ...
     //if the title isn't changed the next part cause invalidation beacuse the Title has already Exist
     if (dl.Rows[0]["Title"].ToString() != txtTitle.Text)
     {
         da.SelectCommand.CommandText = "SELECT * FROM Skills WHERE Title=@t AND Cat_ID=@scid";
         da.SelectCommand.Parameters.AddWithValue("@t", txtTitle.Text);
         da.SelectCommand.Parameters.AddWithValue("@scid", ddlSkillCat.SelectedValue);
         da.Fill(dt);
         //If the TextBox' Value has changed ...
         //So , Now Check if The New Value has already Exist in Table or not
         if (dt.Rows.Count == 0)
         {
             args.IsValid = true;
         }
         else
             args.IsValid = false;
     }
 }
Exemplo n.º 23
0
	protected void Page_Load(object sender, System.EventArgs e)
	{
		// Create the Connection, DataAdapter, and DataSet.
		string connectionString = "Data Source=localhost;Initial Catalog=Northwind;" +
			"Integrated Security=SSPI";
		SqlConnection con = new SqlConnection(connectionString);

		string sqlCat = "SELECT CategoryID, CategoryName FROM Categories";
		string sqlProd = "SELECT ProductName, CategoryID FROM Products";

		SqlDataAdapter da = new SqlDataAdapter(sqlCat, con);
		DataSet ds = new DataSet();

		try
		{
			con.Open();

			// Fill the DataSet with the Categories table.
			da.Fill(ds, "Categories");

			// Change the command text and retrieve the Products table.
			// You could also use another DataAdapter object for this task.
			da.SelectCommand.CommandText = sqlProd;
			da.Fill(ds, "Products");
		}
		finally
		{
			con.Close();
		}

		// Define the relationship between Categories and Products.
		DataRelation relat = new DataRelation("CatProds",
			ds.Tables["Categories"].Columns["CategoryID"],
			ds.Tables["Products"].Columns["CategoryID"]);
		// Add the relationship to the DataSet.
		ds.Relations.Add(relat);

		// Loop through the category records and build the HTML string.
		StringBuilder htmlStr = new StringBuilder("");
		foreach (DataRow row in ds.Tables["Categories"].Rows)
		{
			htmlStr.Append("<b>");
			htmlStr.Append(row["CategoryName"].ToString());
			htmlStr.Append("</b><ul>");

			// Get the children (products) for this parent (category).
			DataRow[] childRows = row.GetChildRows(relat);
			// Loop through all the products in this category.
			foreach (DataRow childRow in childRows)
			{
				htmlStr.Append("<li>");
				htmlStr.Append(childRow["ProductName"].ToString());
				htmlStr.Append("</li>");
			}
			htmlStr.Append("</ul>");
		}

		// Show the generated HTML code.
		HtmlContent.Text = htmlStr.ToString();
	}
Exemplo n.º 24
0
 public void GetData()
 {
     try
     {
         con = new SqlConnection(cs);
         con.Open();
         cmd = new SqlCommand("SELECT StockId as [Stock ID], (productName) as [Product Name],Features,sum(Quantity) as [Quantity],Price,sum(TotalPrice) as [Total Price] from Config,Stock where Config.ConfigID=Stock.ConfigID group by Stockid, productname,features,price having (sum(Quantity) > 0)  order by Productname", con);
         var myDA = new SqlDataAdapter(cmd);
         var myDataSet = new DataSet();
         myDA.Fill(myDataSet, "Stock");
         myDA.Fill(myDataSet, "Config");
         dataGridView1.DataSource = myDataSet.Tables["Stock"].DefaultView;
         dataGridView1.DataSource = myDataSet.Tables["Config"].DefaultView;
         con.Close();
         var header = new string[]
         { "รหัส", "ชื่อสินค้า", "รายละเอียด", "จำนวน", "ราคา", "รวม"
         };
         for (var i = 0; i < header.Length; i++)
         {
             dataGridView1.Columns[i].HeaderText = header[i];
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "ล้มเหลว", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        public DataSet GetDataSet()
        {
            try
            {
                using (SqlConnection conn = new SqlConnection())
                {
                    string connectionString = WebConfigurationManager.AppSettings["connectionString"];
                    conn.ConnectionString = connectionString;

                    SqlDataAdapter adapter = new SqlDataAdapter();
                    DataSet ds = new DataSet();
                    adapter.SelectCommand = new SqlCommand("SELECT * FROM Student", conn);
                    adapter.Fill(ds, "Student");
                    adapter.SelectCommand = new SqlCommand("SELECT * FROM Course", conn);
                    adapter.Fill(ds, "Course");
                    adapter.SelectCommand = new SqlCommand("SELECT * FROM SC", conn);
                    adapter.Fill(ds, "SC");
                    return ds;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 26
0
        public void LoadData()
        {
            //string mid = Session["Mid"].ToString();
            string mid = "930251337";
            SqlDataAdapter da = new SqlDataAdapter("", connection);
            DataTable dt = new DataTable();
            da.SelectCommand.CommandText = "SELECT * FROM MemberList WHERE Mid = @mid";
            da.SelectCommand.Parameters.AddWithValue("@mid", mid);
            da.Fill(dt);
            if (dt.Rows[0]["ImageExtention"].ToString().Length != 0)
            {
                imgProfile.ImageUrl = dt.Rows[0]["Image"].ToString() + dt.Rows[0]["ImageExtention"].ToString();
            }
            lblFullNameUP.Text = dt.Rows[0]["FullName"].ToString();
            lblMembershipStatusUP.Text = dt.Rows[0]["Status_ID"].ToString();
            lblFieldUP.Text = dt.Rows[0]["Title"].ToString();
            lblBioUP.Text = dt.Rows[0]["Bio"].ToString();

            if (dt.Rows[0]["Github"].ToString().Length == 0)
                github.Visible = false;
            else
            {
                lblgithub.Text ='/' + dt.Rows[0]["Github"].ToString();
                github.HRef = "https://github.com/" + dt.Rows[0]["Github"].ToString();
            }

            if (dt.Rows[0]["Linkedin"].ToString().Length == 0)
                linkedin.Visible = false;
            else
            {
                lblLinkedin.Text ='/' + dt.Rows[0]["Linkedin"].ToString();
                //linkedin.HRef = "https://Linkedin.com/" + dt.Rows[0]["Linkedin"].ToString();
            }

            if (dt.Rows[0]["Twitter"].ToString().Length == 0)
                twitter.Visible = false;
            else
            {
                lblTwitter.Text ='/' + dt.Rows[0]["Twitter"].ToString();
                //twitter.HRef = "https://Twitter.com/" + dt.Rows[0]["Twitter"].ToString();
            }
            lblFirstName.Text = dt.Rows[0]["FirstName"].ToString();
            lblLastName.Text = dt.Rows[0]["LastName"].ToString();
            lblField.Text = dt.Rows[0]["Title"].ToString();
            lblPhone1.Text = dt.Rows[0]["PhoneNumber"].ToString();
            lblPhone2.Text = dt.Rows[0]["AltPhoneNumber"].ToString();
            lblEmail.Text = dt.Rows[0]["Email"].ToString();
            lblNationalID.Text = dt.Rows[0]["NationalID"].ToString();
            lblStudentID.Text = dt.Rows[0]["Mid"].ToString();
            da.SelectCommand.Parameters.Clear();
            dt.Clear();
            da.SelectCommand.CommandText = "SELECT * FROM MemberSkillList WHERE Member_ID = @mid2";
            da.SelectCommand.Parameters.AddWithValue("@mid2", mid);
            da.Fill(dt);
            dlSkills.DataSource = dt;
            dlSkills.DataBind();
            da.SelectCommand.Parameters.Clear();
            dt.Clear();
        }
Exemplo n.º 27
0
        /// <summary>
        /// xử lý sự kiện khi ấn nút submit, bao gồm nhập dữ liệu cho 2 bảng là User và UserResult
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (txtName.Text != null)
            {
                /*--khai báo tất cả các component từ việc nạp dữ liệu--*/
                //query cho bảng User dùng để add User
                string queryForAddUser = "******";
                //query cho bảng UserResult dùng để add UserResult
                string queryForAddUserInUserResult = "select * from [PrePool].[dbo].[UserResult]";
                SqlDataAdapter adapter1 = new SqlDataAdapter(queryForAddUser, conn);
                SqlDataAdapter adapter2 = new SqlDataAdapter(queryForAddUserInUserResult, conn);
                SqlCommandBuilder builder = new SqlCommandBuilder(adapter1);
                SqlCommandBuilder builder2 = new SqlCommandBuilder(adapter2);
                adapter1.Fill(ds, "User");
                adapter2.Fill(ds, "UserResult");

                //khai báo 2 trường name và mail trong table User
                string name = txtName.Text;
                string mail = txtEmail.Text;

                //add value cho bảng User
                DataRow newAdmin = ds.Tables["User"].NewRow();
                //add 2 collumn name va email (id tu tăng)
                newAdmin["name"] = name;
                newAdmin["email"] = mail;
                ds.Tables["User"].Rows.Add(newAdmin);
                adapter1.Update(ds.Tables["User"]);

                /*-- xu ly để lấy userId và resultId --*/
                //đổ lại vào table User
                adapter1.Fill(ds, "User");
                //lay vị trí của row vừa add
                int count = ds.Tables["User"].Rows.Count - 1;
                //xuat ra [id] cua row moi nhat - row vua add
                string userIdStringType = ds.Tables["User"].Rows[count]["id"].ToString();
                //userId
                int userId = Int32.Parse(userIdStringType);
                //resultId lấy từ text cua checkbox
                int resultId;

                //add value cho bang UserResult với từng chechbox được check
                foreach (CheckBox cb in checkedList)
                {
                    DataRow newUserResult = ds.Tables["UserResult"].NewRow();
                    resultId = Int32.Parse(cb.Text);
                    //add 2 collumn resultId va userId
                    newUserResult["resultId"] = resultId;
                    newUserResult["userId"] = userId;
                    ds.Tables["UserResult"].Rows.Add(newUserResult);
                }
                adapter2.Update(ds.Tables["UserResult"]);
                //cảm ơn người dùng
                MsgBox("ありがとうございます");

            }
            //refresh lại trang mới
            checkedList.Clear();
            Page.Response.Redirect(Page.Request.Url.ToString(), true);
        }
Exemplo n.º 28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string v_term= "";
            string cmdText_TermsSearchResult = "";
            string cmdText_categoryBreadCrumb = "";

            cmdText_TermsSearchResult = "SELECT Term_Key, Term_Name, Parent_Category, Short_Description,Long_Description,Status FROM Terms where term_name like @Term_Name and active='Y' order by Term_Name";

            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "WITH Hierarchy(Term_Key, Category_key, Category_Name, Parent_category, HLevel) AS ( ";
            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "select te.term_key, ca.category_key, ca.category_name, ca.parent_category, 0 as Hlevel ";
            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "from categories ca, (SELECT Term_Key, Term_Name, Parent_Category FROM Terms where term_name like @Term_Name and active='Y') te ";
            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "where (upper(te.parent_category) = upper(ca.parent_category+'>>'+ca.category_name) ";
            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "or upper(te.parent_category) = upper(ca.category_name) ) and ca.active='Y' ";
            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "UNION ALL ";
            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "SELECT child.term_key, parent.category_key, parent.category_name, parent.parent_category,HLevel + 1 ";
            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "FROM Categories parent ";
            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "INNER JOIN Hierarchy child ";
            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "ON  upper(child.parent_category) = upper(case when isnull(parent.parent_category,'')='' then parent.category_name else parent.parent_category+'>>'+parent.category_name end) ) ";
            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "SELECT term_key, Category_key, Category_Name, Parent_category, HLevel FROM  Hierarchy ";
            cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "ORDER BY term_key, HLevel DESC ";

               // cmdText_categoryBreadCrumb = cmdText_categoryBreadCrumb + "SELECT terms.term_key, Results.OrderOfOccurrence, Results.StringName, Category_key FROM categories, terms OUTER APPLY dbo.SplitString(terms.parent_category,'>>') AS Results WHERE term_name like @Term_Name and Results.StringName = categories.Category_name order by term_key, Results.OrderOfOccurrence ";

            if (!string.IsNullOrEmpty(Request["query"]))
            {
                if (Request["hdnSearchType"] == "srchBox")
                    v_term = '%' + Request["query"] + '%';
                else
                    v_term = Request["query"] + '%';
            }
            else
            {
                Response.Redirect("default.aspx");
            }

            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
            SqlDataAdapter cmd = new SqlDataAdapter();
            DataSet ds = new DataSet();
            SqlCommand selectCMD = new SqlCommand();

            selectCMD = new SqlCommand(cmdText_TermsSearchResult, conn);
            selectCMD.Parameters.Add("@Term_Name", SqlDbType.NVarChar, 255).Value = v_term;
            cmd.SelectCommand = selectCMD;
            cmd.Fill(ds, "Terms");

            selectCMD = new SqlCommand(cmdText_categoryBreadCrumb, conn);
            selectCMD.Parameters.Add("@Term_Name", SqlDbType.NVarChar, 255).Value = v_term;
            cmd.SelectCommand = selectCMD;
            cmd.Fill(ds, "Category");

            ds.Relations.Add("myrelation",
            ds.Tables["Terms"].Columns["term_key"],
            ds.Tables["Category"].Columns["term_key"]);

            rptrSearchResult.DataSource = ds.Tables["Terms"];
            Page.DataBind();

            conn.Close();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            QAQuestions pitanje = new QAQuestions();
            List<QAQuestions> Pitanja = new List<QAQuestions>();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            DataRow dr = null;

            string Question = Request.QueryString["IdQuestion"];

            SqlCommand cmd = new SqlCommand("SELECT dbo.QAPitanja.Id AS IdPitanje, dbo.QAPitanja.NaslovPitanja, dbo.QAPitanja.Pitanje FROM dbo.QAPitanja Where dbo.QAPitanja.Id=@IdPitanje", connection);
            cmd.Parameters.AddWithValue("@IdPitanje", Question);

            dt.Columns.Add("IdPitanje");
            dt.Columns.Add("NaslovPitanja");
            dt.Columns.Add("Pitanje");

            connection.Open();
            try
            {
                SqlDataAdapter da = new SqlDataAdapter(cmd);

                da.Fill(ds, "QAPitanja");
                da.Fill(dt);

                SqlDataReader reader = cmd.ExecuteReader();
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    dr = dt.NewRow();
                    dr["IdPitanje"] = ds.Tables[0].Rows[i]["IdPitanje"].ToString();
                    dr["NaslovPitanja"] = ds.Tables[0].Rows[i]["NaslovPitanja"].ToString();
                    dr["Pitanje"] = ds.Tables[0].Rows[i]["Pitanje"].ToString();

                    reader.Close();
                    connection.Close();

                    pitanje = new QAQuestions();

                    pitanje.Id = Convert.ToInt32(dr["IdPitanje"].ToString());
                    pitanje.NaslovPitanja = dr["NaslovPitanja"].ToString();
                    pitanje.Pitanje = dr["Pitanje"].ToString();

                }
            }
            catch (Exception ex) { }
            finally
            {
                connection.Close();
            }

            Pitanja.Add(pitanje);
            Repeater1.DataSource = Pitanja;
            Repeater1.DataBind();
            if (!Page.IsPostBack)
            {
                txtPrijedlogNaslova.Text = pitanje.NaslovPitanja;
                txtPrijedlogPitanja.Text = pitanje.Pitanje;
            }
        }
Exemplo n.º 30
0
 public void buscar(string sql)
 {
     cmd = new SqlCommand(sql, Conexion.conectar());
     da = new SqlDataAdapter(cmd);
     da.Fill(dt);
     da.Fill(ds);
     Conexion.desconectar();
 }
Exemplo n.º 31
0
        public ActionResult Register(RegisterViewModal rg)
        {
            sayazilimEntities db = new sayazilimEntities();

            try
            {
                var firmalarlist = db.Firmalar.Where(x => x.FirmaEMail == rg.Email).ToList();

                if (firmalarlist.Count == 0)
                {
                    Firmalar fr = new Firmalar();

                    fr.FirmaAdi = rg.FirmaIsmi;
                    string sifre = rg.Password;
                    fr.FirmaEMail = rg.Email;
                    fr.FirmaTel   = rg.FirmaTel;
                    var firmalist = db.Firmalar.OrderByDescending(x => x.ID).FirstOrDefault();
                    if (firmalist != null)
                    {
                        int i = Convert.ToInt32(firmalist.FirmaID + 1);
                        fr.FirmaID = i;
                    }
                    else
                    {
                        fr.FirmaID = 2;
                    }

                    DateTime kayittarih = DateTime.Now;

                    kayittarih    = kayittarih.AddDays(15);
                    fr.KayitTarih = kayittarih;


                    Personel pr = new Personel();
                    pr.Adi           = "Admin";
                    pr.Soyadi        = "";
                    pr.Pozisyonu     = "Admin";
                    pr.PersonelGrubu = "Admin";
                    pr.FirmaID       = Convert.ToInt16(fr.FirmaID);
                    pr.sCariID       = -1;
                    pr.WebKA         = rg.KullaniciAdi;
                    pr.WebSifre      = GirisKontrol.hash(sifre, true);
                    fr.Demo          = true;
                    db.Personel.Add(pr);
                    db.Firmalar.Add(fr);
                    db.SaveChanges();



                    #region YeniFirmaKontrol
                    int firmaid = Convert.ToInt16(pr.FirmaID);
                    var setting = db.Ayarlar.Where(x => x.FirmaID == firmaid).ToList();
                    if (setting.Count == 0)
                    {
                        DataRow dt = null;
                        using (SqlConnection con = new SqlConnection(AyarMetot.conString))
                        {
                            if (con.State == ConnectionState.Closed)
                            {
                                con.Open();
                            }
                            using (SqlDataAdapter da =
                                       new System.Data.SqlClient.SqlDataAdapter(
                                           "select * from AYARLAR where ID='1'", con))
                            {
                                using (SqlCommandBuilder cb = new SqlCommandBuilder(da))
                                {
                                    DataSet ds = new DataSet();
                                    da.Fill(ds, "AYARLAR");
                                    DataRow[] adf = ds.Tables["AYARLAR"].Select("ID='1'");
                                    if (adf.Length != 0)
                                    {
                                        dt = adf[0];
                                    }
                                }
                            }
                        }
                        using (SqlConnection con = new SqlConnection(AyarMetot.strcon))
                        {
                            if (con.State == ConnectionState.Closed)
                            {
                                con.Open();
                            }
                            using (SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("select Top 1 * from AYARLAR where FirmaID=" + firmaid.ToString(), con))
                            {
                                using (SqlCommandBuilder cb = new SqlCommandBuilder(da))
                                {
                                    DataSet ds = new DataSet();
                                    da.Fill(ds, "AYARLAR");
                                    DataRow df = ds.Tables["AYARLAR"].NewRow();
                                    df.ItemArray  = dt.ItemArray.Clone() as object[];
                                    df["FirmaID"] = fr.FirmaID;

                                    df["Version"]             = KODLA.Kapa(rg.Pakettipi, AyarMetot.ilhan_Control);
                                    df["fMail"]               = "";
                                    df["fMailSifre"]          = "";
                                    df["fMailSender"]         = "";
                                    df["SMSUser"]             = "";
                                    df["SMSPass"]             = "";
                                    df["MesajSonu"]           = "";
                                    df["BorcMesajSonu"]       = "";
                                    df["SmsSender"]           = "";
                                    df["EFatGB"]              = "";
                                    df["EFatKA"]              = "";
                                    df["EFatSifre"]           = "";
                                    df["EIrsKA"]              = "";
                                    df["EIrsSF"]              = "";
                                    df["KurumKodu"]           = "";
                                    df["EIrsGB"]              = "";
                                    df["Entegrator"]          = "";
                                    df["PostaSunucu"]         = "";
                                    df["ServisBorclandirsin"] = 1;
                                    string company_code = "SA01" + fr.FirmaID.ToString().PadLeft(3, '0');
                                    df["Company_Code"] = company_code;
                                    ds.Tables["AYARLAR"].Rows.Add(df);
                                    da.Update(ds, "AYARLAR");
                                }
                            }
                        }
                    }
                    var compony = db.COMPANY_DETAIL.Where(x => x.FirmaID == firmaid).ToList();
                    if (compony.Count == 0)
                    {
                        DataRow dt = null;
                        using (SqlConnection con = new SqlConnection(AyarMetot.conString))
                        {
                            if (con.State == ConnectionState.Closed)
                            {
                                con.Open();
                            }
                            using (SqlDataAdapter da =
                                       new System.Data.SqlClient.SqlDataAdapter(
                                           "select * from COMPANY_DETAIL where ID='1'", con))
                            {
                                using (SqlCommandBuilder cb = new SqlCommandBuilder(da))
                                {
                                    DataSet ds = new DataSet();
                                    da.Fill(ds, "COMPANY_DETAIL");
                                    DataRow[] adf = ds.Tables["COMPANY_DETAIL"].Select("ID='1'");
                                    if (adf.Length != 0)
                                    {
                                        dt = adf[0];
                                    }
                                }
                            }
                        }
                        using (SqlConnection con = new SqlConnection(AyarMetot.strcon))
                        {
                            if (con.State == ConnectionState.Closed)
                            {
                                con.Open();
                            }
                            using (SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("select Top 1 * from COMPANY_DETAIL", con))
                            {
                                using (SqlCommandBuilder cb = new SqlCommandBuilder(da))
                                {
                                    DataSet ds = new DataSet();
                                    da.Fill(ds, "COMPANY_DETAIL");
                                    DataRow df = ds.Tables["COMPANY_DETAIL"].NewRow();
                                    df.ItemArray = dt.ItemArray.Clone() as object[];
                                    Firmalar frm = db.Firmalar.Where(x => x.FirmaID == firmaid).FirstOrDefault();
                                    df["FirmaAdi"] = frm.FirmaAdi;
                                    string company_code = "SA01" + fr.FirmaID.ToString().PadLeft(3, '0');
                                    df["Company_Code"] = company_code;
                                    Personel pb = db.Personel.OrderByDescending(x => x.ID).FirstOrDefault();
                                    df["IlgiliKisi"] = (pb.Adi + pb.Soyadi).TrimEnd();
                                    Firmalar dr = db.Firmalar.Where(x => x.FirmaID == firmaid).FirstOrDefault();
                                    df["Telefon"]        = dr.FirmaTel;
                                    df["Faks"]           = "";
                                    df["ePosta"]         = dr.FirmaEMail;
                                    df["WebSite"]        = "";
                                    df["VergiDairesi"]   = "";
                                    df["VergiNo"]        = "";
                                    df["Ulke"]           = "";
                                    df["Sehir"]          = "";
                                    df["PostaKodu"]      = "";
                                    df["Adres"]          = "";
                                    df["TicaretSicilNo"] = "";
                                    df["MersisNo"]       = "";
                                    df["Ilce"]           = "";
                                    df["FirmaID"]        = fr.FirmaID;

                                    ds.Tables["COMPANY_DETAIL"].Rows.Add(df);
                                    da.Update(ds, "COMPANY_DETAIL");
                                }
                            }
                        }
                    }

                    var stk_ktg = db.STK_KATEGORI.Where(x => x.FirmaID == firmaid).ToList();
                    if (stk_ktg.Count == 0)
                    {
                        int i = 7;
                        for (int j = 1; j < i; j++)
                        {
                            STK_KATEGORI stk = new STK_KATEGORI();
                            stk.FirmaID = fr.FirmaID;
                            stk.Name    = "Stok Kategori " + j;
                            string company_code = "SA01" + fr.FirmaID.ToString().PadLeft(3, '0');
                            stk.Company_Code = company_code;
                            db.STK_KATEGORI.Add(stk);
                            db.SaveChanges();
                        }
                    }

                    var special = db.SPECIAL_TECH.Where(x => x.FirmaID == firmaid).ToList();
                    if (special.Count == 0)
                    {
                        int i = 11;
                        for (int j = 1; j < i; j++)
                        {
                            SPECIAL_TECH stk = new SPECIAL_TECH();
                            stk.FirmaID = Convert.ToInt16(fr.FirmaID);
                            stk.Name    = "Özel Alan " + j;
                            string company_code = "SA01" + fr.FirmaID.ToString().PadLeft(3, '0');
                            stk.Company_Code = company_code;
                            db.SPECIAL_TECH.Add(stk);
                            db.SaveChanges();
                        }
                    }


                    var carikategori = db.CARI_KATEGORI.Where(x => x.FirmaID == firmaid).ToList();
                    if (carikategori.Count == 0)
                    {
                        int i = 7;
                        for (int j = 1; j < i; j++)
                        {
                            CARI_KATEGORI stk = new CARI_KATEGORI();
                            stk.FirmaID = firmaid;
                            stk.Name    = "Cari Kategori " + j;
                            string company_code = "SA01" + fr.FirmaID.ToString().PadLeft(3, '0');
                            stk.Company_Code = company_code;
                            db.CARI_KATEGORI.Add(stk);
                            db.SaveChanges();
                        }
                    }
                    var faturaekbilgi = db.INVOICE_OZEL.Where(x => x.FirmaID == firmaid).ToList();
                    if (carikategori.Count == 0)
                    {
                        int i = 9;
                        for (int j = 1; j < i; j++)
                        {
                            INVOICE_OZEL stk = new INVOICE_OZEL();
                            stk.FirmaID         = firmaid;
                            stk.Name            = "Fature Ek Bilgi " + j;
                            stk.EfaturadaGonder = false;
                            string company_code = "SA01" + fr.FirmaID.ToString().PadLeft(3, '0');
                            stk.Company_Code = company_code;
                            db.INVOICE_OZEL.Add(stk);
                            db.SaveChanges();
                        }
                    }


                    #endregion


                    Session["FirmaAdi"] = fr.FirmaAdi;
                    MailOkey(rg);
                    return(RedirectToAction("Login", "Login"));
                }
                else
                {
                    return(View());
                }
            }
            catch (Exception e)
            {
                return(View());
            }
        }
Exemplo n.º 32
0
        public System.Data.DataTable getprec()
        {
            DateTime strFechaInicial = Convert.ToDateTime(dtinicial.SelectedDate);
            DateTime strFechaFinal   = Convert.ToDateTime(dtfinal.SelectedDate);
            string   conect          = GetOrigen(intEMPRESAID);

            System.Data.DataTable Tabla = new System.Data.DataTable();
            //string strFuncion = "Select  Codigo_De_Articulo AS codigo, Descripcion AS Descripcion, Importe_Total AS Total,Fecha_Y_Hora_De_Ultima_Actualizacion as Fecha " +
            //    "FROM  Facturas_Y_Devoluciones_Detalle INNER JOIN Facturas_Y_Devoluciones ON Facturas_Y_Devoluciones_Detalle.Numero_De_Documento = Facturas_Y_Devoluciones.Numero_De_Documento" +
            //    " WHERE(Codigo_De_Empleado = '"+noemployed+ "') AND  Facturas_Y_Devoluciones.Fecha_Y_Hora_De_Ultima_Actualizacion BETWEEN '" + strFechaInicial + "' AND '" + strFechaFinal + "'";

            string strFuncion = "SELECT * from dbo.fncoperarios(@FechaInicial,@FechaFinal,@noempleado);";

            try
            {
                using (System.Data.SqlClient.SqlConnection Cnn = new System.Data.SqlClient.SqlConnection(conect))
                {
                    //Cnn.ConnectionTimeout = 500;
                    using (System.Data.SqlClient.SqlCommand Cmd = new System.Data.SqlClient.SqlCommand(strFuncion, Cnn))
                    {
                        try
                        {
                            //
                            Cmd.CommandType    = CommandType.Text;
                            Cmd.CommandTimeout = 360;
                            Cmd.Parameters.Add("@FechaInicial", SqlDbType.SmallDateTime).Value = strFechaInicial;
                            Cmd.Parameters.Add("@FechaFinal", SqlDbType.SmallDateTime).Value   = strFechaFinal;
                            Cmd.Parameters.Add("@noempleado", SqlDbType.SmallInt).Value        = Convert.ToInt32(noemployed);


                            System.Data.SqlClient.SqlDataAdapter Datos = new System.Data.SqlClient.SqlDataAdapter(Cmd);

                            Cnn.Open();
                            Datos.Fill(Tabla);
                            return(Tabla);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error de acceso a datos, Error: " + ex.ToString());
                        }
                        finally
                        {
                            if (Cnn.State == ConnectionState.Open)
                            {
                                Cnn.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception z)
            {
                RadWindow radWindow = new RadWindow();
                RadWindow.Alert(new DialogParameters()
                {
                    Content = "Error al acceso de datos .",
                    Header  = "BIG",

                    DialogStartupLocation = WindowStartupLocation.CenterOwner
                                            // IconContent = "";
                });
                return(Tabla);
            }
        }
Exemplo n.º 33
0
        ///// <summary>
        ///// 初始化界面网格控件
        ///// </summary>
        ///// <param name="Grid">DataGridView 控件</param>
        //public virtual void InitColumns(DataGridView Grid)
        //{

        //}
        #endregion

        #region 加载数据(返回DataTable)
        /// <summary>
        /// 加载数据(返回DataTable)
        /// </summary>
        /// <param name="ConnStr">连接字符串</param>
        /// <param name="strSQL">SQL语句</param>
        /// <param name="strTableName">DataTable表名</param>
        /// <param name="isTable">是否对应有物理表,需要有更新、保存等命令</param>
        public static SD.DataTable GetData(string ConnStr, string strSQL, string strTableName, bool isTable)
        {
            SD.DataTable dt = new SD.DataTable(strTableName);

            try
            {
                using (sqlconn = new SDC.SqlConnection(ConnStr))
                {
                    //sqlconn.Open();

                    using (sqlcmd = new SDC.SqlCommand(strSQL, sqlconn))
                    {
                        //if (sqlcmd == null)
                        //{
                        //    using (dt = new SD.DataTable(strTableName))
                        //    {
                        //        return dt;
                        //    }
                        //}


                        using (sqladp = new SDC.SqlDataAdapter(sqlcmd))
                        {
                            if (isTable)
                            {
                                using (sqlcmdbd = new SDC.SqlCommandBuilder(sqladp))
                                {
                                    sqlcmdbd.ConflictOption = SD.ConflictOption.CompareAllSearchableValues;

                                    sqladp.InsertCommand = sqlcmdbd.GetInsertCommand();
                                    sqladp.UpdateCommand = sqlcmdbd.GetUpdateCommand();
                                    sqladp.DeleteCommand = sqlcmdbd.GetDeleteCommand();

                                    sqladp.Fill(dt);

                                    return(dt);
                                }
                            }
                            else
                            {
                                sqladp.Fill(dt);

                                return(dt);
                            }
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sqlconn != null)
                {
                    if (sqlconn.State != SD.ConnectionState.Closed)
                    {
                        sqlconn.Close();
                    }

                    sqlconn.Dispose();
                }
            }
        }
Exemplo n.º 34
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            System.IO.MemoryStream stream1 = new System.IO.MemoryStream();
            string path   = "";
            string LinkId = "";

            String StudentID = Request.QueryString["studid"];

            DataSet ds = new DataSet();
            System.Data.SqlClient.SqlDataAdapter da = default(System.Data.SqlClient.SqlDataAdapter);
            string strSQL = null;


            dynamic SQLcon = new SqlConnection(ConfigurationManager.ConnectionStrings["SkylineUniversityConnPortal"].ToString());
            try
            {
                strSQL = "exec SHP_ApplicationForm '" + StudentID + "'";

                // strSQL = "SELECT  staffdetails.Empid, staffdetails.empname, staffdetails.empdesignation, staffdetails.empdepartment, staffdetails.etype, staffdetails.priority, staffdetails.phoneno, staffdetails.emailid, staffdetails.epassword, staffdetails.eAddress, staffdetails.qulification, staffdetails.imagedata, staffdetails.imgetype, staffdetails.imagelength, staffdetails.extno, tb_advising.f_id, tb_advising.stud_id, tb_advising.sap_status, tb_advising.Conditionaladmission, tb_advising.repeatingcourse, tb_advising.toc_Course, EMPMASTER.OFFICEEXT FROM   staffdetails INNER JOIN tb_advising ON staffdetails.Empid = tb_advising.f_id INNER JOIN EMPMASTER ON staffdetails.Empid = EMPMASTER.EMPID where tb_advising.stud_id='" & Session["StudentID"] & "'"
                da = new System.Data.SqlClient.SqlDataAdapter(strSQL, SQLcon);
                da.Fill(ds);
            }
            catch
            {
            }

            try
            {
                LinkId = Session["LinkId"].ToString();
            }
            catch
            {
                LinkId = ds.Tables[0].Rows[0]["LinkID"].ToString();
            }
            string UName = Request.QueryString["UName"].ToString();


            if (UName.Contains(".pdf"))
            {
            }
            else
            {
                if (UName == "FS")
                {
                }
                else if (UName == "FW")
                {
                }
// PLEASE CHECK IT
                else if (UName == "FO")
                {
                }

                else if (UName == "MQP")
                {
                }
                else if (UName == "MC")
                {
                }

                else
                {
                    string RegNo = ds.Tables[0].Rows[0]["RegistrationNo_CDB"].ToString();
                    path = "~/" + UName + ".rpt";
                    path = Server.MapPath(path);
                    rptStudent.Load(path);
                    if ((UName == "ENROLLMENTFORM") || (UName.Contains("hostel_application")) || (UName == "local_guardian_visa_application") || (UName == "Student_Visa_Processing_request_Form") || (UName == "Student_personal_details_visa_applcation"))
                    {
                        rptStudent.SetParameterValue("@LinkId", LinkId);
                    }
                    else if ((UName == "CpdEventsReportMain"))
                    {
                    }
                    else if ((UName == "RPT_INSTRUCTION"))
                    {
                    }
                    else if ((UName == "RefundPolicy"))
                    {
                    }
                    else if ((UName == "MktCheckListReport"))
                    {
                    }
                    else if ((UName == "RefundPolicy - MQP"))
                    {
                    }
                    else
                    {
                        rptStudent.SetParameterValue("@registerid", LinkId);
                    }
                }
                rptStudent.SetDatabaseLogon("software", "DelFirMENA$idea");
                CrystalReportViewer1.Visible      = false;
                CrystalReportViewer1.ReportSource = rptStudent;
                CrystalReportViewer1.DataBind();
                CrystalReportViewer1.HasCrystalLogo           = false;
                CrystalReportViewer1.HasDrilldownTabs         = false;
                CrystalReportViewer1.HasDrillUpButton         = false;
                CrystalReportViewer1.HasGotoPageButton        = true;
                CrystalReportViewer1.HasPageNavigationButtons = true;

                CrystalReportViewer1.HasRefreshButton              = false;
                CrystalReportViewer1.HasSearchButton               = false;
                CrystalReportViewer1.HasToggleGroupTreeButton      = false;
                CrystalReportViewer1.HasToggleParameterPanelButton = false;

                CrystalReportViewer1.BackColor = System.Drawing.Color.White;

                System.IO.Stream oStream   = null;
                byte[]           byteArray = null;
                oStream   = rptStudent.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                byteArray = new byte[oStream.Length];
                oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(byteArray);
                Response.Flush();
                Response.Close();
                rptStudent.Close();
                rptStudent.Dispose();
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
        void AttachedMCGrid()
        {
            string str = "SELECT imcid as iMissionClearanceId FROM tblDocSend where iDocSendID =  " + iDocSendID + "";



            SqlConnection  cn  = new SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);
            SqlDataAdapter ad  = new System.Data.SqlClient.SqlDataAdapter(str, cn);
            DataSet        ds1 = new DataSet();

            ad.Fill(ds1);

            int viemcid = 0;

            if (ds1.Tables[0].Rows[0]["iMissionClearanceId"].ToString() == "")
            {
                viemcid = 0;
            }
            else
            {
                viemcid = Convert.ToInt32(ds1.Tables[0].Rows[0]["iMissionClearanceId"]);
            }

            if (viemcid > 0)
            {
                //SqlConnection cn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);

                //cn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);

                //  string strgetuser = "******" + hdnmcid.Value;
                string         strgetuser = "******" + ds1.Tables[0].Rows[0]["iMissionClearanceId"];
                SqlDataAdapter adUSer     = new System.Data.SqlClient.SqlDataAdapter(strgetuser, cn);
                DataSet        dsUser     = new DataSet();
                adUSer.Fill(dsUser);



                if (ds1.Tables[0].Rows.Count > 0)
                {
                    dtAttached.Columns.Add("url");
                    //string[] str = Directory.GetFiles(Server.MapPath(@"/writereaddata/"), MCID + "*.pdf", SearchOption.AllDirectories);
                    string[] str1 = null;
                    if (Directory.Exists(Server.MapPath(@"/writereaddata/" + MCID)))
                    {
                        str1 = Directory.GetFiles(Server.MapPath(@"/writereaddata/" + ds1.Tables[0].Rows[0]["iMissionClearanceId"].ToString() + "/"), "*", SearchOption.TopDirectoryOnly);
                    }


                    hdnMCID.Value = ds1.Tables[0].Rows[0]["iMissionClearanceId"].ToString();

                    if (str1.Length > 0)
                    {
                        str1 = Directory.GetFiles(Server.MapPath(@"/writereaddata/" + ds1.Tables[0].Rows[0]["iMissionClearanceId"].ToString() + "/"), "*", SearchOption.TopDirectoryOnly);

                        hdnMCID.Value = ds1.Tables[0].Rows[0]["iMissionClearanceId"].ToString();

                        if (str1.Length > 0)
                        {
                            for (int i = 0; i < str1.Length; i++)
                            {
                                DataRow dr = dtAttached.NewRow();
                                dr[0] = Path.GetFileName(str1[i]);
                                dtAttached.Rows.Add(dr);
                            }
                        }
                    }

                    Visibles(false, true, false);
                    btnReply.Visible = true;          //Modified for reply enable while view in mission docs.
                }
                // Visible(false, true, false);

                gvmcatt.DataSource = dtAttached;
                gvmcatt.DataBind();



                string sql = "Select * from tblmc where iMissionClearanceId=" + hdnMCID.Value;

                // SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);
                SqlDataAdapter ad1  = new System.Data.SqlClient.SqlDataAdapter(sql, cn);
                DataSet        ds11 = new DataSet();
                ad1.Fill(ds11);

                if ((((UserDetails)Session[clsConstant.TOKEN]).AgencyID.ToString() == "7") && (ds11.Tables[0].Rows[0]["bMissionApproved"].ToString() == "no" || ds11.Tables[0].Rows[0]["bMissionApproved"].ToString() == "PC"))



                // if ((((UserDetails)Session[clsConstant.TOKEN]).AgencyID.ToString() == "7"))
                {
                    hlink.Visible = true;
                }
                else
                {
                    hlink.Visible = false;
                }
            }
        }
Exemplo n.º 36
0
        public DataTable GetDataSet(string sqlstr, CommandType CmdType)
        {
            string msg = "";
            bool   chk = false;

            if (DirtyWords.Length > 0)
            {
                foreach (String s in DirtyWords)
                {
                    if (sqlstr.ToUpper().IndexOf(s.ToUpper()) > -1)
                    {
                        chk = true;
                    }
                }
            }
            DataTable DS = new DataTable();

            if (chk)
            {
                WriteLog("[" + DateTime.Now.ToLongTimeString() + "][Main.GetDataSet.Error]:Here is Somthing Wrong!!\n\r" + sqlstr);
                return(DS);
            }
            try
            {
                CMD.Connection  = CONN;
                CMD.CommandText = sqlstr;
                CMD.CommandType = CmdType;
                ADP             = new SqlDataAdapter(CMD);
                ADP.Fill(DS);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            finally
            {
                if (CONN.State == ConnectionState.Open)
                {
                    CONN.Close();
                }
            }


            try  //log用另外的try防止檔案被咬
            {
                if (msg != "")
                {
                    WriteCMD();
                    WriteLog("[" + DateTime.Now.ToLongTimeString() + "][Main.GetDataSet.Error]:" + msg + sqlstr);
                }
                else
                {
                    if (LogStat >= 1)
                    {
                        WriteCMD();
                    }
                    WriteLogselect(sqlstr);
                }
            }
            catch { }

            return(DS);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        // try{
        string mac;

        System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();

        con.ConnectionString = ConfigurationManager.ConnectionStrings["mayeDb"].ConnectionString;
        NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
        mac = nics[0].GetPhysicalAddress().ToString();
        if (con.State == System.Data.ConnectionState.Closed)
        {
            con.Open();
        }
        SqlCommand cmd   = new SqlCommand("select count(id) from customer where mac_address like '" + mac + "'", con);
        int        count = Convert.ToInt16(cmd.ExecuteScalar());

        macadd.Value = mac.ToString();

        if (count > 0)
        {
            SqlCommand cmd1 = new SqlCommand("select top 1 concat(fname,' ',lname) from customer where mac_address like '" + mac + "' order by last_login desc", con);
            SqlCommand cmd2 = new SqlCommand("select top 1 id from customer where mac_address like '" + mac + "' order by last_login desc", con);

            String nameLog = cmd1.ExecuteScalar().ToString();
            custId.Value = cmd2.ExecuteScalar().ToString();
            name1.Value  = nameLog.ToString();
            SqlCommand cmd5    = new SqlCommand("select count(custId) from cart where custId like '" + custId.Value + "'", con);
            int        countId = Convert.ToInt16(cmd5.ExecuteScalar());
            if (countId == 0)
            {
                SqlCommand cmd4 = new SqlCommand("insert into cart (custId, mac , prodQty,price) values ('" + custId.Value + "', '" + mac + "', 0,0)", con);
                cmd4.ExecuteScalar();
            }
        }
        else
        {
            name1.Value = "Guest User";
            SqlCommand cmd3 = new SqlCommand("insert into customer (fname, mac_address, last_login) values ('Guest User', '" + mac + "', CURRENT_TIMESTAMP)", con);
            SqlCommand cmd2 = new SqlCommand("select top 1 id from customer where mac_address like '" + mac + "' order by last_login desc", con);
            cmd3.ExecuteNonQuery();

            custId.Value = cmd2.ExecuteScalar().ToString();
            SqlCommand cmd5    = new SqlCommand("select count(Id) from customer where Id like '" + custId.Value + "'", con);
            int        countId = Convert.ToInt16(cmd5.ExecuteScalar());
            if (countId == 1)
            {
                SqlCommand cmd4 = new SqlCommand("insert into cart (custId, mac, prodQty,price) values ('" + custId.Value + "', '" + mac + "', 0,0)", con);
                cmd4.ExecuteScalar();
            }
        }
        int        cust    = Convert.ToInt16(custId.Value);
        SqlCommand cmd6    = new SqlCommand("select sum(prodQty) from cart where custId like '" + custId.Value + "'", con);
        int        prodQty = Convert.ToInt16(cmd6.ExecuteScalar());
        SqlCommand cmd7    = new SqlCommand("select sum(prodQty*price) from cart where custId like '" + custId.Value + "'", con);
        double     amtDue  = Convert.ToDouble(cmd7.ExecuteScalar());

        itemCount.Text = prodQty.ToString();
        amt.Text       = amtDue.ToString();

        con.Close();

        var queryStrings    = HttpUtility.UrlDecode(Request.QueryString.ToString());
        var arrQueryStrings = queryStrings.Split('=');

        id  = Convert.ToString(arrQueryStrings[1]);
        con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["mayeDb"].ConnectionString;
        if (con.State == System.Data.ConnectionState.Closed)
        {
            con.Open();
        }
        SqlCommand cmd8 = new SqlCommand("select nameFrn, price, descFrn, sizes from products where Id like '" + id + "'", con);

        System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
        da.SelectCommand = cmd8;
        System.Data.DataSet ds = new System.Data.DataSet();
        da.Fill(ds);
        StringBuilder cstext2 = new StringBuilder();

        cstext2.Clear();

        cstext2.Append("<script type='text/javascript'> var newInput; window.onload=function OnLoad() {");
        foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
        {
            cstext2.Append("document.getElementById('name').innerHTML='" + dr[0].ToString() + "';");
            cstext2.Append("document.getElementById('price').innerHTML+='" + dr[1].ToString() + "';");
            cstext2.Append("document.getElementById('description').innerHTML='" + dr[2].ToString() + "';");
            cstext2.Append("document.getElementById('button').innerHTML='<a  onclick=\\'cart(\"" + id + "\", " + dr[1].ToString() + ", " + qty.Text + ")\\' style=\\'height:53px; font-weight:bolder; border-style:groove; width:502px; text-align:center\\' class=\\'add-cart item_add\\'><br />AJOUTER AU PANIER</a>';");
            string size       = dr[3].ToString();
            var    sizeString = size.Split(',');
            for (int i = 0; i < sizeString.Length; i++)
            {
                cstext2.Append("document.getElementById('size').innerHTML+='<option>" + sizeString[i].ToString() + "</option>';");
            }
            cstext2.Append("document.getElementById('description2').innerHTML='" + dr[2].ToString() + "';");

            SqlCommand cmd1   = new SqlCommand("select image1 from products where Id like '" + id + "'", con);
            SqlCommand cmd2   = new SqlCommand("select image2 from products where Id like '" + id + "'", con);
            SqlCommand cmd3   = new SqlCommand("select image3 from products where Id like '" + id + "'", con);
            SqlCommand cmd4   = new SqlCommand("select image4 from products where Id like '" + id + "'", con);
            string     image1 = cmd1.ExecuteScalar().ToString();
            string     image2 = cmd2.ExecuteScalar().ToString();
            string     image3 = cmd3.ExecuteScalar().ToString();
            string     image4 = cmd4.ExecuteScalar().ToString();
            if (!image1.Equals(""))
            {
                cstext2.Append("document.getElementById('slideshow').innerHTML=\"<li  style='height:600px' data-thumb='" + image1 + "'><img style='height:600px' src='" + image1 + "' ></li>\";");
            }
            if (!image2.Equals(""))
            {
                cstext2.Append("document.getElementById('slideshow').innerHTML+=\"<li  style='height:600px' data-thumb='" + image2 + "'><img style='height:600px' src='" + image2 + "' ></li>\";");
            }
            if (!image3.Equals(""))
            {
                cstext2.Append("document.getElementById('slideshow').innerHTML+=\"<li  style='height:600px' data-thumb='" + image3 + "'><img style='height:600px' src='" + image3 + "' ></li>\";");
            }
            if (!image4.Equals(""))
            {
                cstext2.Append("document.getElementById('slideshow').innerHTML+=\"<li  style='height:600px' data-thumb='" + image4 + "'><img style='height:600px' src='" + image4 + "' ></li>\";");
            }
        }

        SqlCommand cmd12 = new SqlCommand("select top 3 id, nameFrn, ctgEng, price, image1 from  products  where id not like " + id + " order by newid()", con);

        System.Data.SqlClient.SqlDataAdapter da5 = new System.Data.SqlClient.SqlDataAdapter();
        da5.SelectCommand = cmd12;
        System.Data.DataSet ds3 = new System.Data.DataSet();
        da5.Fill(ds3);
        cstext2.Append("document.getElementById('suggestions').innerHTML='");

        foreach (System.Data.DataRow dr in ds3.Tables[0].Rows)
        {
            cstext2.Append("<div class=\"col-md-4 bottom-cd simpleCart_shelfItem\">");
            cstext2.Append("<div class=\"product-at \"><center>");
            cstext2.Append("<a href=\"single.aspx?id=" + dr[0] + "\"><img class=\"img-responsive\" style=\"width:254.984px; height:403.453px\" src=\"" + dr[4].ToString() + "\" alt=\"\">");
            cstext2.Append("<div class=\"pro-grid\" style=\"margin-top:70px\">");
            cstext2.Append("<span href=\"single.aspx?id=" + dr[0] + "\" class=\"buy-in\">Buy Now</span>");
            cstext2.Append("</div>");
            cstext2.Append("</a></center>");
            cstext2.Append("</div>");
            cstext2.Append("<p style=\"height:71px\" class=\"tun\">" + dr[1].ToString() + "</p>");
            cstext2.Append("<a  href=\"single.aspx?id=" + dr[0] + "\" class=\"item_add\"><p class=\"number item_price\"><i> </i>&euro;" + dr[3].ToString() + "</p></a>	");
            cstext2.Append("</div>");
        }
        cstext2.Append("';");
        //color
        SqlCommand cmd120 = new SqlCommand("select color from products where id like '" + id + "'", con);
        string     color  = cmd120.ExecuteScalar().ToString();
        var        id1    = id.Split('-');

        if (!color.Equals("0"))
        {
            // cstext2.Append("document.getElementById('color').innerHTML+=\"<li class='size-in' id='colorDrop'>Color<select id='color'>\";");
            var colorString = color.Split(',');

            for (int z = 0; z < colorString.Length; z++)
            {
                cstext2.Append("document.getElementById('color').innerHTML+='<option value=\\'single.aspx?id=" + id1[0] + "-" + (z + 1) + "\\'>" + colorString[z].ToString() + "</option>';");
            }
            cstext2.Append("document.getElementById('color').innerHTML+=\"</select></li>\";");
        }
        else
        {
            cstext2.Append("document.getElementById('colorDrop').style.display = 'none';");
        }
        //color

        SqlCommand cmd15 = new SqlCommand("select custName, review, date from review where productId like '" + id + "'", con);

        System.Data.SqlClient.SqlDataAdapter da1 = new System.Data.SqlClient.SqlDataAdapter();
        da1.SelectCommand = cmd15;
        System.Data.DataSet ds1 = new System.Data.DataSet();
        da1.Fill(ds1);
        cstext2.Append("document.getElementById('reviewpanel').innerHTML='");
        foreach (System.Data.DataRow dr in ds1.Tables[0].Rows)
        {
            cstext2.Append("<div class=\"top-comment-left\">");
            cstext2.Append("<img class=\"img-responsive\" src=\"images/co.png\" >");
            cstext2.Append("</div>");
            cstext2.Append("<div class=\"top-comment-right\">");
            cstext2.Append("<h6><a >" + dr[0].ToString() + "</a> - " + dr[2].ToString() + "</h6>");
            cstext2.Append("<p>" + dr[1].ToString() + "</p>");
            cstext2.Append("</div>");
            cstext2.Append("<div class=\"clearfix\"> </div>");
        }
        cstext2.Append("';}</script>");
        Response.Write(cstext2.ToString());
        con.Close();
        // }
        //catch (Exception a) { Response.Redirect("index.aspx"); }
    }
Exemplo n.º 38
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                sqlBağlanti kullanici = new sqlBağlanti();
                kullanici.Mail = textBox1.Text;

                baglanti.Open();


                string sorgu = "SELECT * FROM tbl_kullaniciKayit WHERE MAİL='" + textBox1.Text + "'";

                SqlCommand komut = new System.Data.SqlClient.SqlCommand(sorgu, baglanti);
                komut.ExecuteNonQuery();
                DataTable      tablo   = new DataTable();
                SqlDataAdapter adaptor = new System.Data.SqlClient.SqlDataAdapter(komut);
                adaptor.Fill(tablo);



                aktKod = rnd.Next(10000000, 99999999).ToString();
                if (tablo.Rows.Count > 0)
                {
                    textBox1.Text = tablo.Rows[0]["MAİL"].ToString();


                    if (kullanici.Mail == textBox1.Text)
                    {
                        MailMessage message = new MailMessage();
                        SmtpClient  istemci = new SmtpClient();
                        istemci.Credentials = new NetworkCredential("*****@*****.**", "iksvESTP34");
                        istemci.Port        = 587;
                        istemci.Host        = "smtp.gmail.com";
                        istemci.EnableSsl   = true;
                        message.To.Add(textBox1.Text);
                        message.From    = new MailAddress(textBox1.Text);
                        message.Subject = "Aktivasyon Kodu";
                        message.Body    = "Aktivasyon kodunuz artık yeni şifreniz oldu   : " + aktKod;
                        istemci.Send(message);
                        MessageBox.Show("Aktivasyon kodu mail adresine gönderildi. Yönlendiriliyorsunuz ... Daha sonra şifrenizi güncellemeyi unutmayınız ...", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //textBox1.Text = " ";


                        //baglanti.Open();

                        //string sorgu2 = "UPDATE tbl_KullaniciKayit SET Sifre='" + aktKod + "' WHERE Email='" + kullanici.Mail + "'";
                        //SqlCommand cmd = new SqlCommand(sorgu2, baglanti);
                        //cmd.ExecuteNonQuery();
                        //baglanti.Close();
                        //KullanıcıGirişForm formLogin = new KullanıcıGirişForm();
                        //this.Hide();
                        //formLogin.Show();
                    }
                    else
                    {
                        label2.Visible = true;
                        label2.Text    = "Kayıtlı Email adresi bulunamadı";
                    }
                }
                else
                {
                    label2.Visible = true;
                    label2.Text    = "Kayıtlı Email adresi bulunamadı";
                }

                baglanti.Close();
                baglanti.Dispose();
            }

            catch (Exception hata)
            {
                label2.Visible = true;
                label2.Text    = "Hata kodu : " + hata.Message;
            }
        }
Exemplo n.º 39
0
 private void LoadData()
 {
     sqlDataAdapter1.Fill(dataSet11);
     DataGrid1.DataSource = dataSet11.Tables[0];
 }
Exemplo n.º 40
0
    protected void dxcbpodfiles_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        try
        {
            string _folderpath = "";
            //int _orderno = 0;
            int   _ordernocount = 0;
            Int32 _folderid     = 0;
            bool  _uploaded     = false; //flagged if uploaded completed ok

            _folderpath = return_selected_folder();
            _folderid   = return_selected_folderid(_folderpath);
            _uploaded   = this.dxhfmanager.Contains("upld") ? (bool)this.dxhfmanager.Get("upld") : false;

            //09012011 stored in ilist to save casting datatable for IN query
            //05012011 multiple order no's are stored in data table
            //_ordernocount = _ol.Rows.Count;
            //_orderno = wwi_func.vint(this.dxlblorderno1.Text.ToString());  //this.dxhfmanager.Contains("ord") ? wwi_func.vint(wwi_security.DecryptString(this.dxhfmanager.Get("ord").ToString(), "publiship")) : 0;
            //DataTable _ol = (DataTable)Session["orderlist"];
            IList <Int32> _ol = (IList <Int32>)Session["orderlist"];
            _ordernocount = _ol.Count;


            if (_uploaded & _folderid > 0 && _ordernocount > 0)
            //if (_uploaded & _folderid > 0 && _orderno > 0)
            {
                //copy files from temporary folder
                //string _uid = wwi_security.DecryptString(this.dxhfmanager.Get("uid").ToString(), "publiship");
                string _uid        = ((UserClass)HttpContext.Current.Session["user"]).UserId.ToString();
                string _tempdir    = DateTime.Now.ToShortDateString().Replace("/", "") + _uid;
                string _sourcepath = System.IO.Path.Combine("~\\documents\\not found", _tempdir);

                int _copies = file_transfer(_sourcepath, _folderpath, true);
                if (_copies > 0)
                {
                    //update order table
                    //save quote id to order table
                    //if (_ordernocount == 1)
                    //{
                    //    //(DataRow)_ol.Rows[0][0]
                    //    SubSonic.Update upd2 = new SubSonic.Update(DAL.Logistics.Schemas.OrderTable);
                    //    recordsaffected = upd2.Set("document_folder").EqualTo(_folderid)
                    //                           .Where("OrderNumber").IsEqualTo(_ol[0])
                    //                           .Execute();
                    //}
                    //else
                    //{
                    //string _csv = wwi_func.datatable_to_string(_ol, ",");
                    string _csv = string.Join(",", _ol.Select(i => i.ToString()).ToArray());

                    //establish connection
                    ConnectionStringSettings _cs = ConfigurationManager.ConnectionStrings["PublishipSQLConnectionString"];
                    SqlConnection            _cn = new SqlConnection(_cs.ConnectionString);
                    //create a sql data adapter
                    System.Data.SqlClient.SqlDataAdapter _adapter = new System.Data.SqlClient.SqlDataAdapter();
                    //instantiate event handler
                    _adapter.RowUpdated += new SqlRowUpdatedEventHandler(adapter_RowUpdated);

                    _adapter.SelectCommand = new SqlCommand("SELECT [document_folder], [orderNumber] FROM OrderTable WHERE [OrderNumber] IN (" + _csv + ")", _cn);
                    //populate datatable using selected order numbers
                    DataTable _dt = new DataTable();
                    _adapter.Fill(_dt);

                    //update document folder for each order number in _dt
                    for (int ix = 0; ix < _dt.Rows.Count; ix++)
                    {
                        _dt.Rows[ix]["document_folder"] = _folderid;
                    }

                    //update command
                    _adapter.UpdateCommand = new SqlCommand("UPDATE OrderTable SET [document_folder] = @document_folder WHERE [OrderNumber] = @OrderNumber;", _cn);
                    _adapter.UpdateCommand.Parameters.Add("@OrderNumber", SqlDbType.Int).SourceColumn     = "OrderNumber";
                    _adapter.UpdateCommand.Parameters.Add("@document_folder", SqlDbType.Int).SourceColumn = "document_folder";

                    _adapter.UpdateBatchSize = 5; //_ordernocount;
                    _adapter.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;
                    _adapter.Update(_dt);
                    _adapter.Dispose();
                    _cn.Close();

                    //}

                    if (_countUpdated > 0) //countupdated will return the number of batches sent NOT the number of records updated
                    {
                        //disable session expiration which occurs when a directory is deleted
                        //uses System.Reflection
                        PropertyInfo p       = typeof(System.Web.HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
                        object       o       = p.GetValue(null, null);
                        FieldInfo    f       = o.GetType().GetField("_dirMonSubdirs", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
                        object       monitor = f.GetValue(o);
                        MethodInfo   m       = monitor.GetType().GetMethod("StopMonitoring", BindingFlags.Instance | BindingFlags.NonPublic);
                        m.Invoke(monitor, new object[] { });
                        //kill temp folder
                        System.IO.Directory.Delete(Server.MapPath(_sourcepath), true);


                        this.dxlblinfo2.Text  += _copies + " files have been uploaded to folder " + _folderid + " and linked to order numbers(s) " + _csv;
                        this.dxpnlinfo.Visible = true;
                    }
                    else
                    {
                        this.dxlblerr.Text    = "We have not been able to link order number(s) to online folder " + _folderid + " please refer to Publiship I.T.";
                        this.dxpnlerr.Visible = true;
                    }
                    //end check records affected
                }
            }
            //end update order table
        }
        catch (Exception ex)
        {
            this.dxlblerr.Text    = ex.Message.ToString();
            this.dxpnlerr.Visible = true;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            con.ConnectionString = ConfigurationManager.ConnectionStrings["mayeDb"].ConnectionString;

            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            mac = nics[0].GetPhysicalAddress().ToString();
            if (con.State == System.Data.ConnectionState.Closed)
            {
                con.Open();
            }
            SqlCommand cmd   = new SqlCommand("select count(id) from customer where mac_address like '" + mac + "'", con);
            int        count = Convert.ToInt16(cmd.ExecuteScalar());
            macadd.Value = mac.ToString();

            if (count > 0)
            {
                SqlCommand cmd1 = new SqlCommand("select top 1 concat(fname,' ',lname) from customer where mac_address like '" + mac + "' order by last_login desc", con);
                SqlCommand cmd2 = new SqlCommand("select top 1 id from customer where mac_address like '" + mac + "' order by last_login desc", con);

                String nameLog = cmd1.ExecuteScalar().ToString();
                custId.Value = cmd2.ExecuteScalar().ToString();
                name.Value   = nameLog.ToString();
                SqlCommand cmd5    = new SqlCommand("select count(custId) from cart where custId like '" + custId.Value + "'", con);
                int        countId = Convert.ToInt16(cmd5.ExecuteScalar());
                if (countId == 0)
                {
                    SqlCommand cmd4 = new SqlCommand("insert into cart (custId, mac , prodQty,price) values ('" + custId.Value + "', '" + mac + "', 0,0)", con);
                    cmd4.ExecuteScalar();
                }
            }
            else
            {
                name.Value = "Guest User";
                SqlCommand cmd3 = new SqlCommand("insert into customer (fname, mac_address, last_login) values ('Guest User', '" + mac + "', CURRENT_TIMESTAMP)", con);
                SqlCommand cmd2 = new SqlCommand("select top 1 id from customer where mac_address like '" + mac + "' order by last_login desc", con);
                cmd3.ExecuteNonQuery();

                custId.Value = cmd2.ExecuteScalar().ToString();
                SqlCommand cmd5    = new SqlCommand("select count(Id) from customer where Id like '" + custId.Value + "'", con);
                int        countId = Convert.ToInt16(cmd5.ExecuteScalar());
                if (countId == 1)
                {
                    SqlCommand cmd4 = new SqlCommand("insert into cart (custId, mac, prodQty,price) values ('" + custId.Value + "', '" + mac + "', 0,0)", con);
                    cmd4.ExecuteScalar();
                }
            }
            cust = Convert.ToInt16(custId.Value);
            SqlCommand cmd6    = new SqlCommand("select sum(prodQty) from cart where custId like '" + custId.Value + "'", con);
            int        prodQty = Convert.ToInt16(cmd6.ExecuteScalar());
            SqlCommand cmd7    = new SqlCommand("select sum(prodQty*price) from cart where custId like '" + custId.Value + "'", con);
            double     amtDue  = Convert.ToDouble(cmd7.ExecuteScalar());
            itemCount.Text = prodQty.ToString();
            amt.Text       = amtDue.ToString();
            con.Close();
            var cat  = "";
            var page = "";
            try
            {
                con = new System.Data.SqlClient.SqlConnection();
                con.ConnectionString = ConfigurationManager.ConnectionStrings["mayeDb"].ConnectionString;
                if (con.State == System.Data.ConnectionState.Closed)
                {
                    con.Open();
                }
                StringBuilder cstext2 = new StringBuilder();
                cstext2.Clear();
                cstext2.Append("<script type='text/javascript'> var newInput; window.onload=function OnLoad() {");
                cstext2.Append("document.getElementById('products').innerHTML ='';");
                System.Data.SqlClient.SqlCommand     cmd8 = new System.Data.SqlClient.SqlCommand(";with A aS(SELECT  id, nameFrn, ctgEng, descEng, price, image1 isAvlbl, sizes,ROW_NUMBER() OVER (ORDER BY Id) AS 'RN' from products where isFeatured =1 )	select * from A order by newid()", con);
                System.Data.SqlClient.SqlDataAdapter da   = new System.Data.SqlClient.SqlDataAdapter();
                da.SelectCommand = cmd8;
                System.Data.DataSet ds = new System.Data.DataSet();
                da.Fill(ds);



                int x = 0;
                cstext2.Append("newInput=\"");
                foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
                {
                    //product

                    if (x % 3 == 0)
                    {
                        cstext2.Append("<div class=' bottom-product'>");
                    }
                    cstext2.Append("<div class='col-md-4 bottom-cd simpleCart_shelfItem'>");
                    cstext2.Append("<div class='product-at '>");
                    cstext2.Append("<a href='single.aspx?id=" + dr[0].ToString() + "'><img class='img-responsive' style='width:254.984px; height:403.453px' src='" + dr[5].ToString() + "'>");
                    cstext2.Append("<div class='pro-grid' style='margin-top:70px'>");
                    cstext2.Append("<span class='buy-in'  href='single.aspx?id=" + dr[0].ToString() + "'>Acheter Maintenant</span>");
                    cstext2.Append("</div>");
                    cstext2.Append("</a>	");
                    cstext2.Append("</div>");
                    cstext2.Append("<p style='height:71px' class='tun'>" + dr[1].ToString() + "</p>");
                    cstext2.Append("<a href='single.aspx?id=" + dr[0].ToString() + "' class='item_add'><p class='number item_price'><i> </i>&euro;" + dr[4].ToString() + "</p></a>						");
                    cstext2.Append("<br><br></div>");
                    if ((x + 1) % 3 == 0)
                    {
                        cstext2.Append("<div>");
                    }

                    x++;
                    //productEnd
                }
                cstext2.Append("\";");
                cstext2.Append(" document.getElementById('products').innerHTML += newInput;");

                cstext2.Append("var newInput1=\"<div class='of-left-in'><h3 class='best'>Best Sellers</h3></div>");
                System.Data.SqlClient.SqlCommand     cmd9 = new System.Data.SqlClient.SqlCommand("select top 2 id, nameFrn, price, image1 from products order by newid() ", con);
                System.Data.SqlClient.SqlDataAdapter da1  = new System.Data.SqlClient.SqlDataAdapter();
                da1.SelectCommand = cmd9;
                System.Data.DataSet ds1 = new System.Data.DataSet();
                da1.Fill(ds1);
                foreach (System.Data.DataRow dr in ds1.Tables[0].Rows)
                {
                    cstext2.Append("<div class='product-go'><div class=' fashion-grid'><a href='single.aspx?id=" + dr[0] + "'><img class='img-responsive' src='" + dr[3].ToString() + "' ></a></div>");
                    cstext2.Append("<div class='fashion-grid1'><h6 class='best2'><a href='single.aspx?id=" + dr[0] + "' >" + dr[1].ToString() + "</a></h6>");
                    cstext2.Append("<span class=' price-in1'> &euro;" + dr[2] + "</span></div><div class='clearfix'> </div></div>");
                }
                cstext2.Append("\";");
                cstext2.Append(" document.getElementById('ticker').innerHTML = newInput1;");


                cstext2.Append("}<");
                cstext2.Append("/script>");
                Response.Write(cstext2.ToString());
            }
            catch (Exception a) { }
        }
        catch (Exception a)
        { Response.Redirect("index.aspx"); }
    }
Exemplo n.º 42
0
        protected void Page_Load(object sender, EventArgs e)
        {
            id_loai_san_pham = 0;
            connect          = new connect();
            mH = new WebApplication2.QuanTri.maHoa();
            try
            {
                if (Request.QueryString["id_loai_san_pham"] != null && Request.QueryString["id_loai_san_pham"] != "")
                {
                    id_loai_san_pham = int.Parse(Request.QueryString["id_loai_san_pham"]);
                }
            }
            catch (Exception a) { }
            if (id_loai_san_pham == 0)
            {
                Response.Redirect("danhsachloaisanpham.aspx");
            }

            System.Data.DataTable ds = new System.Data.DataTable();
            {
                string sql = "select id_loai_san_pham, ten_loai_san_pham, anh_loai_san_pham, bieu_tuong_loai_san_pham, cap_do_loai_san_pham, id_cha_loai_san_pham from loai_san_pham where id_loai_san_pham=" + id_loai_san_pham;
                WebApplication2.YNNSHOP56131778.CONGFIG.connect cnt    = new WebApplication2.YNNSHOP56131778.CONGFIG.connect();
                System.Data.SqlClient.SqlConnection             ketnoi = new System.Data.SqlClient.SqlConnection(connect.getconnect());
                System.Data.SqlClient.SqlCommand lenh = new System.Data.SqlClient.SqlCommand(sql, ketnoi);
                ketnoi.Open();
                System.Data.SqlClient.SqlDataAdapter data = new System.Data.SqlClient.SqlDataAdapter(lenh);
                data.Fill(ds);
                ketnoi.Close();
                id_cha = ds.Rows[0][5].ToString();
                if (!IsPostBack)
                {
                    TextBox1.Text = mH.Base64Decode(ds.Rows[0][1].ToString());
                    TextBox4.Text = ds.Rows[0][4].ToString();
                }
                //TextBox4.Text = ds.Rows[0][4].ToString();
            }
            System.Data.DataTable lsp = new System.Data.DataTable();
            {
                string sql = "select id_loai_san_pham, ten_loai_san_pham from loai_san_pham where cap_do_loai_san_pham = " + (int.Parse(TextBox4.Text) - 1);
                WebApplication2.YNNSHOP56131778.CONGFIG.connect cnt    = new WebApplication2.YNNSHOP56131778.CONGFIG.connect();
                System.Data.SqlClient.SqlConnection             ketnoi = new System.Data.SqlClient.SqlConnection(connect.getconnect());
                System.Data.SqlClient.SqlCommand lenh = new System.Data.SqlClient.SqlCommand(sql, ketnoi);
                ketnoi.Open();
                System.Data.SqlClient.SqlDataAdapter data = new System.Data.SqlClient.SqlDataAdapter(lenh);
                data.Fill(lsp);
                ketnoi.Close();
                for (int i = 0; i < lsp.Rows.Count; i++)
                {
                    lsp.Rows[i][1] = mH.Base64Decode(lsp.Rows[i][1].ToString());
                }
                if ((int.Parse(TextBox4.Text)) == 0)
                {
                    System.Data.DataRow row;
                    row    = lsp.NewRow();
                    row[0] = 0;
                    row[1] = "cao nhất";
                    lsp.Rows.Add(row);
                }
                DropDownList1.DataSource     = lsp;
                DropDownList1.DataTextField  = "ten_loai_san_pham";
                DropDownList1.DataValueField = "id_loai_san_pham";
                DropDownList1.DataBind();
                try { DropDownList1.Items.FindByValue(id_cha + "").Selected = true; }catch (Exception a) { }
            }
        }
Exemplo n.º 43
0
        private void btnVistaPrevia_Click(object sender, System.EventArgs e)
        {
            cryRepResumen1.PrintOptions.PaperOrientation = CrystalDecisions.Shared.PaperOrientation.Landscape;
            cryRepResumen1.SetDataSource(dsResumen1);

            decimal [] tot = new decimal[8];
            for (int i = 0; i < 8; i++)
            {
                tot[i] = 0;
            }
            crvResumen.Visible = true;
            dsResumen1.Clear();
            try
            {
                sqlDAConcepto.Fill(dsResumen1, "Concepto");
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            dsResumen1.Clear();
            sqlDAConcepto.Fill(dsResumen1, "Concepto");
            if (ckbAdicional1.Checked || ckbAdicional2.Checked || ckbAdicional3.Checked || ckbAdicional4.Checked)
            {
                sqlDASumaResumen.SelectCommand.Parameters["@IdObra"].Value = txtIdobra.Text.Trim() + (cbkPrefijo.Checked  ? "" : "%");
                sqlDASumaResumen.SelectCommand.Parameters["@IdObr1"].Value = (ckbAdicional1.Checked ? (cmbIdObr1.SelectedValue.ToString() + (cbkPrefijo.Checked  ? "" : "%")) : "");
                sqlDASumaResumen.SelectCommand.Parameters["@IdObr2"].Value = (ckbAdicional2.Checked ? (cmbIdObr2.SelectedValue.ToString() + (cbkPrefijo.Checked  ? "" : "%")) : "");
                sqlDASumaResumen.SelectCommand.Parameters["@IdObr3"].Value = (ckbAdicional3.Checked ? (cmbIdObr3.SelectedValue.ToString() + (cbkPrefijo.Checked  ? "" : "%")) : "");
                sqlDASumaResumen.SelectCommand.Parameters["@IdObr4"].Value = (ckbAdicional4.Checked ? (cmbIdObr4.SelectedValue.ToString() + (cbkPrefijo.Checked  ? "" : "%")) : "");
                sqlDASumaResumen.SelectCommand.Parameters["@FIni"].Value   = dtpIni.Text;
                sqlDASumaResumen.SelectCommand.Parameters["@FFin"].Value   = dtpFin.Text;
                sqlDASumaResumen.SelectCommand.Parameters["@FIni1"].Value  = dtpIni1.Text;
                sqlDASumaResumen.SelectCommand.Parameters["@FFin1"].Value  = dtpFin1.Text;
                sqlDASumaResumen.SelectCommand.Parameters["@FIni2"].Value  = dtpIni2.Text;
                sqlDASumaResumen.SelectCommand.Parameters["@FFin2"].Value  = dtpFin2.Text;
                sqlDASumaResumen.SelectCommand.Parameters["@FHoy"].Value   = DateTime.Today;
                sqlDASumaResumen.Fill(dsResumen1, "ResumenTrabajos");
            }
            else
            {
                sqlDAResumen.SelectCommand.Parameters["@IdObra"].Value = txtIdobra.Text.Trim() + (cbkPrefijo.Checked  ? "" : "%");
                sqlDAResumen.SelectCommand.Parameters["@FIni"].Value   = dtpIni.Text;
                sqlDAResumen.SelectCommand.Parameters["@FFin"].Value   = dtpFin.Text;
                sqlDAResumen.SelectCommand.Parameters["@FIni1"].Value  = dtpIni1.Text;
                sqlDAResumen.SelectCommand.Parameters["@FFin1"].Value  = dtpFin1.Text;
                sqlDAResumen.SelectCommand.Parameters["@FIni2"].Value  = dtpIni2.Text;
                sqlDAResumen.SelectCommand.Parameters["@FFin2"].Value  = dtpFin2.Text;
                sqlDAResumen.SelectCommand.Parameters["@FHoy"].Value   = DateTime.Today;
                sqlDAResumen.Fill(dsResumen1, "ResumenTrabajos");
            }
            foreach (DataRow dr in dsResumen1.Tables["ResumenTrabajos"].Rows)
            {
                tot[0] += decimal.Parse(dr["Pres"].ToString()) * decimal.Parse(dr["Preuni"].ToString());
                tot[1] += decimal.Parse(dr["Parc1"].ToString()) * decimal.Parse(dr["Preuni"].ToString());
                tot[2] += decimal.Parse(dr["Parc2"].ToString()) * decimal.Parse(dr["Preuni"].ToString());
                tot[3] += decimal.Parse(dr["Parc3"].ToString()) * decimal.Parse(dr["Preuni"].ToString());
                tot[4] += decimal.Parse(dr["Total"].ToString()) * decimal.Parse(dr["Preuni"].ToString());
                if (dr["IdConcepto"].ToString() != "14" && dr["IdConcepto"].ToString() != "16" && dr["IdConcepto"].ToString() != "17" && dr["IdConcepto"].ToString() != "18" && dr["IdConcepto"].ToString() != "19" && dr["IdConcepto"].ToString() != "20")
                {
                    tot[5] += decimal.Parse(dr["Total"].ToString()) * decimal.Parse(dr["Prelis"].ToString());                     //14, 16, 17, 18, 19, 20
                }
                if (dr["IdConcepto"].ToString() != "10" && dr["IdConcepto"].ToString() != "18" && dr["IdConcepto"].ToString() != "19" && dr["IdConcepto"].ToString() != "20")
                {
                    tot[6] += decimal.Parse(dr["Total"].ToString()) * decimal.Parse(dr["Prelis"].ToString());
                }
                if (dr["IdConcepto"].ToString() != "10" && dr["IdConcepto"].ToString() != "14" && dr["IdConcepto"].ToString() != "16" && dr["IdConcepto"].ToString() != "17" && dr["IdConcepto"].ToString() != "30")
                {
                    tot[7] += decimal.Parse(dr["Total"].ToString()) * decimal.Parse(dr["Prelis"].ToString());
                }
            }
            dsResumen1.Tables["Concepto"].Rows[0]["Tot1"] = tot[0];
            dsResumen1.Tables["Concepto"].Rows[0]["Tot2"] = tot[1];
            dsResumen1.Tables["Concepto"].Rows[0]["Tot3"] = tot[2];
            dsResumen1.Tables["Concepto"].Rows[0]["Tot4"] = tot[3];
            dsResumen1.Tables["Concepto"].Rows[0]["Tot5"] = tot[4];
            dsResumen1.Tables["Concepto"].Rows[0]["Tot6"] = tot[5];
            dsResumen1.Tables["Concepto"].Rows[0]["Tot7"] = tot[6];
            dsResumen1.Tables["Concepto"].Rows[0]["Tot8"] = tot[7];
            string obras = "";

            if (ckbAdicional1.Checked || ckbAdicional2.Checked || ckbAdicional3.Checked || ckbAdicional4.Checked)
            {
                obras  = (ckbAdicional1.Checked ? (cmbIdObr1.SelectedValue.ToString() + (cbkPrefijo.Checked  ? "" : "%") + " ") : "");
                obras += (ckbAdicional2.Checked ? (cmbIdObr2.SelectedValue.ToString() + (cbkPrefijo.Checked  ? "" : "%") + " ") : "");
                obras += (ckbAdicional3.Checked ? (cmbIdObr3.SelectedValue.ToString() + (cbkPrefijo.Checked  ? "" : "%") + " ") : "");
                obras += (ckbAdicional4.Checked ? (cmbIdObr4.SelectedValue.ToString() + (cbkPrefijo.Checked  ? "" : "%") + " ") : "");
            }

            cryRepResumen1.SetParameterValue("@Cons", dsDGObra1.Tables[0].Rows[cmbIdObra.SelectedIndex][3].ToString());
            cryRepResumen1.SetParameterValue("@Ubica", dsDGObra1.Tables[0].Rows[cmbIdObra.SelectedIndex][1].ToString());
            cryRepResumen1.SetParameterValue("@Col", dsDGObra1.Tables[0].Rows[cmbIdObra.SelectedIndex][4].ToString());
            cryRepResumen1.SetParameterValue("@Zona", dsDGObra1.Tables[0].Rows[cmbIdObra.SelectedIndex][5].ToString());
            cryRepResumen1.SetParameterValue("@Fi", dtpIni.Value);
            cryRepResumen1.SetParameterValue("@Ff", dtpFin.Value);
            cryRepResumen1.SetParameterValue("@Fi1", dtpIni1.Value);
            cryRepResumen1.SetParameterValue("@Ff1", dtpFin1.Value);
            cryRepResumen1.SetParameterValue("@Fi2", dtpIni2.Value);
            cryRepResumen1.SetParameterValue("@Ff2", dtpFin2.Value);
            cryRepResumen1.SetParameterValue("@Total", cbkTotal.Checked);
            cryRepResumen1.SetParameterValue("@Obras", obras);


            crvResumen.ReportSource = cryRepResumen1;
            //crvResumen.RefreshReport();
        }
Exemplo n.º 44
0
        public void SaveComment(string _Type, string _iDocsendDetailsID, string _sDocumentName, string refno)
        {
            SendRecDoc objDoc  = new SendRecDoc();
            string     PuserID = ((UserDetails)Session[clsConstant.TOKEN]).UserID.ToString();

            string sqlto = "select  tblUserMaster.iUserID from tblUserMaster ";

            sqlto = sqlto + " join tblDocSendDetail on tblDocSendDetail.iUserID=tblUserMaster.iUserID ";
            sqlto = sqlto + " where iDocSendID =" + _iDocsendDetailsID + " and bTOCC=1 ";

            SqlConnection  cntouser = new SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);
            SqlDataAdapter adtouser = new System.Data.SqlClient.SqlDataAdapter(sqlto, cntouser);
            DataSet        dstouser = new DataSet();

            adtouser.Fill(dstouser);

            DataSet        dsuser  = objDoc.getUsersforrejectApprove(int.Parse(_iDocsendDetailsID));
            string         userto  = dsuser.Tables[0].Rows[0]["selectusr"].ToString();
            string         sqlmcid = " select imcid from tblDocSend where iDocSendID=" + _iDocsendDetailsID;
            SqlConnection  mcidcon = new SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);
            SqlDataAdapter mciad   = new System.Data.SqlClient.SqlDataAdapter(sqlmcid, mcidcon);
            DataSet        dsmcid  = new DataSet();

            mciad.Fill(dsmcid);

            if (dsmcid.Tables[0].Rows.Count > 0)
            {
                string SqlUpdate = "update tblmc set bMissionApproved='PC'  where iMissionClearanceId=" + dsmcid.Tables[0].Rows[0][0].ToString() + "";
                mcidcon.Close();
                mcidcon.Open();
                SqlCommand cmd = new SqlCommand(SqlUpdate, mcidcon);
                cmd.ExecuteNonQuery();
            }
            string  emailAlert  = string.Empty;
            DataSet dsuserEmail = new DataSet();

            dsuserEmail = objDoc.getmailforrejectApprove(int.Parse(dsmcid.Tables[0].Rows[0]["imcid"].ToString()));
            emailAlert += GetFromID(int.Parse(dsmcid.Tables[0].Rows[0]["imcid"].ToString())) + ';';
            emailAlert += dsuserEmail.Tables[0].Rows[0]["selectusr"].ToString() + ';';
            emailAlert  = FindEmailID(emailAlert, ((UserDetails)(Session[clsConstant.TOKEN])).EmailID) + ';';

            if (emailAlert.Contains("*****@*****.**"))
            {
                emailAlert += "*****@*****.**" + ';';
            }
            Session["userEmail"] = emailAlert;



            if (objDoc.saveALLComment(dsmcid.Tables[0].Rows[0]["imcid"].ToString(), _iDocsendDetailsID, "R", _sDocumentName, refno, DateTime.Now, int.Parse(PuserID), userto, "") > 0)
            {
                Utility objUtl = new Utility();
                try
                {
                    string nameOfSender = ((UserDetails)Session[clsConstant.TOKEN]).FirstName.ToString() + ' ' + ((UserDetails)Session[clsConstant.TOKEN]).LastName.ToString();

                    // For NIC
                    objUtl.SendAlertEmail_MC_NIC_NotAttachment(Session["userEmail"].ToString(), "Replied - " + refno
                                                               , nameOfSender, null, null,
                                                               ((UserDetails)Session[clsConstant.TOKEN]).Designation,
                                                               ((UserDetails)Session[clsConstant.TOKEN]).Agency
                                                               );
                }

                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Exemplo n.º 45
0
 private void LlenaZona()
 {
     sqlDAZona.Fill(dsZona1, "Zona");
 }
Exemplo n.º 46
0
 private void LlenaConcretera()
 {
     sqlDAConcretera.Fill(dsConcretera1, "Concretera");
 }
Exemplo n.º 47
0
    protected void Page_Load(object sender, System.EventArgs e)
    {
        //string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        //CommonFunctions.Connection.ConnectionString = connectionstring;

        //if (CommonFunctions.Connection.State == System.Data.ConnectionState.Closed)
        //CommonFunctions.Connection.Open ();

        //lock (CommonFunctions.Connection)
        PropertiesAdapter.Fill(PropertiesFullSet);

        //lock (CommonFunctions.Connection)
        RegionsAdapter.Fill(RegionsSet);
        //lock (CommonFunctions.Connection)
        CountriesAdapter.Fill(CountriesSet);
        //lock (CommonFunctions.Connection)
        StateProvincesAdapter.Fill(StateProvincesSet);
        //lock (CommonFunctions.Connection)
        CitiesAdapter.Fill(CitiesSet);

        //lock (CommonFunctions.Connection)
        AmenitiesAdapter.Fill(AmenitiesSet);
        //lock (CommonFunctions.Connection)
        AttractionsAdapter.Fill(AttractionsSet);

        //if (Master.FindControl ("BodyTag") is HtmlGenericControl)
        //{
        //    HtmlGenericControl body = (HtmlGenericControl)Master.FindControl ("BodyTag");
        //    body.Attributes["onload"] = "InitializeDropdowns ();";
        //}

        string temp = "Vacation rentals at ";



        ((System.Web.UI.WebControls.Image)Master.FindControl("Logo")).AlternateText = temp + "Vacations-Abroad.com";
        //((System.Web.UI.WebControls.Image)Master.FindControl ("MainLogo")).AlternateText = temp + "@ Vacations-Abroad.com";

        foreach (DataRow datarow in RegionsSet.Tables["Regions"].Rows)
        {
            if (datarow["Region"] is string)
            {
                regions += " " + (string)datarow["Region"];
            }
        }

        HtmlHead head = Page.Header;
        //Page.ClientScript.RegisterClientScriptInclude("aKeyToIdentifyIt", "/scripts/countryStateCity.js");
        HtmlMeta keywords = new HtmlMeta();

        keywords.Name = "keywords";
        if (PropertiesFullSet.Tables["Properties"].Rows.Count < 1)
        {
            keywords.Content = "View property";
        }
        else
        {
            keywords.Content = Keywords.Text.Replace("%regions%", regions.Trim());
        }

        head.Controls.Add(keywords);
        HtmlMeta description = new HtmlMeta();

        description.Name = "description";
        if (PropertiesFullSet.Tables["Properties"].Rows.Count < 1)
        {
            description.Content = "View property";
        }
        else
        {
            description.Content = Description.Text.Replace("%regions%", regions.Trim());
        }

        head.Controls.Add(description);

        if (!IsPostBack)
        {
            DataBind();

            //Page.Header.Controls.Add(new LiteralControl("<link href='http://vacations-abroad.com/css/StyleSheet.css' rel='stylesheet' type='text/css'></script>"));
            Page.Header.Controls.Add(new LiteralControl("<link href='http://vacations-abroad.com/css/StyleSheet.css' rel='stylesheet' type='text/css' />"));
        }
        DataSet ds = Utility.dsGrab("RegionTextList");

        ltlAfrica.Text           = ds.Tables[0].Rows[0]["RegionTextValue"].ToString();
        ltlAsia.Text             = ds.Tables[0].Rows[1]["RegionTextValue"].ToString();
        ltlEurope.Text           = ds.Tables[0].Rows[2]["RegionTextValue"].ToString();
        ltlNorthAmerica.Text     = ds.Tables[0].Rows[3]["RegionTextValue"].ToString();
        ltlSouthAmerica.Text     = ds.Tables[0].Rows[4]["RegionTextValue"].ToString();
        ltlOceania.Text          = ds.Tables[0].Rows[5]["RegionTextValue"].ToString();
        ltlAfricaList.Text       = GenerateCountryLinks("1");
        ltlAsiaList.Text         = GenerateCountryLinks("2");
        ltlOceaniaList.Text      = GenerateCountryLinks("3");
        ltlSouthAmericaList.Text = GenerateCountryLinks("9");
        ltlEuropeList.Text       = GenerateCountryLinks("6");
        ltlNorthAmericaList.Text = GenerateCountryLinks("8");
    }
Exemplo n.º 48
0
    protected void Page_Load(object sender, System.EventArgs e)
    {
        //footerPropDescContainer.Visible = false;

        //string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;


        //CommonFunctions.Connection.ConnectionString = connectionstring;

        //if (CommonFunctions.Connection.State == System.Data.ConnectionState.Closed)
        //CommonFunctions.Connection.Open ();

        //lock (CommonFunctions.Connection)
        PropertiesAdapter.Fill(PropertiesFullSet);

        //lock (CommonFunctions.Connection)
        RegionsAdapter.Fill(RegionsSet);
        //lock (CommonFunctions.Connection)
        CountriesAdapter.Fill(CountriesSet);
        //lock (CommonFunctions.Connection)
        StateProvincesAdapter.Fill(StateProvincesSet);
        //lock (CommonFunctions.Connection)
        CitiesAdapter.Fill(CitiesSet);

        //lock (CommonFunctions.Connection)
        AmenitiesAdapter.Fill(AmenitiesSet);
        //lock (CommonFunctions.Connection)
        AttractionsAdapter.Fill(AttractionsSet);

        //if (Master.FindControl ("BodyTag") is HtmlGenericControl)
        //{
        //    HtmlGenericControl body = (HtmlGenericControl)Master.FindControl ("BodyTag");
        //    body.Attributes["onload"] = "InitializeDropdowns ();";
        //}

        string temp = "Vacation rentals at ";



        // ((System.Web.UI.WebControls.Image)Master.FindControl("Logo")).AlternateText = temp + "Vacations-Abroad.com";
        //((System.Web.UI.WebControls.Image)Master.FindControl ("MainLogo")).AlternateText = temp + "@ Vacations-Abroad.com";

        foreach (DataRow datarow in RegionsSet.Tables["Regions"].Rows)
        {
            if (datarow["Region"] is string)
            {
                regions += " " + (string)datarow["Region"];
            }
        }

        HtmlHead head = Page.Header;
        //Page.ClientScript.RegisterClientScriptInclude("aKeyToIdentifyIt", "/scripts/countryStateCity.js");

        string   Keywords = "Africa Vacation Rentals, Africa Safari Lodges, Africa Beach Resorts, Africa Vacations";
        HtmlMeta keywords = new HtmlMeta();

        keywords.Name = "keywords";
        if (PropertiesFullSet.Tables["Properties"].Rows.Count < 1)
        {
            keywords.Content = "View property";
        }
        else
        {
            keywords.Content = Keywords.Replace("%regions%", regions.Trim());
        }

        head.Controls.Add(keywords);
        string   Description = "Explore Africa while staying in our boutique hotels or vacation rentals.";
        HtmlMeta description = new HtmlMeta();

        description.Name = "description";
        if (PropertiesFullSet.Tables["Properties"].Rows.Count < 1)
        {
            description.Content = "View property";
        }
        else
        {
            description.Content = Description.Replace("%regions%", regions.Trim());
        }

        head.Controls.Add(description);

        if (!IsPostBack)
        {
            DataBind();
            // Page.Header.Controls.Add(new LiteralControl("<link href='http://vacations-abroad.com/css/StyleSheet.css' rel='stylesheet' type='text/css' />"));
        }
        DataSet ds = Utility.dsGrab("RegionTextList");
    }
        void Message()
        {
            StringBuilder sb = new StringBuilder();

            string[] Msg = null;
            if (Request.QueryString["MCID"] != null)
            {
                Session["MCID"] = Request.QueryString["MCID"].ToString();
            }
            else if (hdnMCID.Value != string.Empty)
            {
                Session["MCID"] = hdnMCID.Value;
            }
            if (Session["MCID"].ToString() != null && Session["MCID"].ToString() != "0")
            {
                string sql = " SELECT dbo.tblMC.vsMissionClearnceName, dbo.tblMC.CreateDate, dbo.tblMC.bMissionApproved,";
                sql = sql + " fromtblUserMaster.vsFirstName as FromFirstName, fromtblUserMaster.vsLastName as FromLastName,";
                sql = sql + " fromtblDesignationMaster.vsDesignationName as FromDesignation, TotblUserMaster.vsFirstName AS ToFirstName, TotblUserMaster.vsLastName AS ToLastName,TotblDesignationMaster.vsDesignationName AS ToDesignation";
                sql = sql + " FROM dbo.tblMC INNER JOIN ";
                sql = sql + " dbo.tblUserMaster fromtblUserMaster  ON dbo.tblMC.iFromUser = fromtblUserMaster.iUserID INNER JOIN ";
                sql = sql + " dbo.tblDesignationMaster fromtblDesignationMaster  ON ";
                sql = sql + " fromtblUserMaster.iDesignationID = fromtblDesignationMaster.iDesignationID INNER JOIN ";
                sql = sql + " dbo.tblUserMaster AS TotblUserMaster ON dbo.tblMC.iToUser = TotblUserMaster.iUserID ";
                sql = sql + " INNER JOIN ";
                sql = sql + " dbo.tblDesignationMaster AS TotblDesignationMaster ON TotblUserMaster.iDesignationID = TotblDesignationMaster.iDesignationID ";
                sql = sql + " where iMissionClearanceId=" + Session["MCID"].ToString();

                SqlConnection  cn  = new SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);
                SqlDataAdapter ad  = new System.Data.SqlClient.SqlDataAdapter(sql, cn);
                DataSet        ds1 = new DataSet();
                ad.Fill(ds1);

                string dtcreate = Convert.ToDateTime(ds1.Tables[0].Rows[0]["CreateDate"].ToString()).ToString("dd MMM yyyy");
                if (Request.QueryString["Reject_approved"] != null)
                {
                    if (Request.QueryString["Reject_approved"].ToString() == "Approved")
                    {
                        //string fileName = Server.MapPath(@"~/writereaddata/CAAA Letter.pdf")
                        Msg = File.ReadAllLines(Server.MapPath(@"~/writereaddata/RequestAproval.txt"));
                        for (int i = 0; i < Msg.Length; i++)
                        {
                            Msg[i] = Msg[i].Replace("<user name>", ds1.Tables[0].Rows[0]["FromFirstName"].ToString() + "  " + ds1.Tables[0].Rows[0]["FromLastName"].ToString());// (((UserDetails)Session[clsConstant.TOKEN]).userNm).ToString());
                            Msg[i] = Msg[i].Replace("<Mission clearance reference No>", Session["MCID"].ToString());
                            Msg[i] = Msg[i].Replace("<Mission clearance reference Description>", ds1.Tables[0].Rows[0]["vsMissionClearnceName"].ToString());
                            Msg[i] = Msg[i].Replace("<Mission clearance request submission date>", dtcreate.ToString());
                            Msg[i] = Msg[i].Replace("<sender first name>", ds1.Tables[0].Rows[0]["ToFirstName"].ToString());
                            Msg[i] = Msg[i].Replace("<sender last name>", ds1.Tables[0].Rows[0]["ToLastName"].ToString());
                            Msg[i] = Msg[i].Replace("<Designation>", ds1.Tables[0].Rows[0]["ToDesignation"].ToString());
                            Msg[i] = Msg[i].Replace("<Department of External Affairs>", (((UserDetails)Session[clsConstant.TOKEN]).AgencyName).ToString());
                            Msg[i] = Msg[i].Replace("<cc list of all original CC list>", "");
                        }
                    }
                }
                else
                {
                    string sqlmsg = " SELECT top 1 REPLACE(convert(varchar(2000),memosendMessage),'<br>','\n') AS memosendMessage FROM    tblDocSend";
                    sqlmsg = sqlmsg + " where imcid=" + Session["MCID"].ToString();
                    sqlmsg = sqlmsg + "  order by  idocsendid desc";
                    SqlConnection  cnmsg = new SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);
                    SqlDataAdapter admsg = new System.Data.SqlClient.SqlDataAdapter(sqlmsg, cnmsg);
                    DataSet        dsmsg = new DataSet();
                    admsg.Fill(dsmsg);
                    try
                    {
                        Msg = new string[1];

                        sb.Append(dsmsg.Tables[0].Rows[0]["memoSendMessage"].ToString());
                        Msg[0] = sb.ToString();
                    }
                    catch { }
                }

                if (Msg != null)
                {
                    for (int i = 0; i < Msg.Length; i++)
                    {
                        txtMessage.Text += Msg[i] + "\n";
                    }
                }
                Session["Reject_aprovedMessage"] = Msg;
            }
        }
Exemplo n.º 50
0
 private void ViewDemoForm_Load(object sender, System.EventArgs e)
 {
     myAdapter.Fill(myDS);
 }
Exemplo n.º 51
0
        public static void GenerateStandardTableDependencyQueries(string connectionStringTxt, string dest, bool seperateFiles, bool removeFilesOnNewSqlGeneration)
        {
            if (removeFilesOnNewSqlGeneration)
            {
                try
                {
                    DirectoryInfo di = new DirectoryInfo(dest);

                    foreach (FileInfo file in di.GetFiles())
                    {
                        file.Delete();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
            if (string.IsNullOrEmpty(connectionStringTxt))
            {
                throw new Exception("Missing connection settings");
            }

            string connString = connectionStringTxt;

            SqlConnection conn = new SqlConnection(connString);

            var cmd = new SqlCommand(query, conn);

            conn.Open();

            // create data adapter
            var da = new System.Data.SqlClient.SqlDataAdapter(cmd);

            // this will query your database and return the result to your datatable
            _dataTable = new DataTable();
            da.Fill(_dataTable);
            conn.Close();
            da.Dispose();

            _sqlBuilder.Length   = 0;
            _sqlBuilder.Capacity = 0;

            foreach (DataRow item in _dataTable.Rows)
            {
                //  0             1               2                   3             4                     5
                //SchemaName | TableName | ColumnName | ReferenceSchemaName | ReferenceTableName | ReferenceColumnName

                //if (!sqlBuilder.ToString().Contains("SELECT * FROM " + item["SchemaName"] + "." + item["TableName"] +
                //									" AS " + item["TableName"] + "_" + item["TableName"]))
                //{
                //	sqlBuilder.AppendLine("SELECT * FROM " + item["SchemaName"] + "." + item["TableName"] + " AS " +
                //						  item["TableName"] + "_" + item["TableName"]);

                //}

                if (!_sqlBuilder.ToString().Contains("SELECT * FROM [" + item["TableName"] +
                                                     "] AS " + item["TableName"] + "_" + item["TableName"]))
                {
                    _sqlBuilder.AppendLine("SELECT * FROM [" + item["TableName"] + "] AS " +
                                           item["TableName"] + "_" + item["TableName"]);
                }

                string sql = SqlJoinMakerRecursive(item, item["TableName"] + "_" + item["TableName"]);
                _sqlBuilder.AppendLine();
                count = 0;

                if (seperateFiles)
                {
                    string sqlOutPut = sql.Replace("{", string.Empty).Replace("}", string.Empty).ToString();
                    Util.SaveOutput(item["TableName"].ToString() + "Query", dest, sqlOutPut);
                    _sqlBuilder.Clear();
                }
            }

            if (!seperateFiles)
            {
                string sqlOutPut = _sqlBuilder.Replace("{", string.Empty).Replace("}", string.Empty).ToString();
                Util.SaveOutput(conn.Database, dest, sqlOutPut);
                _sqlBuilder.Clear();
            }
        }
Exemplo n.º 52
0
        public SqlGTResults Execute(SqlConnection connection,
                                    string procedureName)
        {
            SqlGTResults results = new SqlGTResults();

            // Configure the SqlCommand and SqlParameter.
            SqlCommand insertCommand = new SqlCommand(procedureName, connection);

            insertCommand.CommandType = CommandType.StoredProcedure;
            foreach (object p in this.InputParameters.Keys)
            {
                insertCommand.Parameters.AddWithValue("@" + p, this.InputParameters[p]);
            }
            foreach (object p in this.InputList.Keys)
            {
                SqlParameter tvpParam = insertCommand.Parameters.AddWithValue("@" + p,
                                                                              SqlGTUtil.ConvertToDataTable((List <object>)InputList[p]));
                tvpParam.SqlDbType = SqlDbType.Structured;
            }
            //caso tenha sessao aqui
            //e não tenha informado forçar
            if (!insertCommand.Parameters.Contains("SESSION_ID") &&
                this.session != null)
            {
                insertCommand.Parameters.AddWithValue("@SESSION_ID", this.session.Id);
            }


            //executar / pegar resultados
            System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(insertCommand);
            DataSet ds = new DataSet();

            adapter.Fill(ds);

            //pegar as tabelas de retorno
            foreach (DataTable dt in ds.Tables)
            {
                if (dt.Rows.Count == 0)
                {
                    continue;
                }
                //table name
                dt.TableName = (string)dt.Rows[0]["OPTION_OUTPUT_TABLE"];

                //tabela especial de resultados
                if ((string)dt.Rows[0]["OPTION_OUTPUT_TABLE"] == "RESULT")
                {
                    results.ResultCode      = (string)dt.Rows[0]["CODIGO"];
                    results.ResultType      = (string)dt.Rows[0]["TIPO"];
                    results.ResultMessage   = (string)dt.Rows[0]["MENSAGEM"];
                    results.ResultException = (string)dt.Rows[0]["EXCEPTION"];
                }
                //para cada datable remove coluna de apoio
                dt.Columns.Remove("OPTION_OUTPUT_TABLE");
                //adiciona
                results.Tables.Add(dt);
            }
            if (results.ResultCode == null)
            {
                throw new Exception("SqlGT: resposta invalida de procedure não contém dados de controle.");
            }
            if (!ds.Tables.Contains("DEFAULT"))
            {
                throw new Exception("SqlGT: resposta invalida de procedure não contém dados padrao de retorno.");
            }

            return(results);
        }
Exemplo n.º 53
0
        static void Main(string[] args)
        {
            Console.WriteLine("Input command (/y /d /YM /Missing (Year/Day/YearMonth))");
            string command  = Console.ReadLine();
            string day      = "";
            int    year     = 2018;
            int    month    = 1;
            int    daysback = 31;
            string mode     = "day";

            switch (command)
            {
            case "/y":
                Console.WriteLine("Input year to import: ");
                year = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Importing " + year);
                mode = "year";
                break;

            case "/d":
                Console.WriteLine("Input day to import(yyyy-DD-mm): ");
                day = Console.ReadLine();
                Console.WriteLine("Importing " + day);
                mode = "Day";
                break;

            case "/YM":
                Console.WriteLine("Input year: ");
                year = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Input month: ");
                month = Convert.ToInt32(Console.ReadLine());
                mode  = "YM";
                break;

            case "/Missing":
                Console.WriteLine("Type how many days back to check: ");
                daysback = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Importing data from " + daysback + " days back");
                mode = "Missing";
                break;



            default:
                break;
            }

            if (mode == "YM")
            {
                GetDatesMonth(year, month);
            }
            if (mode == "Day")
            {
                FetchData(day);
            }
            if (mode == "year")
            {
                GetDatesYear(year);
            }

            if (mode == "Missing")
            {
                Console.WriteLine("Got into Missing mode");
                //Get missing dates from sql proc
                var connection = System.Configuration.ConfigurationManager.ConnectionStrings["PostListe"].ConnectionString;
                using (SqlConnection db = new SqlConnection(connection))
                {
                    db.Open();

                    SqlCommand GetMissingDates = new SqlCommand(@"[PostListe].[dbo].[GetMissingDays]", db);
                    Console.WriteLine(GetMissingDates);
                    GetMissingDates.Parameters.AddWithValue("@DaysBack", daysback);
                    GetMissingDates.CommandType = CommandType.StoredProcedure;
                    SqlDataAdapter MissingDatesResult = new System.Data.SqlClient.SqlDataAdapter(GetMissingDates);
                    DataSet        ds = new DataSet();
                    MissingDatesResult.Fill(ds);

                    Console.WriteLine(ds.Tables[0].DefaultView);

                    foreach (DataTable table in ds.Tables)
                    {
                        foreach (DataRow dr in table.Rows)
                        {
                            Console.WriteLine(dr["DateLookup"].ToString());
                            string CleanDate = dr["DateLookup"].ToString().Replace(" 00.00.00", "");
                            FetchData(CleanDate);
                        }
                    }

                    db.Close();
                }
            }

            Console.ReadKey();
        }
Exemplo n.º 54
0
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (propertyid == -1)
        {
            Response.Redirect(backlinkurl);
        }

        //string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        //CommonFunctions.Connection.ConnectionString = connectionstring;

        //if (CommonFunctions.Connection.State == System.Data.ConnectionState.Closed)
        //CommonFunctions.Connection.Open ();

        object retval = null;

        using (SqlConnection connection = CommonFunctions.GetConnection()) {
            connection.Open();
            SqlCommand checkuserid = new SqlCommand("SELECT UserID FROM Properties WHERE ID=@PropertyID", connection);
            checkuserid.Parameters.Add("@PropertyID", SqlDbType.Int, 4, "PropertyID");
            checkuserid.Parameters["@PropertyID"].Value = propertyid;

            retval = checkuserid.ExecuteScalar();
            connection.Close();
        }

        if (!(retval is int))
        {
            Response.Redirect(backlinkurl);
        }

        if (((int)retval != userid) && !AuthenticationManager.IfAdmin)
        {
            Response.Redirect(CommonFunctions.PrepareURL("Login.aspx?BackLink=" + HttpUtility.UrlEncode(Request.Url.ToString())));
        }

        object retval2 = null;

        using (SqlConnection connection = CommonFunctions.GetConnection()) {
            connection.Open();
            SqlCommand checkauction = new SqlCommand("SELECT COUNT(*) " +
                                                     "FROM Auctions WHERE (Auctions.PropertyID = @PropertyID)", connection);
            checkauction.Parameters.Add("@PropertyID", SqlDbType.Int, 4, "PropertyID");
            checkauction.Parameters["@PropertyID"].Value = propertyid;

            retval2 = checkauction.ExecuteScalar();
            connection.Close();
        }

        ifauction = (retval2 is int) && ((int)retval2 > 0);

        if (ifauction)
        {
            object retval3 = null;
            using (SqlConnection connection = CommonFunctions.GetConnection()) {
                connection.Open();
                SqlCommand checkpaid = new SqlCommand("SELECT COUNT(*) " +
                                                      "FROM Transactions INNER JOIN Auctions ON Transactions.AuctionID = Auctions.ID " +
                                                      "WHERE (Auctions.PropertyID = @PropertyID) AND (Transactions.IfListingFee = 1)" +
                                                      " AND (Transactions.PaymentAmount >= Transactions.InvoiceAmount) AND (AuctionEnd < GETDATE())", connection);
                checkpaid.Parameters.Add("@PropertyID", SqlDbType.Int, 4, "PropertyID");
                checkpaid.Parameters["@PropertyID"].Value = propertyid;

                retval3 = checkpaid.ExecuteScalar();
                connection.Close();
            }

            ifallow = (retval3 is int) && ((int)retval3 > 0);

            AllowedWarning.Text = "You can review emails only for finished and paid auctions.";
        }
        else
        {
            using (SqlConnection connection = CommonFunctions.GetConnection()) {
                connection.Open();
                SqlCommand checkpaid = new SqlCommand("SELECT COUNT(*) FROM Invoices WHERE (Invoices.PropertyID =" +
                                                      " @PropertyID) AND (PaymentAmount >= InvoiceAmount) AND (GETDATE() <= RenewalDate)", connection);
                checkpaid.Parameters.Add("@PropertyID", SqlDbType.Int, 4, "PropertyID");
                checkpaid.Parameters["@PropertyID"].Value = propertyid;

                object retval3 = checkpaid.ExecuteScalar();

                SqlCommand getstartdate = new SqlCommand("SELECT DateStartViewed FROM Properties WHERE ID = @PropertyID",
                                                         connection);
                getstartdate.Parameters.Add("@PropertyID", SqlDbType.Int, 4, "PropertyID");
                getstartdate.Parameters["@PropertyID"].Value = propertyid;

                object retval4 = getstartdate.ExecuteScalar();

                ifallow = ((retval3 is int) && ((int)retval3 > 0)) || ((retval4 is DateTime) &&
                                                                       ((DateTime.Now - (DateTime)retval4).TotalDays <= 60));

                connection.Close();
            }
            AllowedWarning.Text = "You can review emails only for paid properties.";
        }

        if (AuthenticationManager.IfAuthenticated && AuthenticationManager.IfAdmin)
        {
            ifallow = true;
        }

        AllowedWarning.Visible = !ifallow;

        EmailsAdapter.SelectCommand.Parameters["@PropertyID"].Value = propertyid;
        //lock (CommonFunctions.Connection)
        EmailsAdapter.Fill(EmailsSet);

        if (!IsPostBack)
        {
            DataBind();
        }
    }
Exemplo n.º 55
0
        private void btnExecute_Click(object sender, EventArgs e)
        {
            DataSet MyDataSet = new DataSet();

            System.Data.SqlClient.SqlDataAdapter DataAdapter = new System.Data.SqlClient.SqlDataAdapter();

            System.Data.SqlClient.SqlConnection myConnection = GetCnn();// new System.Data.SqlClient.SqlConnection(DBConnStr);
            if (myConnection.State != ConnectionState.Open)
            {
                myConnection.Open();
            }

            System.Data.SqlClient.SqlCommand myCommand = new System.Data.SqlClient.SqlCommand(); //("select 1", myConnection);
            myCommand.Connection  = myConnection;
            myCommand.CommandType = CommandType.Text;                                            // StoredProcedure;

            this.prgExec.Maximum = Procs.Count;
            prgExec.Value        = 0;
            this.Text            = string.Empty;

            string folder = txtDB.Text + (chkNew.Checked == true ? "AfterMove" : string.Empty);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }


            foreach (var proc in Procs)
            {
                txtProcs.Clear();
                txtProcs.AppendText(proc.Cmd);

                Application.DoEvents();
                myCommand.CommandText     = proc.Cmd;
                DataAdapter.SelectCommand = myCommand;

                DataAdapter.Fill(MyDataSet, "table");

                DataTable tb = MyDataSet.Tables[0].DefaultView.ToTable(true, proc.Columns.ToArray());

                tb.WriteXml(
                    string.Format("{0}\\{1}.xml",
                                  folder
                                  , proc.FileName
                                  ), true);
                prgExec.Value += 1;
                MyDataSet.Clear();
            }

            dataGridView1.DataSource = MyDataSet.Tables[0];


            this.Text = "success";


            if (myConnection.State == ConnectionState.Open)
            {
                myConnection.Close();
            }
        }
Exemplo n.º 56
0
 public void Ejecutar_Consulta(string strSQL)
 {
     _da = new System.Data.SqlClient.SqlDataAdapter(strSQL, _cn);
     _da.Fill(_ds);
     _tabla = _ds.Tables[0];
 }
    //-----------------------------------------------------------------------------
    //Funcion: EjecucionConsulta
    //Parámetro: bTiparDataset (System.Boolean)
    //Retorno: (System.Data.DataSet)
    //Descripcion: Ejecuta la consulta a partir de la consultaSQL , cadena de conexión que se le haya pasado.
    //             Si se le pone bTiparDataset, el dataset resultante tiene información del Esquema

    //-----------------------------------------------------------------------------
    //public  System.Data.DataSet EjecucionConsulta(bool bTiparDataset)
    //{
    //    DataSet dsActual = new DataSet();
    //    this.EjecucionConsulta(ref dsActual, bTiparDataset, String.Empty, null);
    //    return dsActual;
    //}

    //-----------------------------------------------------------------------------
    //Funcion: EjecucionConsulta
    //Parámetro: dsActual (System.Data.DataSet)
    //Parámetro: bTiparDataset (System.Boolean)
    //Descripcion: Ejecuta la consulta a partir de la consultaSQL , cadena de conexión que se le haya pasado.
    //             Si se le pone bTiparDataset, el dataset resultante tiene información del Esquema
    //             Rellena los datos resultantes en el dataset pasado

    //-----------------------------------------------------------------------------
    //public void EjecucionConsulta(ref DataSet dsActual, bool bTiparDataset)
    //{
    //    this._EjecucionConsulta(ref dsActual, bTiparDataset, String.Empty, null, CommandType.Text);
    //}

    //-----------------------------------------------------------------------------
    //Funcion: EjecucionConsulta
    //Parámetro: dsActual (System.Data.DataSet)
    //Parámetro: bTiparDataset (System.Boolean)
    //Parámetro: NombreTablaDestino (System.String)
    //Descripcion: Ejecuta la consulta a partir de la consultaSQL , cadena de conexión que se le haya pasado.
    //             Si se le pone bTiparDataset, el dataset resultante tiene información del Esquema
    //             Rellena los datos resultantes en el dataset pasado
    //             Asigna al dataset pasado el nombre de tabla tambien pasado

    //-----------------------------------------------------------------------------
    //public void EjecucionConsulta(ref DataSet dsActual, bool bTiparDataset, string NombreTablaDestino)
    //{
    //    this._EjecucionConsulta(ref dsActual, bTiparDataset, NombreTablaDestino, null, CommandType.Text);
    //}

    //-----------------------------------------------------------------------------
    //Funcion: EjecucionConsulta
    //Parámetro: dsActual (System.Data.DataSet)
    //Parámetro: bTiparDataset (System.Boolean)
    //Parámetro: NombreTablaDestino (System.String)
    //Parámetro: oTransaccion (System.Data.IDbTransaction)
    //Descripcion: Ejecuta la consulta a partir de la consultaSQL , cadena de conexión que se le haya pasado.
    //             Si se le pone bTiparDataset, el dataset resultante tiene información del Esquema
    //             Rellena los datos resultantes en el dataset pasado
    //             Asigna al dataset pasado el nombre de tabla tambien pasado
    //             Si se le pasa la transacción, se obtiene la conexion del otransaccion

    //-----------------------------------------------------------------------------
    //public void EjecucionConsulta(ref DataSet dsActual, bool bTiparDataset, string NombreTablaDestino, System.Data.IDbTransaction oTransaccion)
    //{
    //    this._EjecucionConsulta(ref dsActual, bTiparDataset, NombreTablaDestino, oTransaccion, CommandType.Text);
    //}

    //-----------------------------------------------------------------------------
    //Funcion: EjecucionConsulta
    //Parámetro: dsActual (System.Data.DataSet)
    //Parámetro: bTiparDataset (System.Boolean)
    //Parámetro: NombreTablaDestino (System.String)
    //Parámetro: oTransaccion (System.Data.IDbTransaction)
    //Descripcion: Ejecuta la consulta a partir de la consultaSQL , cadena de conexión que se le haya pasado.
    //             Si se le pone bTiparDataset, el dataset resultante tiene información del Esquema
    //             Rellena los datos resultantes en el dataset pasado
    //             Asigna al dataset pasado el nombre de tabla tambien pasado
    //             Si se le pasa la transacción, se obtiene la conexion del otransaccion
    //-----------------------------------------------------------------------------
    //private void _EjecucionConsulta(ref DataSet dsActual, bool bTiparDataset, string NombreTablaDestino, System.Data.IDbTransaction oTransaccion, System.Data.CommandType Tipoconsulta)
    //{
    //    System.Data.SqlClient.SqlConnection oSqlConnection;
    //    System.Data.SqlClient.SqlDataAdapter oSqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
    //    System.Data.SqlClient.SqlCommand oSqlCommand = new System.Data.SqlClient.SqlCommand();

    //    bool bTransaccionCreadaEnLaFuncion = true;

    //    // si se le pasa una transaccion, le asignamos la conexion
    //    if (oTransaccion != null)
    //    {
    //        bTransaccionCreadaEnLaFuncion = false;
    //        oSqlConnection = ((System.Data.SqlClient.SqlConnection)oTransaccion.Connection);
    //    }
    //    else
    //    {
    //        oSqlConnection = new System.Data.SqlClient.SqlConnection();
    //    }

    //    try
    //    {
    //        // Si de antemano, sabemos que no es posible la ejecución lanzamos el error.
    //        if (this.CadenaConexion == String.Empty)
    //        {
    //            throw new Exception("Falta establecer la cadena de conexión");
    //        }

    //        if (this.ConsultaSQL == String.Empty)
    //        {
    //            throw new Exception("Falta establecer la cadena de consulta");
    //        }

    //        oSqlCommand.Connection = oSqlConnection;
    //        oSqlCommand.CommandType = Tipoconsulta;
    //        oSqlCommand.CommandText = this.ConsultaSQL;
    //        if (this.nTiempoEjecucionConsulta != -1)
    //        {
    //            oSqlCommand.CommandTimeout = nTiempoEjecucionConsulta;
    //        }

    //        for (int nInd = 0; nInd < this._NombreParametros.Count; nInd++)
    //        {
    //            // oSqlCommand.Parameters.Add("@" + Convert.ToString(_NombreParametros(nInd)), Convert.ToString(_ValorParametros(nInd)));
    //            oSqlCommand.Parameters.AddWithValue("@" + Convert.ToString(_NombreParametros[nInd]), Convert.ToString(_ValorParametros[nInd]));
    //        }

    //        // si no tiene  transaccion, asignamos la cadena de conexion y la abrimos
    //        if (oTransaccion == null)
    //        {
    //            oSqlConnection.ConnectionString = this.CadenaConexion;
    //            oSqlConnection.Open();
    //            oTransaccion = oSqlConnection.BeginTransaction(IsolationLevel.ReadUncommitted);
    //            oSqlCommand.Transaction = ((System.Data.SqlClient.SqlTransaction)oTransaccion);
    //        }
    //        else
    //        {
    //            oSqlCommand.Transaction = ((System.Data.SqlClient.SqlTransaction)oTransaccion);
    //        }

    //        oSqlDataAdapter.SelectCommand = oSqlCommand;
    //        if ((NombreTablaDestino != null && NombreTablaDestino != String.Empty))
    //        {
    //            if (NombreTablaDestino.IndexOf(";") > -1)
    //            { //si hay mas de una tabla, hay que hacer un mapeo de ellas
    //                string[] tablas;
    //                tablas = Split(NombreTablaDestino, ";");
    //                int i = 0;
    //                oSqlDataAdapter.TableMappings.AddRange(new System.Data.Common.DataTableMapping() { new System.Data.Common.DataTableMapping("Table", dsActual.Tables[0].TableName, new System.Data.Common.DataColumnMapping(-1) { }) });
    //                for (i = 1; i < tablas.Length; i++)
    //                {
    //                    oSqlCommand.Parameters.AddWithValue("@" + Convert.ToString(_NombreParametros[nInd]), Convert.ToString(_ValorParametros[nInd]));
    //                }
    //                oSqlDataAdapter.Fill(dsActual);
    //            }
    //            else
    //            {
    //                oSqlDataAdapter.Fill(dsActual, NombreTablaDestino);
    //            }
    //        }
    //        else
    //        {
    //            oSqlDataAdapter.Fill(dsActual);
    //        }
    //        if (bTiparDataset)
    //        {
    //            oSqlDataAdapter.FillSchema(dsActual, SchemaType.Mapped);
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //        if (bTransaccionCreadaEnLaFuncion)
    //        {
    //            oTransaccion.Rollback();
    //        }
    //    }
    //    finally
    //    {
    //        // si la transaccion es nula, se cierra la conexion
    //        if (oTransaccion == null || bTransaccionCreadaEnLaFuncion)
    //        {
    //            if (oSqlConnection != null)
    //            {
    //                if (oTransaccion != null && oTransaccion.Connection !== null)
    //                {
    //                    oTransaccion.Commit();
    //                    oTransaccion.Dispose();
    //                }
    //                if (oSqlConnection.State != ConnectionState.Closed)
    //                {
    //                    oSqlConnection.Close();
    //                }
    //                oSqlConnection.Dispose();
    //            }
    //        }
    //    }
    //}


    #endregion

    // TODO: saber donde se utiliza!
    //public System.Data.DataSet EjecucionConsulta(bool bTiparDataset, int filaOrigen, int nLineas, string nombreTabla)
    public System.Data.DataSet EjecucionConsulta(bool bTiparDataset, string nombreTabla)
    {
        System.Data.SqlClient.SqlConnection  oSqlConnection  = new System.Data.SqlClient.SqlConnection();
        System.Data.SqlClient.SqlDataAdapter oSqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
        System.Data.SqlClient.SqlCommand     oSqlCommand     = new System.Data.SqlClient.SqlCommand();
        System.Data.DataSet oDataset = new System.Data.DataSet();
        int nInd; //Contador para bucle insercion parametros

        try
        {
            //Si de antemano, sabemos que no es posible la ejecución lanzamos el error.
            if (this.CadenaConexion == String.Empty)
            {
                throw new Exception("Falta establecer la cadena de conexión");
            }

            if (this.ConsultaSQL == String.Empty)
            {
                throw new Exception("Falta establecer la cadena de consulta");
            }

            oSqlCommand.Connection  = oSqlConnection;
            oSqlCommand.CommandType = CommandType.Text;
            oSqlCommand.CommandText = this.ConsultaSQL;
            if (this.nTiempoEjecucionConsulta != -1)
            {
                oSqlCommand.CommandTimeout = nTiempoEjecucionConsulta;
            }

            for (nInd = 0; nInd < this._NombreParametros.Count; nInd++)
            {
                // oSqlCommand.Parameters.Add("@" + Convert.ToString(_NombreParametros(nInd)), Convert.ToString(_ValorParametros(nInd)));
                oSqlCommand.Parameters.AddWithValue("@" + Convert.ToString(_NombreParametros[nInd]), Convert.ToString(_ValorParametros[nInd]));
            }

            oSqlConnection.ConnectionString = this.CadenaConexion;
            oSqlConnection.Open();

            oSqlDataAdapter.SelectCommand = oSqlCommand;
            //oSqlDataAdapter.Fill(oDataset, filaOrigen, nLineas, nombreTabla);
            oSqlDataAdapter.Fill(oDataset, nombreTabla);
            if (bTiparDataset)
            {
                oSqlDataAdapter.FillSchema(oDataset, SchemaType.Mapped);
            }

            return(oDataset);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (oSqlConnection != null)
            {
                if (oSqlConnection.State != ConnectionState.Closed)
                {
                    oSqlConnection.Close();
                }
                oSqlConnection.Dispose();
            }
        }
    }
Exemplo n.º 58
0
 private void LlenaNivel()
 {
     sqlDANivel.Fill(dsNivel1, "Nivel");
 }
Exemplo n.º 59
0
        string Message(string _Type, string MCID, string Description, out string refno)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("");
            string _message      = string.Empty;
            string _finalMessage = string.Empty;

            string[] Msg = null;
            refno = string.Empty;
            if (MCID != null)
            {
                string sql = " SELECT     dbo.tblMC.vsMissionClearnceName, dbo.tblMC.CreateDate, dbo.tblMC.bMissionApproved, fromtblUserMaster.vsFirstName AS FromFirstName, ";
                sql = sql + "   fromtblUserMaster.vsLastName AS FromLastName, fromtblDesignationMaster.vsDesignationName AS FromDesignation, ";
                sql = sql + "   TotblUserMaster.vsFirstName AS ToFirstName, TotblUserMaster.vsLastName AS ToLastName, TotblDesignationMaster.vsDesignationName AS ToDesignation, ";
                sql = sql + "     fromtblUserMaster.iAgencyID, tblAgency_1.vsAgencyName AS FrmAgency, dbo.tblAgency.vsAgencyName AS ToAgency ";
                sql = sql + " FROM         dbo.tblMC INNER JOIN ";
                sql = sql + "   dbo.tblUserMaster AS fromtblUserMaster ON dbo.tblMC.iFromUser = fromtblUserMaster.iUserID INNER JOIN ";
                sql = sql + "    dbo.tblDesignationMaster AS fromtblDesignationMaster ON fromtblUserMaster.iDesignationID = fromtblDesignationMaster.iDesignationID INNER JOIN ";
                sql = sql + "   dbo.tblUserMaster AS TotblUserMaster ON dbo.tblMC.iToUser = TotblUserMaster.iUserID INNER JOIN ";
                sql = sql + "   dbo.tblDesignationMaster AS TotblDesignationMaster ON TotblUserMaster.iDesignationID = TotblDesignationMaster.iDesignationID INNER JOIN";
                sql = sql + "   dbo.tblAgency AS tblAgency_1 ON fromtblUserMaster.iAgencyID = tblAgency_1.iAgencyID INNER JOIN ";
                sql = sql + "   dbo.tblAgency ON TotblUserMaster.iAgencyID = dbo.tblAgency.iAgencyID";
                sql = sql + " WHERE     dbo.tblMC.iMissionClearanceId =" + MCID;
                SqlConnection  cn  = new SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);
                SqlDataAdapter ad  = new System.Data.SqlClient.SqlDataAdapter(sql, cn);
                DataSet        ds1 = new DataSet();
                ad.Fill(ds1);

                string dtcreate = Convert.ToDateTime(ds1.Tables[0].Rows[0]["CreateDate"].ToString()).ToString("dd MMM yyyy");
                refno = ds1.Tables[0].Rows[0]["vsMissionClearnceName"].ToString();

                if (_Type.ToString() == "Approved")
                {
                    Msg = File.ReadAllLines(Server.MapPath(@"~/writereaddata/RequestAproval.txt"));
                    for (int i = 0; i < Msg.Length; i++)
                    {
                        Msg[i] = Msg[i].Replace("<user name>", ds1.Tables[0].Rows[0]["FromFirstName"].ToString() + "  " + ds1.Tables[0].Rows[0]["FromLastName"].ToString());// (((UserDetails)Session[clsConstant.TOKEN]).userNm).ToString());
                        Msg[i] = Msg[i].Replace("<Mission clearance reference No>", Request.QueryString["MCID"].ToString());
                        Msg[i] = Msg[i].Replace("<Mission clearance reference Description>", ds1.Tables[0].Rows[0]["vsMissionClearnceName"].ToString());
                        Msg[i] = Msg[i].Replace("<Mission clearance request submission date>", dtcreate.ToString());
                        Msg[i] = Msg[i].Replace("<sender first name>", ds1.Tables[0].Rows[0]["ToFirstName"].ToString());
                        Msg[i] = Msg[i].Replace("<sender last name>", ds1.Tables[0].Rows[0]["ToLastName"].ToString());
                        Msg[i] = Msg[i].Replace("<Designation>", ds1.Tables[0].Rows[0]["ToDesignation"].ToString());
                        Msg[i] = Msg[i].Replace("<Department of External Affairs>", (((UserDetails)Session[clsConstant.TOKEN]).AgencyName).ToString());
                        Msg[i] = Msg[i].Replace("<cc list of all original CC list>", "");
                    }

                    for (int i = 0; i < Msg.Length; i++)
                    {
                        _finalMessage += Msg[i] + "\n";
                    }



                    sb.Append("");
                    sb.Append("");
                    sb.Append("------------------ Message ----------------\n");

                    string sqlmsg = " SELECT top 1 REPLACE(convert(varchar(2000),memosendMessage),'<br>','\n') AS memosendMessage FROM    tblDocSend";
                    sqlmsg = sqlmsg + " where imcid=" + MCID;
                    sqlmsg = sqlmsg + "  order by  idocsendid desc";
                    SqlConnection  cnmsg = new SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);
                    SqlDataAdapter admsg = new System.Data.SqlClient.SqlDataAdapter(sqlmsg, cnmsg);
                    DataSet        dsmsg = new DataSet();
                    admsg.Fill(dsmsg);
                    try
                    {
                        _message = _finalMessage + sb.ToString() + dsmsg.Tables[0].Rows[0]["memoSendMessage"].ToString();
                    }
                    catch { }
                }
                else if (_Type.ToString() == "Rejected")
                {
                    Msg = File.ReadAllLines(Server.MapPath(@"~/writereaddata/RequestRejection.txt"));
                    for (int i = 0; i < Msg.Length; i++)
                    {
                        Msg[i] = Msg[i].Replace("<user name>", ds1.Tables[0].Rows[0]["FromFirstName"].ToString() + " " + ds1.Tables[0].Rows[0]["FromLastName"].ToString());// (((UserDetails)Session[clsConstant.TOKEN]).userNm).ToString());
                        Msg[i] = Msg[i].Replace("<Mission clearance reference No>", MCID);
                        Msg[i] = Msg[i].Replace("<Mission clearance reference Description>", ds1.Tables[0].Rows[0]["vsMissionClearnceName"].ToString());
                        Msg[i] = Msg[i].Replace("<Mission clearance request submission date>", dtcreate.ToString());
                        Msg[i] = Msg[i].Replace("<Reasons>", Description);

                        Msg[i] = Msg[i].Replace("<sender first name>", (((UserDetails)Session[clsConstant.TOKEN]).FirstName).ToString());
                        Msg[i] = Msg[i].Replace("<sender last name>", (((UserDetails)Session[clsConstant.TOKEN]).LastName).ToString());
                        Msg[i] = Msg[i].Replace("<Designation>", (((UserDetails)Session[clsConstant.TOKEN]).Designation).ToString());
                        Msg[i] = Msg[i].Replace("<Department of External Affairs>", (((UserDetails)Session[clsConstant.TOKEN]).AgencyName).ToString());
                        Msg[i] = Msg[i].Replace("<cc list of all original CC list>", "");
                    }

                    for (int i = 0; i < Msg.Length; i++)
                    {
                        _message += Msg[i] + "\n";
                    }


                    sb.Append("");
                    sb.Append("");
                    sb.Append("------------------ Message ----------------\n");

                    string sqlmsg = " SELECT top 1 REPLACE(convert(varchar(2000),memosendMessage),'<br>','\n') AS memosendMessage FROM    tblDocSend";
                    sqlmsg = sqlmsg + " where imcid=" + MCID;
                    sqlmsg = sqlmsg + "  order by  idocsendid desc";
                    SqlConnection  cnmsg = new SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);
                    SqlDataAdapter admsg = new System.Data.SqlClient.SqlDataAdapter(sqlmsg, cnmsg);
                    DataSet        dsmsg = new DataSet();
                    admsg.Fill(dsmsg);
                    try
                    {
                        _message = _message + sb.ToString() + dsmsg.Tables[0].Rows[0]["memoSendMessage"].ToString();
                    }
                    catch { }

                    _finalMessage = _message;
                }

                else if (_Type.ToString() == "Clarification")
                {
                    sb.Append("\n");
                    sb.Append(File.ReadAllText(Server.MapPath(@"~/writereaddata/Clarification.txt")));

                    sb.Replace("<Mission clearance reference No>", MCID.ToString());


                    sb.Replace("<Mission clearance reference Description>", ds1.Tables[0].Rows[0]["vsMissionClearnceName"].ToString());
                    sb.Replace("The following clarifications are needed :", "The following clarifications are needed :\n" + Description);

                    sb.Append("");
                    sb.Append("------------------ Message ----------------\n");

                    string sqlmsg = " SELECT top 1 REPLACE(convert(varchar(2000),memosendMessage),'<br>','\n') AS memosendMessage FROM    tblDocSend";
                    sqlmsg = sqlmsg + " where imcid=" + MCID;
                    sqlmsg = sqlmsg + "  order by  idocsendid desc";
                    SqlConnection  cnmsg = new SqlConnection(ConfigurationManager.ConnectionStrings["TA7511DBConnString"].ConnectionString);
                    SqlDataAdapter admsg = new System.Data.SqlClient.SqlDataAdapter(sqlmsg, cnmsg);
                    DataSet        dsmsg = new DataSet();
                    admsg.Fill(dsmsg);
                    try
                    {
                        _message = dsmsg.Tables[0].Rows[0]["memoSendMessage"].ToString();
                    }
                    catch { }

                    _finalMessage = sb.ToString() + _message;
                }
            }

            return(_finalMessage);
        }
Exemplo n.º 60
0
 private void LlenasSqlDA()
 {
     sqlDAConcentra.SelectCommand.Parameters["@IdObra"].Value = cmbIdObra.SelectedValue.ToString();
     sqlDAConcentra.Fill(dsConcentra1, "Concentra");
 }