Inheritance: System.Data.Common.DbConnection, ICloneable
        public static DataTable GetHandoverLogByHandoverLogId(int handoverLogId)
        {
            string connectionString = ConnectionStringFactory.GetNXJCConnectionString();
            DataSet ds = new DataSet();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = @"SELECT  WorkingTeamShiftLog.*,
                                                StaffInfo.Name AS ChargeManName, ProductLine.Name AS ProductLineName,
                                                WorkingTeam.Name AS WorkingTeamName
                                        FROM    WorkingTeam INNER JOIN
                                                StaffInfo INNER JOIN
                                                WorkingTeamShiftLog ON StaffInfo.ID = WorkingTeamShiftLog.ChargeManID INNER JOIN
                                                ProductLine ON WorkingTeamShiftLog.ProductLineID = ProductLine.ID ON
                                                WorkingTeam.ID = WorkingTeamShiftLog.WorkingTeamID
                                        WHERE   (WorkingTeamShiftLog.ID = @workingTeamShiftLogID)";

                command.Parameters.Add(new SqlParameter("workingTeamShiftLogID", handoverLogId));
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(ds);
            }

            return ds.Tables[0];
        }
 public bool Delete(string empresaid, tb_co_tabla01_mediopago BE)
 {
     using (SqlConnection cnx = new SqlConnection(conex.empConexion(empresaid)))
     {
         using (SqlCommand cmd = new SqlCommand("gspTbCoTabla01Mediopago_DELETE", cnx))
         {
             {
                 cmd.CommandTimeout = 0;
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.Parameters.Add("@codigoid", SqlDbType.Char, 3).Value = BE.codigoid;
             }
             try
             {
                 cnx.Open();
                 if (cmd.ExecuteNonQuery() > 0)
                 {
                     return true;
                 }
                 else
                 {
                     return false;
                 }
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }
     }
 }
        public static void Main()
        {
            using (SqlConnection dbcon = new SqlConnection(ImageExtracter.ConnectionString))
            {
                dbcon.Open();

                SqlCommand command = new SqlCommand("SELECT Picture FROM Categories", dbcon);
                var reader = command.ExecuteReader();
                var counter = 0;

                while (reader.Read())
                {
                    byte[] imageByteArray = (byte[])reader["Picture"];

                    const int oleMetaPictStartPosition = 78;
                    var memoryStream =
                        new MemoryStream(imageByteArray, oleMetaPictStartPosition,
                            imageByteArray.Length - oleMetaPictStartPosition);

                    using (memoryStream)
                    {
                        using (var image = Image.FromStream(memoryStream, true, true))
                        {
                            image.Save("../../picture" + (++counter) + ".jpg");
                        }
                    }
                }
            }

            Console.WriteLine("Images exported successfully!");
            Console.WriteLine("See project folder for results!");
        }
 public static DataTable Ilceler(int id)
 {
     try
     {
         using (baglan = new SqlConnection(ConnectionString))
         {
             baglan.Open();
             using (komutver = new SqlCommand())
             {
                 komutver.Connection = baglan;
                 komutver.CommandText = "ilce_Listele";
                 komutver.Parameters.Add("@ilceId", SqlDbType.Int);
                 komutver.Parameters["@ilceId"].Value = Convert.ToInt32(id);
                 komutver.CommandType = CommandType.StoredProcedure;
                 adp = new SqlDataAdapter(komutver);
                 dt = new DataTable();
                 adp.Fill(dt);
             }
         }
     }
     catch (Exception)
     {
         throw;
     }
     return dt;
 }
示例#5
1
        public static void Main()
        {
            var connection = new SqlConnection(connectionString: "Server=(local); Database=Northwind; Integrated Security=true;");
            connection.Open();
            var command = new SqlCommand(cmdText: "select c.CategoryName, p.ProductName from Products p inner join Categories c on c.CategoryId = p.CategoryId;", connection: connection);

            var categoriesAndProducts = new Dictionary<string, List<string>>();
            var reader = command.ExecuteReader();
            while (reader.Read())
            {
                var category = (string)reader["CategoryName"];
                var product = (string)reader["ProductName"];
                if(categoriesAndProducts.ContainsKey(category))
                {
                    categoriesAndProducts[category].Add(product);
                }
                else
                {
                    categoriesAndProducts.Add(category, new List<string>());
                }
            }

            connection.Close();

            foreach (var kvp in categoriesAndProducts)
            {
                Console.WriteLine(new string(c: '=', count: 20) + "\n" + kvp.Key + "\n" + new string(c: '=', count: 20));

                foreach (var product in kvp.Value)
                {
                    Console.WriteLine("-- " + product);
                }
            }
        }
 private void repositoryItemButtonEditSave_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
 {
     if (MessageBox.Show("هل انت متأكد؟", "تحزيــــر", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
         return;
     DataRow Row = (DataRow)gridViewMain.GetFocusedDataRow();
     SqlConnection con = new SqlConnection(MyCL.SqlConStr);
     SqlCommand cmd = new SqlCommand("", con);
     try
     {
         if (Row["knowID"].ToString() == string.Empty)// Is Unsaved Row?
         {
             string NewID = MyCL.GetNewID("CDknow", "knowID");
             cmd.CommandText = string.Format(@"Insert Into CDknow (knowID, know) VALUES ({0}, '{1}')",
             NewID, Row["know"]);
         }
         else
         {
             cmd.CommandText = string.Format(@"Update CDknow Set know = '{0}' Where knowID = {1}",
             Row["know"], Row["knowID"]);
         }
         con.Open();
         cmd.ExecuteNonQuery();
         MyCL.ShowMsg("تم الحفظ", false, this);
     }
     catch (SqlException ex)
     {
         MyCL.ShowMsg(MyCL.CheckExp(ex), true, this);
     }
     con.Close();
     LoadData();
 }
示例#7
1
 public static SqlConnection createConnection()
 {
     SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;" +
         "AttachDbFilename=C:\\Users\\Edson\\Downloads\\Solution\\Solution\\WebApp\\WebApp\\App_Data\\Database.mdf;" +
         "Integrated Security=True;Connect Timeout=30");
     return conn;
 }
示例#8
1
        static void Main(string[] args)
        {
            Console.Write("Enter some text to search for it in the Products: ");
            var searchedProduct = Console.ReadLine();

            SqlConnection dbCon = new SqlConnection("Server=localhost; " +
                "Database=NORTHWND; Integrated Security=true");
            dbCon.Open();
            using (dbCon)
            {
                SqlCommand cmd = new SqlCommand(
                    "SELECT ProductName FROM Products " +
                    "WHERE CHARINDEX (@searchedProduct, ProductName)>0", dbCon);

                cmd.Parameters.AddWithValue("@searchedProduct", searchedProduct);

                SqlDataReader reader = cmd.ExecuteReader();
                using (reader)
                {
                    while (reader.Read())
                    {
                        string productName = (string)reader["ProductName"];
                        Console.WriteLine(productName);
                    }
                }
            }
        }
示例#9
1
        public string InsertKhachHang(string TenKH, string Gioitinh, string Diachi, string SDT, string LoaiKH, string Ghichu)
        {
            string str = "";
            string sql = "InsertKH";
            //   string sql = "insert NhomSP values (@Manhom, @Tennhom, @NgayCN)";
            SqlConnection con = new SqlConnection(KetNoiDB.getconnect());
            con.Open();
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@TenKH", TenKH);
            cmd.Parameters.AddWithValue("@gt", Gioitinh);
            cmd.Parameters.AddWithValue("@DC", Diachi);
            cmd.Parameters.AddWithValue("@SDT", SDT);
            cmd.Parameters.AddWithValue("@LoaiKH", LoaiKH);
            cmd.Parameters.AddWithValue("@ghichu", Ghichu);
            //cmd.ExecuteNonQuery();

            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            str = dt.Rows[0].ItemArray[0].ToString();

            cmd.Dispose();
            con.Close();

            return str;
        }
示例#10
1
        public static int PH_BHTrans_Calc(string strConnDB, string strYearWeek)
        {
            try
            {
                int rtn = 0;
                using (SqlConnection sqlConn = new SqlConnection(strConnDB))
                {
                    if (sqlConn.State == ConnectionState.Closed ) sqlConn.Open();
                    SqlCommand sqlComm = new SqlCommand("usp_BH_Transaction_Calc", sqlConn);
                    sqlComm.CommandText = "usp_BH_Transaction_Calc";
                    sqlComm.CommandType = CommandType.StoredProcedure;
                    sqlComm.CommandTimeout = 0;
                    sqlComm.Parameters.AddRange(new SqlParameter[] { new SqlParameter("@Tesco_Week", strYearWeek) });
                    rtn = sqlComm.ExecuteNonQuery();
                }
                    //int rtn =
                    //SqlTransaction sqlTran = new SqlConnection(strConnDB).BeginTransaction();

                    //SqlHelper.ExecuteNonQuery(strConnDB, CommandType.StoredProcedure, "usp_BH_Transaction_Calc"
                    //            , new SqlParameter[] {new SqlParameter("@Tesco_Week",strYearWeek)
                    //                                 });

                    return rtn;
            }
            catch (Exception ex)
            {
                throw new Exception("PH_BHTrans_Calc >> " + ex.Message);
            }
        }
示例#11
1
 public bool CreateUser(UserInfo userInfo)
 {
     var salt = _helper.GenerateSalt();
     var pas = _helper.EncodePassword(userInfo.Password, salt);
     using (var connection = new SqlConnection(_configurationService.DatabaseConnectionString))
     {
         using (var command = connection.CreateCommand())
         {
             command.CommandType = CommandType.StoredProcedure;
             command.CommandText = "sp_CreateUser";
             command.Parameters.AddWithValue("@Login", userInfo.Login).SqlDbType = SqlDbType.NVarChar;
             command.Parameters.AddWithValue("@Password", pas).SqlDbType = SqlDbType.NVarChar;
             command.Parameters.AddWithValue("@PasswordSalt", salt).SqlDbType = SqlDbType.NVarChar;
             command.Parameters.AddWithValue("@Email", userInfo.Email).SqlDbType = SqlDbType.NVarChar;
             command.Parameters.AddWithValue("@Fio", userInfo.Fio).SqlDbType = SqlDbType.NVarChar;
             command.Parameters.AddWithValue("@Address", userInfo.Address).SqlDbType = SqlDbType.NVarChar;
             command.Parameters.AddWithValue("@Phone", userInfo.Phone).SqlDbType = SqlDbType.NVarChar;
             command.Parameters.AddWithValue("@Mobile", userInfo.Mobile).SqlDbType = SqlDbType.NVarChar;
             command.Parameters.AddWithValue("@Country", userInfo.Country).SqlDbType = SqlDbType.Char;
             command.Parameters.AddWithValue("@Zip", userInfo.Zip).SqlDbType = SqlDbType.NVarChar;
             var retParam = command.Parameters.AddWithValue("@Return", SqlDbType.Int);
             retParam.Direction = ParameterDirection.ReturnValue;
             connection.Open();
             command.ExecuteNonQuery();
             return (int)retParam.Value == 1;
         }
     }
 }
示例#12
1
        public IEnumerable<UserInfoShort> EnumerateClients(string fio, string login, int pageNumber, int countPerPage)
        {
            using (var connection = new SqlConnection(_configurationService.DatabaseConnectionString))
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "sp_EnumerateClients";
                    command.Parameters.AddWithValue("@FIO", fio ?? (object)DBNull.Value).SqlDbType = SqlDbType.NVarChar;
                    command.Parameters.AddWithValue("@Login",
                        login != null ? login.ToLower() : (object)DBNull.Value).SqlDbType = SqlDbType.NVarChar;
                    command.Parameters.AddWithValue("@PageNumber", pageNumber).SqlDbType = SqlDbType.Int;
                    command.Parameters.AddWithValue("@CountPerPage", countPerPage).SqlDbType = SqlDbType.Int;
                    connection.Open();
                    using (var reader = command.ExecuteReader())
                    {
                        var lst = new List<UserInfoShort>();
                        while (reader.Read())
                        {
                            lst.Add(new UserInfoShort
                                {
                                    UserId = (Guid)reader["UserId"],
                                    CounOfCardAccounts = (int)reader["CounOfCardAccounts"],
                                    FIO = (string)reader["FIO"],
                                    Login = (string)reader["Login"],
                                    RegistrationDate = (DateTime)reader["RegistrationDate"]
                                });
                        }

                        return lst;
                    }
                }
            }
        }
        private void DataPortal_Fetch(CategoryCriteria criteria)
        {
            bool cancel = false;
            OnFetching(criteria, ref cancel);
            if (cancel) return;

            string commandText = String.Format("SELECT [CategoryId], [Name], [Descn] FROM [dbo].[Category] {0}", ADOHelper.BuildWhereStatement(criteria.StateBag));
            using (var connection = new SqlConnection(ADOHelper.ConnectionString))
            {
                connection.Open();
                using (var command = new SqlCommand(commandText, connection))
                {
                    command.Parameters.AddRange(ADOHelper.SqlParameters(criteria.StateBag));
                    using(var reader = new SafeDataReader(command.ExecuteReader()))
                    {
                        if (reader.Read())
                            Map(reader);
                        else
                            throw new Exception(String.Format("The record was not found in 'dbo.Category' using the following criteria: {0}.", criteria));
                    }
                }
            }

            OnFetched();
        }
        protected override void DataPortal_Insert()
        {
            bool cancel = false;
            OnInserting(ref cancel);
            if (cancel) return;

            const string commandText = "INSERT INTO [dbo].[Category] ([CategoryId], [Name], [Descn]) VALUES (@p_CategoryId, @p_Name, @p_Descn)";
            using (var connection = new SqlConnection(ADOHelper.ConnectionString))
            {
                connection.Open();
                using(var command = new SqlCommand(commandText, connection))
                {
                    command.Parameters.AddWithValue("@p_CategoryId", this.CategoryId);
                command.Parameters.AddWithValue("@p_Name", ADOHelper.NullCheck(this.Name));
                command.Parameters.AddWithValue("@p_Descn", ADOHelper.NullCheck(this.Description));

                    //result: The number of rows changed, inserted, or deleted. -1 for select statements; 0 if no rows were affected, or the statement failed. 
                    int result = command.ExecuteNonQuery();
                    if (result == 0)
                        throw new DBConcurrencyException("The entity is out of date on the client. Please update the entity and try again. This could also be thrown if the sql statement failed to execute.");

                    LoadProperty(_originalCategoryIdProperty, this.CategoryId);
                }

                FieldManager.UpdateChildren(this, connection);
            }

            OnInserted();

        }
        public void addJedi(Jedi jedi)
        {
            string commande = "";

            List<Caracteristique> carac = jedi.Caracteristiques;
            if (carac != null)
            {
                foreach (Caracteristique c in carac)
                {
                    commande += "; INSERT INTO dbo.carac_jedi (id_jedi, id_carac) VALUES ((SELECT IDENT_CURRENT('jedi'))," + c.ID + ")";
                }
            }

            using (SqlConnection sqlConnection = new SqlConnection(m_connexionString))
            {

                jedi.Nom = jedi.Nom.Replace("'", "''");

                SqlCommand sqlAddJedi = new SqlCommand("INSERT INTO dbo.jedi (nom, isSith, image) VALUES('" + jedi.Nom + "', '" + jedi.IsSith + "', '" + jedi.Image + "')" + commande, sqlConnection);

                sqlAddJedi.Connection = sqlConnection;
                sqlConnection.Open();
                sqlAddJedi.ExecuteNonQuery();
                sqlConnection.Close();
            }
        }
 public DataSet GetAll(string empresaid, tb_co_tabla01_mediopago BE)
 {
     using (SqlConnection cnx = new SqlConnection(conex.empConexion(empresaid)))
     {
         using (SqlCommand cmd = new SqlCommand("gspTbCoTabla01Mediopago_SEARCH", cnx))
         {
             DataSet ds = new DataSet();
             {
                 cmd.CommandTimeout = 0;
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.Parameters.Add("@codigoid", SqlDbType.Char, 3).Value = BE.codigoid;
                 cmd.Parameters.Add("@descripcion", SqlDbType.VarChar, 100).Value = BE.descripcion;
                 cmd.Parameters.Add("@sigla", SqlDbType.Char, 3).Value = BE.sigla;
                 cmd.Parameters.Add("@usuar", SqlDbType.Char, 15).Value = BE.usuar;
             }
             try
             {
                 cnx.Open();
                 using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                 {
                     da.Fill(ds);
                 }
                 return ds;
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }
     }
 }
示例#17
1
 private DataTable GetTiposVenda()
 {
     DataTable dataTable = new DataTable();
     this.con = new SqlConnection(Security.GetCnn());
     string selectCommandText = "";
     if (this._dev != "D")
     {
         selectCommandText = "select tipo_venta_id, descripcion, devolucion from Tipo_venta where devolucion='N'";
     }
     else
     {
         selectCommandText = "select tipo_venta_id, descripcion, devolucion from Tipo_venta where devolucion='S'";
     }
     if ((this.con != null) && (this.con.State == ConnectionState.Open))
     {
         this.con.Close();
     }
     this.con.Open();
     try
     {
         new SqlDataAdapter(selectCommandText, this.con).Fill(dataTable);
         this.con.Close();
     }
     catch (Exception)
     {
     }
     return dataTable;
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
            string requestFromPost = reader.ReadToEnd();

            //loop through
               // string formValue;

            string speed;
            string initialLocation;
            string finalLocation;
            string IMEI;

            if (!string.IsNullOrEmpty(Request.Form["txtSpeed"]))
            {
                //formValue = Request.Form["txtSpeed"];
                //formValue = Request.Form["txtImei"];
                speed = Request.Form["Speed"];
                initialLocation = Request.Form["initialLocation"];
                finalLocation = Request.Form["finalLocation"];
                IMEI = Request.Form["IMEI"];

                string s = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
                SqlConnection cn = new SqlConnection(s);
                cn.Open();
                SqlCommand cmd = new SqlCommand("insert into DataHistory(Speed, initialLocation, finalLocation, IMEI)values('" + speed + "','" + initialLocation + "','" + finalLocation + "','" + IMEI + "')", cn);
                cmd.ExecuteNonQuery();

            }
        }
示例#19
1
        public void GetScheduledAppointments()
        {
            var con = new SqlConnection("Data Source=CSDB;Initial Catalog=SEI_Ninja;Persist Security Info=True;UID=sei_timemachine;PWD=z5t9l3x0");



            string sql = @"SELECT e.eventID, e.eventName, e.eventLocation, et.eventDate, et.eventDuration, u.user_first_name + ' ' + u.user_last_name AS name
                             FROM [SEI_Ninja].[dbo].SCHEDULED_USERS su
                                  JOIN [SEI_Ninja].[dbo].EVENT_TIMES et ON (su.eventTimeID = et.eventTimeID)
                                  JOIN [SEI_TimeMachine2].[dbo].[USER] u ON (su.userID = u.user_id)
                                  JOIN [SEI_Ninja].[dbo].EVENT e ON (et.eventID = e.eventID)
                            WHERE e.eventOwner = 'mgeary'
                            ORDER BY e.eventID";
            using (var command = new SqlCommand(sql, con))
            {
                con.Open();
                using (var reader = command.ExecuteReader())
                {
                    var list = new List<ScheduledAppointment>();
                    while (reader.Read())
                        list.Add(new ScheduledAppointment
                        {
                            eventID = reader.GetInt32(0),
                            eventName = reader.GetString(1),
                            eventLocation = reader.GetString(2),
                            eventDate = reader.GetDateTime(3),
                            eventDuration = (float)reader.GetDouble(4),
                            eventUserName = reader.GetString(5)
                        });
                    allAppointments = list.ToArray();
                }
            }
        }
示例#20
1
文件: Get.cs 项目: kincade71/is670
        public RootObjectOut GetMessageByUser(UserIn jm)
        {
            RootObjectOut output = new RootObjectOut();
            String jsonString = "";
            try
            {
                String strConnection = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
                SqlConnection Connection = new SqlConnection(strConnection);
                String strSQL = string.Format("SELECT message FROM messages WHERE msgTo = '{0}' AND [msgID] = (SELECT MAX(msgID) FROM messages WHERE msgTo='{1}')", jm.user.ToString(),jm.user.ToString());
                SqlCommand Command = new SqlCommand(strSQL, Connection);
                Connection.Open();
                SqlDataReader Dr;
                Dr = Command.ExecuteReader();
                if (Dr.HasRows)
                {
                    if (Dr.Read())
                    {
                        jsonString = Dr.GetValue(0).ToString();
                    }
                }
                Dr.Close();
                Connection.Close();
            }
            catch (Exception ex)
            {
                output.errorMessage = ex.Message;
            }
            finally
            {
            }
            JavaScriptSerializer ser = new JavaScriptSerializer();
            output = ser.Deserialize<RootObjectOut>(jsonString);

            return output;
        }
示例#21
1
        private static ICollection<string> FindProductBy(string partOfName)
        {
            var names = new List<string>();
            string connectionString = "Data Source=.;Initial Catalog=Northwind;Integrated Security=SSPI;";

            var dbCon = new SqlConnection(connectionString);

            dbCon.Open();
            using (dbCon)
            {
                SqlCommand command = new SqlCommand(
                    "SELECT p.ProductName FROM Products p WHERE p.ProductName LIKE @Search", dbCon);

                command.Parameters.AddWithValue("@Search", "%" + partOfName + "%");

                SqlDataReader reader = command.ExecuteReader();

                Console.WriteLine("\nProductNams that contains ({0}):\n", partOfName);
                using (reader)
                {
                    string categoryName = string.Empty;
                    string currentCategoryName = string.Empty;
                    while (reader.Read())
                    {
                        string productName = (string)reader["ProductName"];

                        names.Add(productName);
                    }
                }
            }

            return names;
        }
 public List<BootcampTechnology> GetAllBootcampTechnologies()
 {
     using (SqlConnection connection = new SqlConnection(Settings.GetConnectionString()))
     {
         return connection.Query<BootcampTechnology>("BootcampTechnologyGetAll", commandType: CommandType.StoredProcedure).ToList();
     }
 }
        public DataSet GetOne(string empresaid, tb_tipimpto BE)
        {
            using (SqlConnection cnx = new SqlConnection(conex.empConexion(empresaid)))
            {
                using (SqlCommand cmd = new SqlCommand("gspTbTipimpto_SELECT", cnx))
                {
                    DataSet ds = new DataSet();

                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@tipimptoid", SqlDbType.Char, 1).Value = BE.tipimptoid;
                    }

                    try
                    {
                        cnx.Open();
                        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                        {
                            da.Fill(ds);
                        }
                        return ds;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
            }
        }
 private void repositoryItemButtonEditDelete_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
 {
     if (MessageBox.Show("هل انت متأكد؟", "تحزيــــر", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
         return;
     DataRow Row = (DataRow)gridViewMain.GetFocusedDataRow();
     if (Row["knowID"].ToString() == string.Empty)// Is Unsaved Row?
     {
         LoadData();
         return;
     }
     SqlConnection con = new SqlConnection(MyCL.SqlConStr);
     SqlCommand cmd = new SqlCommand("", con);
     try
     {
         cmd.CommandText = @"Delete From CDknow Where knowID = " + Row["knowID"];
         con.Open();
         cmd.ExecuteNonQuery();
         MyCL.ShowMsg("تم الحذف", false, this);
     }
     catch (SqlException ex)
     {
         MyCL.ShowMsg(MyCL.CheckExp(ex), true, this);
     }
     con.Close();
     LoadData();
 }
 public bool Delete(string empresaid, tb_tipimpto BE)
 {
     using (SqlConnection cnx = new SqlConnection(conex.empConexion(empresaid)))
     {
         using (SqlCommand cmd = new SqlCommand("gspTbTipimpto_DELETE", cnx))
         {
             {
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.Parameters.Add("@tipimptoid", SqlDbType.Char, 1).Value = BE.tipimptoid;
             }
             try
             {
                 cnx.Open();
                 if (cmd.ExecuteNonQuery() > 0)
                 {
                     return true;
                 }
                 else
                 {
                     return false;
                 }
             }
             catch (Exception ex)
             {
                 throw new Exception(ex.Message);
             }
         }
     }
 }
        protected void load_price()
        {
            string price_name = null;
            string article = null;
            price_name = Request.QueryString["price_name"];
            article = Request.QueryString["article"];

            if (article != null)
            {
                if (price_name != null)
                {

                    SqlConnection con = new SqlConnection(str);
                    string sql = "SELECT id, article, ROUND([price]*(SELECT course FROM Course_USD WHERE id = 1),2) AS [price] FROM " + price_name + " WHERE article=" + article + ";";
                    SqlDataAdapter da = new SqlDataAdapter(sql, con);
                    DataSet ds = new DataSet();
                    da.Fill(ds, price_name);
                    DataRow dr;
                    dr = ds.Tables[price_name].Rows[0];

                    //Заполняем стоимость товара:
                    lblprice.Text = dr["price"].ToString();
                }
                else {Response.Redirect("Error.aspx");}

            }
            else {Response.Redirect("Error.aspx"); }
        }
        private void ReadOrderData(string filterPrimkey, string connectionString, int rowIndex)
        {
            var queryString =
              "SELECT numcode, charcode, nominal, name, value FROM dbo.values_history inner join dbo.description on  dbo.description.id = dbo.values_history.id WHERE dbo.values_history.primkey ='" + filterPrimkey + "' ;";

            try
            {
                using (var connection =
                      new SqlConnection(connectionString))
                {
                    var command =
                        new SqlCommand(queryString, connection);
                    connection.Open();

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        WriteCurrency(reader, rowIndex);
                    }
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                Log.Text = ex.Message;
            }
        }
        public static DataTable Sehirler()
        {
            try
            {
                using (baglan = new SqlConnection(ConnectionString))
                {
                    baglan.Open();
                    using (komutver = new SqlCommand())
                    {
                        komutver.Connection = baglan;
                        komutver.CommandText = "sehir_Listele";
                        komutver.CommandType = CommandType.StoredProcedure;
                        adp = new SqlDataAdapter(komutver);
                        dt = new DataTable();
                        adp.Fill(dt);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return dt;
        }
示例#29
1
 public List<Model.Beneficios> Select()
 {
     List<Model.Beneficios> lstBeneficios = new List<Model.Beneficios>();
     SqlConnection conexao = new SqlConnection(strCon);
     string sql = "Select * from Beneficios";
     SqlCommand cmd = new SqlCommand(sql, conexao);
     conexao.Open();
     try
     {
         SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
         while (reader.Read())
         {
             Model.Beneficios beneficios = new Model.Beneficios();
             beneficios.id = Convert.ToInt32(reader["id"].ToString());
             beneficios.descr = Convert.ToString(reader["descr"].ToString());
             lstBeneficios.Add(beneficios);
         }
     }
     catch
     {
         Console.WriteLine("Deu erro na Seleção de Beneficios...");
     }
     finally
     {
         conexao.Close();
     }
     return lstBeneficios;
 }
示例#30
0
        /// <summary>
        /// Delete values from Item by primary key(s).
        /// </summary>
        /// <param name="sqlConnection">Sql connection or null.</param>
        /// <param name="sqlTransaction">Sql transaction or null.</param>
        /// <param name="connectionKeyName">Connection key name located in config file.</param>
        /// <param name="itemID"></param>
        /// <returns>true if successful otherwise false.</returns>
        public bool ItemDeleteAuto(
            SqlConnection sqlConnection,
            SqlTransaction sqlTransaction,
            string connectionKeyName,
            int itemID)
        {
            SqlConnection connection = CustomSqlHelper.CreateConnection(CustomSqlHelper.GetConnectionStringFromConnectionStrings(connectionKeyName), sqlConnection);
            SqlTransaction transaction = sqlTransaction;

            using (SqlCommand command = CustomSqlHelper.CreateCommand("ItemDeleteAuto", connection, transaction,
                CustomSqlHelper.CreateInputParameter("ItemID", SqlDbType.Int, null, false, itemID),
                    CustomSqlHelper.CreateReturnValueParameter("ReturnCode", SqlDbType.Int, null, false)))
            {
                int returnCode = CustomSqlHelper.ExecuteNonQuery(command, "ReturnCode");

                if (transaction == null)
                {
                    CustomSqlHelper.CloseConnection(connection);
                }

                if (returnCode == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
 private static System.Data.SqlClient.SqlCommand getCmd(string query)
 {
     con = new System.Data.SqlClient.SqlConnection(constr);
     con.Open();
     return(new System.Data.SqlClient.SqlCommand(query, con));
 }
示例#32
0
        /// <summary>
        /// Inserts default values into a field on a form. This is based on the standard DMB form design where
        /// controls will be held within a control panel (name controlPanel) within the form. The routine should
        /// not be used for any application which does not conform to this standard.
        /// </summary>
        /// <param name="passedForm">The name of the form on which the controls are held</param>
        /// <param name="originatingControlName">The name of the control within the form</param>
        /// <param name="connectionType">The type of data source connection</param>
        /// <param name="originatingValue">The value to be checked for whether a default applies</param>
        /// <param name="connectionString">The connection string</param>
        public void insertDefaults(ref System.Windows.Forms.Form passedForm, string originatingControlName, string connectionType, string originatingValue, string connectionString)
        {
            DataSet       defaultsDataset = new DataSet();
            DataConnector myHandler       = new DataConnector();
            string        SQLQuery        = "SELECT DefaultValues.OriginatingForm, DefaultValues.OriginatingField, DefaultValues.OriginatingValue, DefaultValues.AffectedField, DefaultValues.DefaultValue FROM DefaultValues WHERE (((DefaultValues.OriginatingForm)='" + passedForm.Name.ToString() + "') AND ((DefaultValues.OriginatingField)='" + originatingControlName + "') AND ((DefaultValues.OriginatingValue)='" + originatingValue + "'));";

            switch (connectionType)
            {
            case "SQL":
                System.Data.SqlClient.SqlConnection SQLConnection = new System.Data.SqlClient.SqlConnection(connectionString);
                defaultsDataset = myHandler.getDataSetViaSQL(SQLQuery, "defaults", SQLConnection);
                break;

            case "ADO":
                System.Data.OleDb.OleDbConnection ADOConnection = new System.Data.OleDb.OleDbConnection(connectionString);
                defaultsDataset = myHandler.getDataSetViaSQL(SQLQuery, "defaults", ADOConnection);
                break;

            default:
                throw new Exception("DMBT-GT03 - The connection type cannot be identified.");
            }
            DataTable defaultsTable = defaultsDataset.Tables["defaults"];

            if (defaultsTable.Rows.Count != 0)
            {
                foreach (DataRow myRow in defaultsTable.Rows)
                {
                    //identify the target field type and then activate a switch statement to insert the relevant
                    //info
                    switch (passedForm.Controls["controlPanel"].Controls[myRow["AffectedField"].ToString()].GetType().ToString())
                    {
                    case "System.Windows.Forms.ListBox":
                        System.Windows.Forms.ListBox myListBox = new System.Windows.Forms.ListBox();
                        myListBox = passedForm.Controls["controlPanel"].Controls[myRow["AffectedField"].ToString()] as ListBox;
                        //myListBox.SelectedItem = myRow["DefaultValue"].ToString(); //#####REMOVED 17/09/2015
                        myListBox.Text = myRow["DefaultValue"].ToString();   //#####ADDED 17/09/2015
                        //insertDefault(ref myListBox, myRow["DefaultValue"].ToString());
                        break;

                    case "System.Windows.Forms.ComboBox":
                        System.Windows.Forms.ComboBox myCombo = new System.Windows.Forms.ComboBox();
                        myCombo = passedForm.Controls["controlPanel"].Controls[myRow["AffectedField"].ToString()] as ComboBox;
                        //myCombo.SelectedItem = myRow["DefaultValue"].ToString();//#####REMOVED 17/09/2015
                        myCombo.Text = myRow["DefaultValue"].ToString();    //#####ADDED 17/09/2015
                        //insertDefault(ref myCombo, myRow["DefaultValue"].ToString());
                        break;

                    case "System.Windows.Forms.TextBox":
                        System.Windows.Forms.TextBox myTextBox = new System.Windows.Forms.TextBox();
                        myTextBox      = passedForm.Controls["controlPanel"].Controls[myRow["AffectedField"].ToString()] as TextBox;
                        myTextBox.Text = myRow["DefaultValue"].ToString();
                        //insertDefault(ref myTextBox, myRow["DefaultValue"].ToString());
                        break;

                    default:
                        MessageBox.Show("DMBT-GT04 - The system cannot determine the default values for this selection. Please notify your line manager.");
                        break;
                    }
                }
            }
        }
示例#33
0
        public List <TournamentModel> GetTournament_All()
        {
            List <TournamentModel> output;

            using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.ConnectionString(db)))
            {
                output = connection.Query <TournamentModel>("dbo.spTournaments_GetAll").ToList();
                var p = new DynamicParameters();

                foreach (TournamentModel t in output)
                {
                    //Populate Prizes
                    p = new DynamicParameters();
                    p.Add("@TournamentId", t.Id);
                    t.Prizes = connection.Query <PrizeModel>("dbo.spPrizes_GetByTournament", p, commandType: CommandType.StoredProcedure).ToList();

                    //Populate Teams
                    t.EnteredTeams = connection.Query <TeamModel>("dbo.spTeam_GetByTournament", p, commandType: CommandType.StoredProcedure).ToList();

                    foreach (TeamModel team in t.EnteredTeams)
                    {
                        p = new DynamicParameters();
                        p.Add("@TeamId", team.Id);
                        team.TeamMembers = connection.Query <PersonModel>("spTeamMembers_GetByTeam", p, commandType: CommandType.StoredProcedure).ToList();
                    }

                    //Populate Rounds
                    p = new DynamicParameters();
                    p.Add("@TournamentId", t.Id);
                    List <MatchupModel> matchups = connection.Query <MatchupModel>("dbo.spMatchups_GetByTournament", p, commandType: CommandType.StoredProcedure).ToList();

                    foreach (MatchupModel m in matchups)
                    {
                        p = new DynamicParameters();
                        p.Add("@MatchupId", m.Id);

                        //Populate Rounds
                        m.Entries = connection.Query <MatchupEntryModel>("dbo.spMatchupEntries_GetByMatchup", p, commandType: CommandType.StoredProcedure).ToList();

                        //Populate each entry (2 models)
                        //Populate each matchup (1 model)

                        List <TeamModel> allTeams = GetTeam_All();

                        if (m.WinnerId > 0)
                        {
                            m.Winner = allTeams.Where(x => x.Id == m.WinnerId).First();
                        }

                        foreach (var me in m.Entries)
                        {
                            if (me.TeamCompetingId > 0)
                            {
                                me.TeamCompeting = allTeams.Where(x => x.Id == me.TeamCompetingId).First();
                            }

                            if (me.ParentMatchupId > 0)
                            {
                                me.ParentMatchup = matchups.Where(x => x.Id == me.ParentMatchupId).First();
                            }
                        }
                    }

                    //List<List<MatchupModel>>
                    List <MatchupModel> currRow = new List <MatchupModel>();
                    int currRound = 1;

                    foreach (MatchupModel m in matchups)
                    {
                        if (m.MatchupRound > currRound)
                        {
                            t.Rounds.Add(currRow);
                            currRow    = new List <MatchupModel>();
                            currRound += 1;
                        }

                        currRow.Add(m);
                    }
                    t.Rounds.Add(currRow);
                }
            }

            return(output);
        }
示例#34
0
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(clsRPlus.sCN_SALES))
        {
            try
            {
                if (e.CommandName.Equals("New"))
                {
                    LinkButton  btnNew = e.CommandSource as LinkButton;
                    GridViewRow row    = btnNew.NamingContainer as GridViewRow;
                    System.Data.SqlClient.SqlDataReader reader = null;
                    System.Data.SqlClient.SqlCommand    cmd    = new System.Data.SqlClient.SqlCommand();
                    if (row == null)
                    {
                        return;
                    }
                    TextBox      txtItemCode        = GridView1.FooterRow.FindControl("ItemCodeTextBoxNew") as TextBox;
                    TextBox      txtDate            = GridView1.FooterRow.FindControl("transactiondateTextBoxNew") as TextBox;
                    DropDownList txtTransactionType = GridView1.FooterRow.FindControl("TypeTextBoxEmpty") as DropDownList;
                    TextBox      txtValue           = GridView1.FooterRow.FindControl("valueTextBoxNew") as TextBox;
                    String       query = "INSERT INTO [SkupFutureEntrys] ( [ItemCode], [transactiondate], [Type], [value]) VALUES (@ItemCode, @transactiondate, @Type, @value)";

                    cmd.CommandText = query;
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.Connection  = conn;

                    cmd.Parameters.AddWithValue("ItemCode", txtItemCode.Text);
                    cmd.Parameters.AddWithValue("transactiondate", txtDate.Text);
                    cmd.Parameters.AddWithValue("Type", txtTransactionType.Text);
                    cmd.Parameters.AddWithValue("value", txtValue.Text);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    cmd.Cancel();
                    cmd.Dispose();
                    conn.Close();
                    Response.AppendHeader("Refresh", "0,URL=");
                }
                if (e.CommandName.Equals("EmptyNew"))
                {
                    LinkButton  btnNew = e.CommandSource as LinkButton;
                    GridViewRow row    = btnNew.NamingContainer as GridViewRow;
                    System.Data.SqlClient.SqlDataReader reader = null;
                    System.Data.SqlClient.SqlCommand    cmd    = new System.Data.SqlClient.SqlCommand();
                    if (row == null)
                    {
                        return;
                    }
                    TextBox      txt                = GridView1.Controls[0].Controls[0].FindControl("ItemCodeTextBoxEmpty") as TextBox;
                    TextBox      txtItemCode        = GridView1.Controls[0].Controls[0].FindControl("ItemCodeTextBoxEmpty") as TextBox;
                    TextBox      txttransactiondate = GridView1.Controls[0].Controls[0].FindControl("transactiondateTextBoxEmpty") as TextBox;
                    DropDownList txtTransactionType = GridView1.Controls[0].Controls[0].FindControl("TypeTextBoxEmpty") as DropDownList;
                    TextBox      txtValue           = GridView1.Controls[0].Controls[0].FindControl("valueTextBoxEmpty") as TextBox;
                    String       query              = "INSERT INTO [SkupFutureEntrys] ( [ItemCode], [transactiondate], [Type], [value]) VALUES (@ItemCode, @transactiondate, @Type, @value)";

                    cmd.CommandText = query;
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.Connection  = conn;

                    cmd.Parameters.AddWithValue("ItemCode", txtItemCode.Text);
                    cmd.Parameters.AddWithValue("transactiondate", txttransactiondate.Text);
                    cmd.Parameters.AddWithValue("Type", txtTransactionType.Text);
                    cmd.Parameters.AddWithValue("value", txtValue.Text);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    cmd.Cancel();
                    cmd.Dispose();
                    conn.Close();
                    Response.AppendHeader("Refresh", "0,URL=");
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                conn.Close();
            }
        }
    }
示例#35
0
        public Esito AggiornaUtente(Utenti newUtente)
        {
            Anag_Utenti utente = ((Anag_Utenti)HttpContext.Current.Session[SessionManager.UTENTE]);
            Esito       esito  = new Esito();

            try
            {
                using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(sqlConstr))
                {
                    using (System.Data.SqlClient.SqlCommand StoreProc = new System.Data.SqlClient.SqlCommand("UpdateUtente"))
                    {
                        using (System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter())
                        {
                            StoreProc.Connection  = con;
                            sda.SelectCommand     = StoreProc;
                            StoreProc.CommandType = CommandType.StoredProcedure;

                            // PARAMETRI PER LOG UTENTE
                            System.Data.SqlClient.SqlParameter idUtente = new SqlParameter("@idUtente", utente.id);
                            idUtente.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(idUtente);

                            System.Data.SqlClient.SqlParameter nomeUtente = new SqlParameter("@nomeUtente", utente.username);
                            nomeUtente.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nomeUtente);
                            // FINE PARAMETRI PER LOG UTENTE

                            System.Data.SqlClient.SqlParameter id = new System.Data.SqlClient.SqlParameter("@id", newUtente.Id);
                            id.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id);

                            SqlParameter cognome = new SqlParameter("@cognome", newUtente.Cognome);
                            cognome.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(cognome);

                            SqlParameter nome = new SqlParameter("@nome", newUtente.Nome);
                            nome.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome);

                            SqlParameter descrizione = new SqlParameter("@descrizione", newUtente.Descrizione);
                            descrizione.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(descrizione);

                            SqlParameter username = new SqlParameter("@username", newUtente.Username);
                            username.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(username);

                            SqlParameter password = new SqlParameter("@password", newUtente.Password);
                            password.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(password);

                            SqlParameter id_tipoUtente = new SqlParameter("@id_tipoUtente", newUtente.Id_tipoUtente);
                            id_tipoUtente.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_tipoUtente);

                            SqlParameter email = new SqlParameter("@email", newUtente.Email);
                            email.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(email);

                            SqlParameter attivo = new SqlParameter("@attivo", newUtente.Attivo);
                            attivo.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(attivo);

                            StoreProc.Connection.Open();

                            int iReturn = StoreProc.ExecuteNonQuery();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                esito.Codice      = Esito.ESITO_KO_ERRORE_SCRITTURA_TABELLA;
                esito.Descrizione = "Anag_Utenti_DAL.cs - AggiornaUtente " + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace;
            }

            return(esito);
        }
示例#36
0
        //------------------------------------------------------------------------------------------
        #region Construction/Destruction

        /// <summary>
        /// Skapar ett databaskopplingsobjekt.
        /// </summary>
        /// <param name="connectionString">Kopplingssträng till databasen.</param>
        internal EasyBaseSqlConnection(string connectionString)
        {
            _connectionString = connectionString;
            _connection       = null;
            _transaction      = null;
        }
示例#37
0
    protected void ListViewMediaComment_ItemCreated(object sender, ListViewItemEventArgs e)
    {
        try
        {
            ListView lv = (ListView)sender;
            postId2c = (Guid)lv.DataKeys[e.Item.DataItemIndex].Values[0];
            likeId2c = lv.DataKeys[e.Item.DataItemIndex].Values[1].ToString();
            userId2c = lv.DataKeys[e.Item.DataItemIndex].Values[2].ToString();

            Button lb = e.Item.FindControl("LinkButtonLike") as Button;

            System.Data.SqlClient.SqlDataReader rdr    = null;
            System.Data.SqlClient.SqlConnection conn   = null;
            System.Data.SqlClient.SqlCommand    sqlcmd = null;

            try
            {
                string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["SecurityConnectionString"].ConnectionString;
                conn = new System.Data.SqlClient.SqlConnection(connectionString);

                sqlcmd = new System.Data.SqlClient.SqlCommand("select * from [UserLikes]", conn);
                conn.Open();

                rdr = sqlcmd.ExecuteReader();


                while (rdr.Read())
                {
                    String uid = rdr["UserId"].ToString();
                    String lid = rdr["LikeId"].ToString();
                    if (userId2c == uid && likeId2c == lid)
                    {
                        lb.Text = "Unlike";
                        break;
                    }
                    else
                    {
                        lb.Text = "Like";
                    }
                }
                if (rdr != null)
                {
                    rdr.Close();
                }
            }
            catch (Exception ex)
            {
            }

            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }

            string connectionString2 = ConfigurationManager.ConnectionStrings["SecurityConnectionString"].ConnectionString;
            //string selectSql = "SELECT * FROM UserLikes WHERE UserId = @UserId";
            string selectSql = "select COUNT(*) from [UserLikes] WHERE LikeId=@LikeId";

            using (SqlConnection myConnection = new SqlConnection(connectionString2))
            {
                myConnection.Open();
                SqlCommand myCommand = new SqlCommand(selectSql, myConnection);
                myCommand.Parameters.AddWithValue("@LikeId", likeId2c);


                Int32 count = (Int32)myCommand.ExecuteScalar();


                HyperLink lbcount = e.Item.FindControl("LikeCountLabel") as HyperLink;
                lbcount.Text = count.ToString() + " people like this.";

                myConnection.Close();
            }
        }
        catch { }
    }
示例#38
0
        //返回系统设置信息
        private void LoadSysSetupInfo()
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
            conn.ConnectionString = rms_var.ConnStr;
            try
            {
                SqlCommand     selectCMD = new SqlCommand();
                SqlDataAdapter dbDA      = new SqlDataAdapter();
                DataSet        dbDS      = new DataSet();
                selectCMD.Connection     = conn;
                selectCMD.CommandTimeout = 30;
                conn.Open();

                //companyname
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='companyname'";
                dbDA.SelectCommand    = selectCMD;

                dbDA.Fill(dbDS, "t");
                TextBox1.Text = dbDS.Tables[0].Rows[0]["value"].ToString();

                TextBox1.Text = rms_var.ReadStrfromReg("RestaurantName", "");

                //address
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='address'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                TextBox2.Text = dbDS.Tables[0].Rows[0]["value"].ToString();

                //telphone
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='telphone'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                TextBox3.Text = dbDS.Tables[0].Rows[0]["value"].ToString();

                //email
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='email'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                TextBox4.Text = dbDS.Tables[0].Rows[0]["value"].ToString();

                //webpage
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='webpage'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                TextBox5.Text = dbDS.Tables[0].Rows[0]["value"].ToString();

                //autobalancebill 前台单据号自动生成
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='autobalancebill'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                CheckBox1.Checked = dbDS.Tables[0].Rows[0]["value"].ToString() == "1"?true:false;

                //autostorebill 库存单据号自动生成
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='autostorebill'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                CheckBox2.Checked = dbDS.Tables[0].Rows[0]["value"].ToString() == "1" ? true : false;

                //showlastprice 入库直拨的单价从商品库中读最新进价
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='showlastprice'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                CheckBox3.Checked = dbDS.Tables[0].Rows[0]["value"].ToString() == "1" ? true : false;

                //foodcodelenth 菜例代码长度
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='foodcodelenth'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                NumericUpDown1.Text = dbDS.Tables[0].Rows[0]["value"].ToString();

                //YMatCodeLen 原料物品代码长度
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='YMatCodeLen'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                NumericUpDown2.Text = dbDS.Tables[0].Rows[0]["value"].ToString();

                //WMatCodeLen 物料物品代码长度
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='WMatCodeLen'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                NumericUpDown3.Text = dbDS.Tables[0].Rows[0]["value"].ToString();

                //autotmpcost 结账 自动抹零 四舍五入
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='autotmpcost'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                ComboBox1.SelectedIndex = int.Parse(dbDS.Tables[0].Rows[0]["value"].ToString());

                //lowerpay 当客户消费低于最低最低消费用最低消费结账
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='lowerpay'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                CheckBox4.Checked = dbDS.Tables[0].Rows[0]["value"].ToString() == "1" ? true : false;

                //clubfixedderate 会员卡固定折扣
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='clubfixedderate'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                if (Convert.ToInt32(dbDS.Tables[0].Rows[0]["value"]) == 1)
                {
                    RadioButton2.Checked = true;
                }
                else
                {
                    RadioButton1.Checked = true;
                }

                //SignFullBalance 签单金额累计超过限额,是否允许签单结账
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='SignFullBalance'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                CheckBox8.Checked = dbDS.Tables[0].Rows[0]["value"].ToString() == "1" ? true : false;

                //DiscountOnDiscount 允许优惠菜品特价菜品折上折
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='DiscountOnDiscount'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                CheckBox9.Checked = dbDS.Tables[0].Rows[0]["value"].ToString() == "1" ? true : false;

                //foodcodecost 菜例成本卡计算方法
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='foodcodecost'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                if (Convert.ToInt32(dbDS.Tables[0].Rows[0]["value"]) == 1)
                {
                    RadioButton3.Checked = true;
                }
                else if (Convert.ToInt32(dbDS.Tables[0].Rows[0]["value"]) == 2)
                {
                    RadioButton4.Checked = true;
                }
                else if (Convert.ToInt32(dbDS.Tables[0].Rows[0]["value"]) == 3)
                {
                    RadioButton5.Checked = true;
                }

                //autoPrintFood 自动打印传菜单
                selectCMD.CommandText = "SELECT parametercode,value FROM syssetup where parametercode='autoPrintFood'";
                dbDA.SelectCommand    = selectCMD;
                dbDS.Clear();
                dbDA.Fill(dbDS, "t");
                CheckBox7.Checked = dbDS.Tables[0].Rows[0]["value"].ToString() == "1" ? true : false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
示例#39
0
        public static bool GetLocalDB(string dbName, bool deleteIfExists = false)
        {
            try
            {
                string outputFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), DB_DIRECTORY);
                string mdfFilename  = dbName + ".mdf";
                string dbFileName   = Path.Combine(outputFolder, mdfFilename);
                string logFileName  = Path.Combine(outputFolder, String.Format("{0}_log.ldf", dbName));

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

                bool mustCreateTables = false;

                if (File.Exists(dbFileName) && deleteIfExists)
                {
                    if (File.Exists(logFileName))
                    {
                        File.Delete(logFileName);
                    }
                    File.Delete(dbFileName);
                    CreateDatabase(dbName, dbFileName);
                    mustCreateTables = true;
                }
                else if (!File.Exists(dbFileName))
                {
                    CreateDatabase(dbName, dbFileName);
                    mustCreateTables = true;
                }

                string        connectionString = String.Format(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDBFileName={1};Initial Catalog={0};Integrated Security=True;", dbName, dbFileName);
                SqlConnection connection       = new SqlConnection(connectionString);
                connection.Open();

                if (mustCreateTables)
                {
                    using (connection)
                    {
                        SqlCommand cmd = connection.CreateCommand();

                        string sql =
                            @"
                            CREATE TABLE [dbo].[Client]
                            (
	                            [IDX] INT NOT NULL PRIMARY KEY IDENTITY(1,1), 
                                [Name] VARCHAR(50) NOT NULL, 
                                [Surname] VARCHAR(50) NOT NULL, 
                                [Gender] TINYINT NOT NULL, 
                                [Age] INT NOT NULL
                            );

                            CREATE TABLE [dbo].[ContactType]
                            (
	                            [IDX] INT NOT NULL PRIMARY KEY IDENTITY(1,1), 
                                [Type] TINYINT NOT NULL, 
                                [Description] VARCHAR(50) NOT NULL
                            );

                            CREATE UNIQUE INDEX [IX_ContactType_Type_Description] ON [dbo].[ContactType] ([Type], [Description]);

                            CREATE TABLE [dbo].[ClientContact]
                            (
	                            [IDX] INT NOT NULL PRIMARY KEY IDENTITY(1,1), 
                                [ClientIDX] INT NOT NULL, 
                                [ContactTypeIDX] INT NOT NULL, 
                                [Contact] VARCHAR(200) NULL, 
                                CONSTRAINT [FK_ClientContact_ClientIDX] FOREIGN KEY ([ClientIDX]) REFERENCES [Client]([IDX]),
                                CONSTRAINT [FK_ClientContact_ContactTypeIDX] FOREIGN KEY ([ContactTypeIDX]) REFERENCES [ContactType]([IDX])
                            );

                            CREATE UNIQUE INDEX [IX_Table_ClientIDX_ContactTypeIDX] ON [dbo].[ClientContact] ([ClientIDX], [ContactTypeIDX]);

                            INSERT INTO [dbo].[ContactType] ([Type], [Description]) VALUES ('0', 'Home Phone');
                            INSERT INTO [dbo].[ContactType] ([Type], [Description]) VALUES ('0', 'Work Phone');
                            INSERT INTO [dbo].[ContactType] ([Type], [Description]) VALUES ('0', 'Cell Number');
                            INSERT INTO [dbo].[ContactType] ([Type], [Description]) VALUES ('1', 'Home Address');
                            INSERT INTO [dbo].[ContactType] ([Type], [Description]) VALUES ('1', 'Work Address');
                            ";

                        cmd.CommandText = sql;
                        cmd.ExecuteNonQuery();

                        /*
                         * for (int i = 0; i < 100000; i++)
                         * {
                         *  sql = "INSERT INTO [dbo].[Client] ([Name], [Surname], [Gender], [Age]) VALUES ('" + i.ToString() + "', '" + i.ToString() + "', '0', '" + i.ToString() + "');";
                         *  cmd.CommandText = sql;
                         *  cmd.ExecuteNonQuery();
                         * }
                         */
                    }

                    ReInitDB(dbName, deleteIfExists);
                }
                else
                {
                    con = connection;
                }

                return(mustCreateTables);
            }
            catch
            {
                throw;
            }
        }
示例#40
0
 public CustomerSQLDB(DBConnection cn) : base(cn)
 {
 }
示例#41
0
        //保存系统设置信息
        private void SaveSysSetupInfo()
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
            conn.ConnectionString = rms_var.ConnStr;
            try
            {
                SqlCommand selectCMD = new SqlCommand();
                //Dim dbDA As SqlDataAdapter = New SqlDataAdapter
                //Dim dbDS As DataSet = New DataSet
                selectCMD.Connection     = conn;
                selectCMD.CommandTimeout = 30;
                conn.Open();

                //CompanyName
                selectCMD.CommandText = "update syssetup set value='" + TextBox1.Text + "' " + "where parametercode='companyname'";

                selectCMD.ExecuteNonQuery();

                if (CheckBox6.Checked)                 //同时保存到注册表里
                {
                    rms_var.WriteStrToReg("RestaurantName", TextBox1.Text);
                }

                //address
                selectCMD.CommandText = "update syssetup set value='" + TextBox2.Text + "' " + "where parametercode='address'";

                selectCMD.ExecuteNonQuery();

                //telphone
                selectCMD.CommandText = "update syssetup set value='" + TextBox3.Text + "' " + "where parametercode='telphone'";

                selectCMD.ExecuteNonQuery();

                //email
                selectCMD.CommandText = "update syssetup set value='" + TextBox4.Text + "' " + "where parametercode='email'";

                selectCMD.ExecuteNonQuery();

                //webpage
                selectCMD.CommandText = "update syssetup set value='" + TextBox5.Text + "' " + "where parametercode='webpage'";

                selectCMD.ExecuteNonQuery();

                //autobalancebill 前台单据号自动生成
                selectCMD.CommandText = "update syssetup set value='" + Math.Abs(System.Convert.ToInt32(CheckBox1.Checked)).ToString() + "' " + "where parametercode='autobalancebill'";

                selectCMD.ExecuteNonQuery();

                //autostorebill 库存单据号自动生成
                selectCMD.CommandText = "update syssetup set value='" + Math.Abs(System.Convert.ToInt32(CheckBox2.Checked)).ToString() + "' " + "where parametercode='autostorebill'";

                selectCMD.ExecuteNonQuery();

                //showlastprice 入库直拨的单价从商品库中读最新进价
                selectCMD.CommandText = "update syssetup set value='" + Math.Abs(System.Convert.ToInt32(CheckBox3.Checked)).ToString() + "' " + "where parametercode='showlastprice'";

                selectCMD.ExecuteNonQuery();

                //foodcodelenth 菜例代码长度
                selectCMD.CommandText = "update syssetup set value='" + NumericUpDown1.Text + "' " + "where parametercode='foodcodelenth'";

                selectCMD.ExecuteNonQuery();

                //YMatCodeLen 原料物品代码长度
                selectCMD.CommandText = "update syssetup set value='" + NumericUpDown2.Text + "' " + "where parametercode='YMatCodeLen'";

                selectCMD.ExecuteNonQuery();

                //WMatCodeLen 物料物品代码长度
                selectCMD.CommandText = "update syssetup set value='" + NumericUpDown3.Text + "' " + "where parametercode='WMatCodeLen'";

                selectCMD.ExecuteNonQuery();

                //autotmpcost 结账自动抹零
                selectCMD.CommandText = "update syssetup set value='" + ComboBox1.SelectedIndex.ToString() + "' " + "where parametercode='autotmpcost'";

                selectCMD.ExecuteNonQuery();

                //lowerpay 当客户消费低于最低最低消费用最低消费结账
                selectCMD.CommandText = "update syssetup set value='" + Math.Abs(System.Convert.ToInt32(CheckBox4.Checked)).ToString() + "' " + "where parametercode='lowerpay'";

                selectCMD.ExecuteNonQuery();

                //clubfixedderate 会员卡固定折扣
                selectCMD.CommandText = "update syssetup set value='" + Math.Abs(System.Convert.ToInt32(RadioButton2.Checked)).ToString() + "' " + "where parametercode='clubfixedderate'";

                selectCMD.ExecuteNonQuery();

                //SignFullBalance 签单金额累计超过限额,是否允许签单结账
                selectCMD.CommandText = "update syssetup set value='" + Math.Abs(System.Convert.ToInt32(CheckBox8.Checked)).ToString() + "' " + "where parametercode='SignFullBalance'";

                selectCMD.ExecuteNonQuery();

                //DiscountOnDiscount 允许优惠菜品特价菜品折上折
                selectCMD.CommandText = "update syssetup set value='" + Math.Abs(System.Convert.ToInt32(CheckBox9.Checked)).ToString() + "' " + "where parametercode='DiscountOnDiscount'";

                selectCMD.ExecuteNonQuery();

                //foodcodecost 菜例成本卡计算方法
                if (RadioButton3.Checked)
                {
                    selectCMD.CommandText = "update syssetup set value='1' " + "where parametercode='foodcodecost'";

                    selectCMD.ExecuteNonQuery();
                }
                else if (RadioButton4.Checked)
                {
                    selectCMD.CommandText = "update syssetup set value='2' " + "where parametercode='foodcodecost'";

                    selectCMD.ExecuteNonQuery();
                }
                else if (RadioButton5.Checked)
                {
                    selectCMD.CommandText = "update syssetup set value='3' " + "where parametercode='foodcodecost'";

                    selectCMD.ExecuteNonQuery();
                }

                //autoPrintFood 自动打印传菜单
                selectCMD.CommandText = "update syssetup set value='" + Math.Abs(System.Convert.ToInt32(CheckBox7.Checked)).ToString() + "' " + "where parametercode='autoPrintFood'";

                selectCMD.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
示例#42
0
        /// <summary>
        /// Функция получения данных для MSSQL, Postgre, SQLite. Результат в DataSet. Возвращает несколько таблиц.
        /// </summary>
        /// <param name="sql">Запрос любой, select, update, delete, ddl</param>
        /// <param name="ds">DataSet - набор таблиц</param>
        /// <param name="errorMes">Сообщение об ошибке</param>
        /// <param name="errorShow">Показывать или нет ошибки</param>
        /// <returns>Если успешно, то true</returns>
        public bool SelectDS(string sql, out DataSet ds, out string errorMes, bool errorShow)
        {
            ds       = new DataSet("DS");
            errorMes = "";
            if ((sys.IsEmpty(sql)) || (sql == "Empty"))
            {
                return(false);
            }
            try
            {
                if (ConnectionDirect)
                {
                    if (serverType == ServerType.Postgre)
                    {
                        Npgsql.NpgsqlConnection connection = null; //Postgres
                        connection = new Npgsql.NpgsqlConnection(ConnectStringSQLite);
                        connection.Open();
                        var da = new NpgsqlDataAdapter(sql, connection);
                        da.Fill(ds);
                        connection.Close();
                    }

                    if (serverType == ServerType.MSSQL)
                    {
                        var connection = new System.Data.SqlClient.SqlConnection(ConnectStringMSSQL);
                        connection.Open();
                        var da = new SqlDataAdapter(sql, connection);
                        da.Fill(ds);
                        connection.Close();
                    }
                }

                if (serverType == ServerType.SQLite)
                {
                    var connection = new System.Data.SQLite.SQLiteConnection(ConnectStringSQLite);
                    connection.Open();
                    var da = new SQLiteDataAdapter(sql, connection);
                    da.Fill(ds);
                    connection.Close();
                    //connection.BindFunction(CloseToSQLiteFunction.GetAttribute(), new CloseToSQLiteFunction());
                }

                if (!ConnectionDirect)
                {
                    if (!AppSelectDS(sql, out ds))
                    {
                        return(false);
                    }
                }

                LastQueryDateTime = DateTime.Now;
                return(true);
            }
            catch (Exception e)
            {
                errorMes = "703. Ошибка выполнения запроса: " + errorMes + Var.CR + e.Message + Var.CR + sql;
                if (errorShow)
                {
                    sys.SM(errorMes);
                }
                ds = null;
                return(false);
            }
        }
示例#43
0
    public string[] verifyReader(string query, string ColumnNumber1, string ColumnNumber2 = "0", string ColumnNumber3 = "0", string ColumnNumber4 = "0", string ColumnNumber5 = "0", string ColumnNumber6 = "0", string ColumnNumber7 = "0", string ColumnNumber8 = "0", string ColumnNumber9 = "0", string ColumnNumber10 = "0", string ColumnNumber11 = "0", string ColumnNumber12 = "0", string ColumnNumber13 = "0", string ColumnNumber14 = "0", string ColumnNumber15 = "0", string ColumnNumber16 = "0", string ColumnNumber17 = "0", string ColumnNumber18 = "0", string ColumnNumber19 = "0", string ColumnNumber20 = "0", string ColumnNumber21 = "0", string ColumnNumber22 = "0", string ColumnNumber23 = "0", string ColumnNumber24 = "0", string ColumnNumber25 = "0", string ColumnNumber26 = "0", string ColumnNumber27 = "0", string ColumnNumber28 = "0", string ColumnNumber29 = "0", string ColumnNumber30 = "0", string ColumnNumber31 = "0", string ColumnNumber32 = "0", string ColumnNumber33 = "0", string ColumnNumber34 = "0", string ColumnNumber35 = "0", string ColumnNumber36 = "0", string ColumnNumber37 = "0", string ColumnNumber38 = "0", string ColumnNumber39 = "0", string ColumnNumber40 = "0", string ColumnNumber41 = "0", string ColumnNumber42 = "0", string ColumnNumber43 = "0", string ColumnNumber44 = "0", string ColumnNumber45 = "0", string ColumnNumber46 = "0", string ColumnNumber47 = "0", string ColumnNumber48 = "0", string ColumnNumber49 = "0", string ColumnNumber50 = "0", string ColumnNumber51 = "0", string ColumnNumber52 = "0", string ColumnNumber53 = "0", string ColumnNumber54 = "0", string ColumnNumber55 = "0", string ColumnNumber56 = "0", string ColumnNumber57 = "0", string ColumnNumber58 = "0", string ColumnNumber59 = "0", string ColumnNumber60 = "0", string ColumnNumber61 = "0", string ColumnNumber62 = "0", string ColumnNumber63 = "0", string ColumnNumber64 = "0", string ColumnNumber65 = "0", string ColumnNumber66 = "0", string ColumnNumber67 = "0", string ColumnNumber68 = "0", string ColumnNumber69 = "0", string ColumnNumber70 = "0", string ColumnNumber71 = "0", string ColumnNumber72 = "0", string ColumnNumber73 = "0", string ColumnNumber74 = "0", string ColumnNumber75 = "0", string ColumnNumber76 = "0", string ColumnNumber77 = "0", string ColumnNumber78 = "0", string ColumnNumber79 = "0", string ColumnNumber80 = "0", string ColumnNumber81 = "0", string ColumnNumber82 = "0", string ColumnNumber83 = "0", string ColumnNumber84 = "0", string ColumnNumber85 = "0", string ColumnNumber86 = "0", string ColumnNumber87 = "0", string ColumnNumber88 = "0", string ColumnNumber89 = "0", string ColumnNumber90 = "0", string ColumnNumber91 = "0", string ColumnNumber92 = "0", string ColumnNumber93 = "0", string ColumnNumber94 = "0", string ColumnNumber95 = "0", string ColumnNumber96 = "0", string ColumnNumber97 = "0", string ColumnNumber98 = "0", string ColumnNumber99 = "0", string ColumnNumber100 = "0")
    {
        int i = 0;

        string[] x           = new string[100];
        string[] ColumnArray = new string[100];

        ColumnArray[0] = ColumnNumber1; ColumnArray[1] = ColumnNumber2; ColumnArray[2] = ColumnNumber3; ColumnArray[3] = ColumnNumber4; ColumnArray[4] = ColumnNumber5; ColumnArray[5] = ColumnNumber6; ColumnArray[6] = ColumnNumber7; ColumnArray[7] = ColumnNumber8; ColumnArray[8] = ColumnNumber9; ColumnArray[9] = ColumnNumber10; ColumnArray[10] = ColumnNumber11; ColumnArray[11] = ColumnNumber12; ColumnArray[12] = ColumnNumber13; ColumnArray[13] = ColumnNumber14; ColumnArray[14] = ColumnNumber15; ColumnArray[15] = ColumnNumber16; ColumnArray[16] = ColumnNumber17; ColumnArray[17] = ColumnNumber18; ColumnArray[18] = ColumnNumber19; ColumnArray[19] = ColumnNumber20; ColumnArray[20] = ColumnNumber21; ColumnArray[21] = ColumnNumber22; ColumnArray[22] = ColumnNumber23; ColumnArray[23] = ColumnNumber24; ColumnArray[24] = ColumnNumber25; ColumnArray[25] = ColumnNumber26; ColumnArray[26] = ColumnNumber27; ColumnArray[27] = ColumnNumber28; ColumnArray[28] = ColumnNumber29; ColumnArray[29] = ColumnNumber30; ColumnArray[30] = ColumnNumber31; ColumnArray[31] = ColumnNumber32; ColumnArray[32] = ColumnNumber33; ColumnArray[33] = ColumnNumber34; ColumnArray[34] = ColumnNumber35; ColumnArray[35] = ColumnNumber36; ColumnArray[36] = ColumnNumber37; ColumnArray[37] = ColumnNumber38; ColumnArray[38] = ColumnNumber39; ColumnArray[39] = ColumnNumber40; ColumnArray[40] = ColumnNumber41; ColumnArray[41] = ColumnNumber42; ColumnArray[42] = ColumnNumber43; ColumnArray[43] = ColumnNumber44; ColumnArray[44] = ColumnNumber45; ColumnArray[45] = ColumnNumber46; ColumnArray[46] = ColumnNumber47; ColumnArray[47] = ColumnNumber48; ColumnArray[48] = ColumnNumber49; ColumnArray[49] = ColumnNumber50; ColumnArray [50] = ColumnNumber51; ColumnArray [51] = ColumnNumber52; ColumnArray [52] = ColumnNumber53; ColumnArray [53] = ColumnNumber54; ColumnArray [54] = ColumnNumber55; ColumnArray [55] = ColumnNumber56; ColumnArray [56] = ColumnNumber57; ColumnArray [57] = ColumnNumber58; ColumnArray [58] = ColumnNumber59; ColumnArray [59] = ColumnNumber60; ColumnArray [60] = ColumnNumber61; ColumnArray [61] = ColumnNumber62; ColumnArray [62] = ColumnNumber63; ColumnArray [63] = ColumnNumber64; ColumnArray [64] = ColumnNumber65; ColumnArray [65] = ColumnNumber66; ColumnArray [66] = ColumnNumber67; ColumnArray [67] = ColumnNumber68; ColumnArray [68] = ColumnNumber69; ColumnArray [69] = ColumnNumber70; ColumnArray [70] = ColumnNumber71; ColumnArray [71] = ColumnNumber72; ColumnArray [72] = ColumnNumber73; ColumnArray [73] = ColumnNumber74; ColumnArray [74] = ColumnNumber75; ColumnArray [75] = ColumnNumber76; ColumnArray [76] = ColumnNumber77; ColumnArray [77] = ColumnNumber78; ColumnArray [78] = ColumnNumber79; ColumnArray [79] = ColumnNumber80; ColumnArray [80] = ColumnNumber81; ColumnArray [81] = ColumnNumber82; ColumnArray [82] = ColumnNumber83; ColumnArray [83] = ColumnNumber84; ColumnArray [84] = ColumnNumber85; ColumnArray [85] = ColumnNumber86; ColumnArray [86] = ColumnNumber87; ColumnArray [87] = ColumnNumber88; ColumnArray [88] = ColumnNumber89; ColumnArray [89] = ColumnNumber90; ColumnArray [90] = ColumnNumber91; ColumnArray [91] = ColumnNumber92; ColumnArray [92] = ColumnNumber93; ColumnArray [93] = ColumnNumber94; ColumnArray [94] = ColumnNumber95; ColumnArray [95] = ColumnNumber96; ColumnArray [96] = ColumnNumber97; ColumnArray [97] = ColumnNumber98; ColumnArray [98] = ColumnNumber99; ColumnArray [99] = ColumnNumber100;



        System.Data.SqlClient.SqlDataReader reader;
        System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection();
        cn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnstr"].ConnectionString;
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(query, cn);

        cn.Open();

        try
        {
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                try
                {
                    while (i < 100)
                    {
                        try
                        {
                            x[i] = reader[ColumnArray[i].ToString()].ToString().Trim();
                        }
                        catch
                        {
                            if (ColumnArray[i].ToString() != "0")
                            {
                                x[i] = "0";
                            }
                            else
                            {
                                reader.Close();
                                cn.Close();
                                cn.Dispose();
                                break;
                            }
                        }
                        i++;
                    }
                    reader.Close();
                    cn.Close();
                    cn.Dispose();
                    return(x);
                }
                catch
                {
                    reader.Close();
                    cn.Close();
                    cn.Dispose();
                    return(x);
                }
            }
            return(x);
        }
        catch
        {
            cn.Close();
            cn.Dispose();
            return(x);
        }
        finally
        {
            cn.Close();
            cn.Dispose();
        }
    }
示例#44
0
 private BfBotDbWorker()
 {
     s_sqlConnection = new SqlConnection(ConnectionString);
     OpenConnection();
 }
示例#45
0
 /// <summary>
 /// Método necesario para admitir el Diseñador. No se puede modificar
 /// el contenido del método con el editor de código.
 /// </summary>
 private void InitializeComponent()
 {
     this.components = new System.ComponentModel.Container();
     System.Configuration.AppSettingsReader         configurationAppSettings = new System.Configuration.AppSettingsReader();
     System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Principal));
     this.mainMenu          = new System.Windows.Forms.MainMenu(this.components);
     this.archivo           = new System.Windows.Forms.MenuItem();
     this.ActualizarMenu    = new System.Windows.Forms.MenuItem();
     this.CambiarUsuario    = new System.Windows.Forms.MenuItem();
     this.salir             = new System.Windows.Forms.MenuItem();
     this.Ventana           = new System.Windows.Forms.MenuItem();
     this.Horizontal        = new System.Windows.Forms.MenuItem();
     this.Vertical          = new System.Windows.Forms.MenuItem();
     this.Cascada           = new System.Windows.Forms.MenuItem();
     this.ayuda             = new System.Windows.Forms.MenuItem();
     this.acercade          = new System.Windows.Forms.MenuItem();
     this.sqlConn           = new System.Data.SqlClient.SqlConnection();
     this.stausbarPrincipal = new System.Windows.Forms.StatusBar();
     this.txtUsr            = new System.Windows.Forms.TextBox();
     this.SuspendLayout();
     //
     // mainMenu
     //
     this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
         this.archivo,
         this.Ventana,
         this.ayuda
     });
     //
     // archivo
     //
     this.archivo.Index = 0;
     this.archivo.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
         this.ActualizarMenu,
         this.CambiarUsuario,
         this.salir
     });
     this.archivo.Text = "&Archivo";
     //
     // ActualizarMenu
     //
     this.ActualizarMenu.Index  = 0;
     this.ActualizarMenu.Text   = "&Actualizar Menu";
     this.ActualizarMenu.Click += new System.EventHandler(this.ActualizarMenu_Click);
     //
     // CambiarUsuario
     //
     this.CambiarUsuario.Index  = 1;
     this.CambiarUsuario.Text   = "&Cambiar de usuario";
     this.CambiarUsuario.Click += new System.EventHandler(this.CambiarUsuario_Click);
     //
     // salir
     //
     this.salir.Index  = 2;
     this.salir.Text   = "&Salir";
     this.salir.Click += new System.EventHandler(this.salir_Click);
     //
     // Ventana
     //
     this.Ventana.Index   = 1;
     this.Ventana.MdiList = true;
     this.Ventana.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
         this.Horizontal,
         this.Vertical,
         this.Cascada
     });
     this.Ventana.Text = "&Ventana";
     //
     // Horizontal
     //
     this.Horizontal.Index      = 0;
     this.Horizontal.RadioCheck = true;
     this.Horizontal.Text       = "&Horizontal";
     this.Horizontal.Click     += new System.EventHandler(this.Horizontal_Click);
     //
     // Vertical
     //
     this.Vertical.Index      = 1;
     this.Vertical.RadioCheck = true;
     this.Vertical.Text       = "&Vertical";
     this.Vertical.Click     += new System.EventHandler(this.Vertical_Click);
     //
     // Cascada
     //
     this.Cascada.Index      = 2;
     this.Cascada.RadioCheck = true;
     this.Cascada.Text       = "&Cascada";
     this.Cascada.Click     += new System.EventHandler(this.Cascada_Click);
     //
     // ayuda
     //
     this.ayuda.Index = 2;
     this.ayuda.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
         this.acercade
     });
     this.ayuda.Text = "?";
     //
     // acercade
     //
     this.acercade.Index  = 0;
     this.acercade.Text   = "Acerca de";
     this.acercade.Click += new System.EventHandler(this.acercade_Click);
     //
     // sqlConn
     //
     this.sqlConn.ConnectionString = ((string)(configurationAppSettings.GetValue("sqlConn.ConnectionString", typeof(string))));
     this.sqlConn.FireInfoMessageEventOnUserErrors = false;
     //
     // stausbarPrincipal
     //
     this.stausbarPrincipal.Location = new System.Drawing.Point(0, 431);
     this.stausbarPrincipal.Name     = "stausbarPrincipal";
     this.stausbarPrincipal.Size     = new System.Drawing.Size(692, 22);
     this.stausbarPrincipal.TabIndex = 1;
     //
     // txtUsr
     //
     this.txtUsr.BackColor   = System.Drawing.SystemColors.ControlDark;
     this.txtUsr.BorderStyle = System.Windows.Forms.BorderStyle.None;
     this.txtUsr.ForeColor   = System.Drawing.SystemColors.ControlDark;
     this.txtUsr.Location    = new System.Drawing.Point(0, 0);
     this.txtUsr.Margin      = new System.Windows.Forms.Padding(0);
     this.txtUsr.MaxLength   = 10;
     this.txtUsr.Name        = "txtUsr";
     this.txtUsr.ReadOnly    = true;
     this.txtUsr.Size        = new System.Drawing.Size(0, 13);
     this.txtUsr.TabIndex    = 3;
     //
     // Principal
     //
     this.AutoScaleBaseSize     = new System.Drawing.Size(5, 13);
     this.AutoSize              = true;
     this.BackColor             = System.Drawing.SystemColors.HighlightText;
     this.BackgroundImage       = global::LancNeo.Properties.Resources.logolanc30A;
     this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
     this.ClientSize            = new System.Drawing.Size(692, 453);
     this.Controls.Add(this.txtUsr);
     this.Controls.Add(this.stausbarPrincipal);
     this.Icon           = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
     this.IsMdiContainer = true;
     this.Menu           = this.mainMenu;
     this.Name           = "Principal";
     this.Text           = "Sistema de Evaluación de Concreto";
     this.WindowState    = System.Windows.Forms.FormWindowState.Maximized;
     this.Load          += new System.EventHandler(this.Principal_Load);
     this.ResumeLayout(false);
     this.PerformLayout();
 }
示例#46
0
 public SysConsumerDbSvc(System.Data.SqlClient.SqlConnection connection)
     : base(connection)
 {
 }
示例#47
0
        static void Main(string[] args)
        {
            string serverConnectionString = args[0];
            string serverDatabase         = args[1];
            string serverSchema           = args[2];
            string countBytes             = args[3];
            string writeMode             = args[4];
            string defaultConstraintName = args[5];
            string defaultConstraintType = args[6];
            string defaultConstraint     = args[7];
            string reformBaseLink        = args[8];
            string reformTableId;

            try {
                reformTableId = args[9];
            }
            catch
            {
                reformTableId = null;
            }
            CultureInfo culture = new CultureInfo("en-us", false);

            culture.NumberFormat.NumberDecimalSeparator             = ".";
            Thread.CurrentThread.CurrentCulture                     = culture;
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); });
            using (TransactionScope scope = new TransactionScope())
                using (WebClient client = new InfiniteTimeoutWebClient())
                    using (SqlConnection connection = new System.Data.SqlClient.SqlConnection(serverConnectionString))
                        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
                        {
                            connection.Open();
                            if (reformTableId != null && reformTableId != "")
                            {
                                String      reformTableLink   = $"{reformBaseLink}/api/table/{reformTableId}";
                                String      encodedToken      = client.UploadString($"{reformTableLink}/access-token", "");
                                ReformToken token             = JsonConvert.DeserializeObject <ReformToken>(encodedToken);
                                String      reformResultsLink = $"{reformBaseLink}/api/result/{token.Secret}.csv";
                                Transfer(client, connection, bulkCopy, culture, serverConnectionString, serverDatabase, serverSchema, countBytes, writeMode, defaultConstraintName, defaultConstraintType, defaultConstraint, reformTableLink, reformResultsLink);
                            }
                            else
                            {
                                using (Stream reformTablesStream = client.OpenRead($"{reformBaseLink}/api/tables"))
                                    using (StreamReader reformTablesStreamReader = new StreamReader(reformTablesStream, System.Text.Encoding.UTF8))
                                    {
                                        String encodedTables = reformTablesStreamReader.ReadToEnd();
                                        Dictionary <String, ReformListingTable> tables = JsonConvert.DeserializeObject <Dictionary <String, ReformListingTable> >(encodedTables);
                                        foreach (KeyValuePair <String, ReformListingTable> table in tables)
                                        {
                                            if (!table.Value.Name.Contains("[Archived]"))
                                            {
                                                String      encodedToken      = client.UploadString($"{reformBaseLink}/api/table/{table.Key}/access-token", "");
                                                ReformToken token             = JsonConvert.DeserializeObject <ReformToken>(encodedToken);
                                                String      reformResultsLink = $"{reformBaseLink}/api/result/{token.Secret}.csv";
                                                Transfer(client, connection, bulkCopy, culture, serverConnectionString, serverDatabase, serverSchema, countBytes, writeMode, defaultConstraintName, defaultConstraintType, defaultConstraint, $"{reformBaseLink}/api/table/{table.Key}", $"{reformBaseLink}/api/result/{token.Secret}.csv");
                                            }
                                        }
                                    }
                            }
                            scope.Complete();
                        }
        }
示例#48
0
        //********************************************************************************

        public string populate_WSCL_Transitions_KAnonymity(string strRadioButtonItemSelected_KAnonType)
        {
            // In the previous processing, we added rows (from WSCL file info), where the rows
            // were not there already, to tables WSTransitionsTable and WSTransitionsAllPossibleRoutes.

            // Now, we go against the following table to see if we need to add rows to it:
            // WSCL_Transition_KAnonymity (if the rows are not there already).

            // This is an intermediate table that will be used further on.
            // Final goal down the line: provide an additional possible KAnon that can be chosen
            // when setting up assertions for the web service side

            string strReturnMessage = "";

            const string C_strAllMethPassThroughCounted    = "AllMethPassThroughCounted";
            const string C_strAllMethPassThroughNotCounted = "AllMethPassThroughNotCounted";
            const string C_strOnlyEndpointMeth             = "OnlyEndpointMeth";
            string       strStoredProcedure = "";

            switch (strRadioButtonItemSelected_KAnonType)
            {
            case C_strAllMethPassThroughCounted:
                strStoredProcedure = "spAdd_WSCL_Transition_KAnonymity_AllMethPassThroughCounted";
                break;

            case C_strAllMethPassThroughNotCounted:
                strStoredProcedure = "spAdd_WSCL_Transition_KAnonymity_AllMethPassThroughNotCounted";
                break;

            case C_strOnlyEndpointMeth:
                strStoredProcedure = "spAdd_WSCL_Transition_KAnonymity_OnlyEndpointMethods";
                break;

            default:
                var dataFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/ErrorLog.txt");
                File.AppendAllText(@dataFile, "KAnonymity Class, populate_WSCL_Transitions_KAnonymity: strRadioButtonItemSelected_KAnonType not specified");
                return("Error: strRadioButtonItemSelected_KAnonType not specified");
            }


            try
            {
                System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
                con.ConnectionString = ConfigurationManager.ConnectionStrings["WSProjectConnectionString"].ConnectionString;

                // previously: spAdd_WSCL_Transition_KAnonymity
                SqlCommand cmd = new SqlCommand(strStoredProcedure);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader reader;
                cmd.Connection = con;
                con.Open();
                reader = cmd.ExecuteReader();

                con.Close();
            }
            catch (Exception ex)
            {
                var dataFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/ErrorLog.txt");
                File.AppendAllText(@dataFile, "KAnonymity Class, populate_WSCL_Transitions_KAnonymity: " + ex.Message.ToString());
            }
            return(strReturnMessage);
        }
示例#49
0
    protected void ListViewMediaComment_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (String.Equals(e.CommandName, "LikeButtonComment"))
        {
            //Button lbtn = e.Item.FindControl("LinkButtonLike") as Button;

            Label  likeidlbl = e.Item.FindControl("LikeIdLabel") as Label;
            String like_Id   = likeidlbl.Text;
            likeId_inc = new Guid(likeidlbl.Text);
            MembershipUser currentUser = Membership.GetUser();

            Guid   currentUserId = (Guid)currentUser.ProviderUserKey;
            String user_Id       = currentUserId.ToString();
            //ListViewDataItem dataItem = (ListViewDataItem)e.Item;
            //Guid code = (Guid)ListView1.DataKeys[dataItem.DisplayIndex].Value;


            //if (String.Equals(lbtn.Text , "Like"))
            //{

            ImageButton lb = e.Item.FindControl("LinkButtonLike") as ImageButton;
            LinkButton  lbviewallcomment = e.Item.FindControl("LinkViewAllComment") as LinkButton;

            System.Data.SqlClient.SqlDataReader rdr    = null;
            System.Data.SqlClient.SqlConnection conn   = null;
            System.Data.SqlClient.SqlCommand    sqlcmd = null;

            try
            {
                string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["SecurityConnectionString"].ConnectionString;
                conn = new System.Data.SqlClient.SqlConnection(connectionString);

                sqlcmd = new System.Data.SqlClient.SqlCommand("select * from [UserLikes]", conn);
                conn.Open();

                rdr = sqlcmd.ExecuteReader();

                //if (rdr.HasRows)
                //{
                while (rdr.Read())
                {
                    String usrid = rdr["UserId"].ToString();
                    String lkid  = rdr["LikeId"].ToString();
                    if (user_Id == usrid && like_Id == lkid)
                    {
                        string connectionString10 = ConfigurationManager.ConnectionStrings["SecurityConnectionString"].ConnectionString;
                        //string selectSql = "SELECT * FROM UserLikes WHERE UserId = @UserId";
                        string Sql = "delete from [UserLikes] WHERE LikeId=@LikeId and UserId=@UserId";

                        using (SqlConnection myConnection = new SqlConnection(connectionString10))
                        {
                            myConnection.Open();
                            SqlCommand myCommand = new SqlCommand(Sql, myConnection);
                            myCommand.Parameters.AddWithValue("@LikeId", new Guid(like_Id));
                            myCommand.Parameters.AddWithValue("@UserId", new Guid(user_Id));

                            myCommand.ExecuteNonQuery();

                            myConnection.Close();
                        }
                        return;
                        //rdr.NextResult();
                    }
                }
                string connectionString11 =
                    ConfigurationManager.ConnectionStrings["SecurityConnectionString"].ConnectionString;


                string insertSql = "INSERT INTO UserLikes(LikeId,LikeUser,UserId) VALUES(@LikeId,@LikeUser,@UserId)";

                using (SqlConnection myConnection = new SqlConnection(connectionString11))
                {
                    myConnection.Open();
                    SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
                    myCommand.Parameters.AddWithValue("@LikeId", like_Id);
                    myCommand.Parameters.AddWithValue("@LikeUser", HttpContext.Current.Session["user"]);



                    myCommand.Parameters.AddWithValue("@UserId", user_Id);



                    myCommand.ExecuteNonQuery();
                    myConnection.Close();
                }


                if (rdr != null)
                {
                    rdr.Close();
                }
            }
            catch (Exception ex)
            {
            }

            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
                this.DataBind();
            }
        }
    }
示例#50
0
        public void WSTransitionsAllPossibleRoutes_InsertsToCoverAllRoutes(ref string strReturnMessage)
        {
            try
            {
                int intWebServiceID = 0;

                System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
                con.ConnectionString = ConfigurationManager.ConnectionStrings["WSProjectConnectionString"].ConnectionString;

                SqlCommand cmd = new SqlCommand("spSelectRows_MatchOnTransitionDestAndSource");
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader reader;
                cmd.Connection = con;
                con.Open();
                reader           = cmd.ExecuteReader();
                strReturnMessage = "";

                while (reader.Read())
                {
                    // this is a potential row we may want to add to the table WSCL_Transitions_AllPossibleRoutes
                    string strSource_Method_ID      = reader.GetValue(0).ToString(); // source id
                    string strDestination_Method_ID = reader.GetValue(1).ToString(); // destination id

                    int intSource_Method_ID;
                    int intDestination_Method_ID;
                    // make sure to check the success flags at some point
                    bool success1 = int.TryParse(strSource_Method_ID, out intSource_Method_ID);
                    bool success2 = int.TryParse(strDestination_Method_ID, out intDestination_Method_ID);

                    //**************************************************************************

                    try
                    {
                        System.Data.SqlClient.SqlConnection con2 = new System.Data.SqlClient.SqlConnection();
                        con2.ConnectionString = ConfigurationManager.ConnectionStrings["WSProjectConnectionString"].ConnectionString;

                        SqlCommand cmd2 = new SqlCommand("spAdd_WSCL_Transition_AllPossibleRoutes_IntIDs");
                        cmd2.CommandType = CommandType.StoredProcedure;
                        SqlDataReader reader2;
                        SqlParameter  param4 = new SqlParameter("@ws_id", SqlDbType.Int);
                        SqlParameter  param5 = new SqlParameter("@source_method_id", SqlDbType.Int);
                        SqlParameter  param6 = new SqlParameter("@destination_method_id", SqlDbType.Int);
                        cmd2.Connection = con2;

                        cmd2.Parameters.Add(param4).Value = intWebServiceID;
                        cmd2.Parameters.Add(param5).Value = intSource_Method_ID;
                        cmd2.Parameters.Add(param6).Value = intDestination_Method_ID;
                        con2.Open();
                        reader2 = cmd2.ExecuteReader();
                        reader2.Read();

                        strReturnMessage = reader2.GetValue(0).ToString();

                        con2.Close();
                    }
                    catch (Exception ex)
                    {
                        var dataFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/ErrorLog.txt");
                        File.AppendAllText(@dataFile, "KAnonymity Class, WSTransitionsAllPossibleRoutes_InsertsToCoverAllRoutes (A): " + ex.Message.ToString());
                    }

                    //**************************************************************************
                }

                con.Close();
            }
            catch (Exception ex)
            {
                var dataFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/ErrorLog.txt");
                File.AppendAllText(@dataFile, "KAnonymity Class, WSTransitionsAllPossibleRoutes_InsertsToCoverAllRoutes (B): " + ex.Message.ToString());
            }
        }
示例#51
0
        public Esito AggiornaQualificaCollaboratore(Anag_Qualifiche_Collaboratori qualificaCollaboratore, Anag_Utenti utente)
        {
            Esito esito = new Esito();

            try
            {
                using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(sqlConstr))
                {
                    using (System.Data.SqlClient.SqlCommand StoreProc = new System.Data.SqlClient.SqlCommand("UpdateQualificheCollaboratore"))
                    {
                        using (System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter())
                        {
                            StoreProc.Connection  = con;
                            sda.SelectCommand     = StoreProc;
                            StoreProc.CommandType = CommandType.StoredProcedure;

                            System.Data.SqlClient.SqlParameter id = new System.Data.SqlClient.SqlParameter("@id", qualificaCollaboratore.Id);
                            id.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id);

                            // PARAMETRI PER LOG UTENTE
                            SqlParameter idUtente = new SqlParameter("@idUtente", utente.id);
                            idUtente.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(idUtente);

                            SqlParameter nomeUtente = new SqlParameter("@nomeUtente", utente.username);
                            nomeUtente.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nomeUtente);
                            // FINE PARAMETRI PER LOG UTENTE

                            SqlParameter id_collaboratore = new SqlParameter("@id_collaboratore", qualificaCollaboratore.Id_collaboratore);
                            id_collaboratore.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_collaboratore);

                            SqlParameter priorita = new SqlParameter("@priorita", qualificaCollaboratore.Priorita);
                            priorita.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(priorita);

                            SqlParameter qualifica = new SqlParameter("@qualifica", qualificaCollaboratore.Qualifica);
                            qualifica.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(qualifica);

                            SqlParameter descrizione = new SqlParameter("@descrizione", qualificaCollaboratore.Descrizione);
                            descrizione.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(descrizione);

                            SqlParameter attivo = new SqlParameter("@attivo", qualificaCollaboratore.Attivo);
                            attivo.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(attivo);

                            StoreProc.Connection.Open();

                            int iReturn = StoreProc.ExecuteNonQuery();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                esito.Codice      = Esito.ESITO_KO_ERRORE_SCRITTURA_TABELLA;
                esito.Descrizione = "Anag_Qualifiche_Collaboratori_DAL.cs - AggiornaQualificaCollaboratore " + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace;
            }

            return(esito);
        }
示例#52
0
        public Esito AggiornaDatiAgendaMagazzino(DatiAgendaMagazzino datiAgendaMagazzino)
        {
            Esito       esito  = new Esito();
            Anag_Utenti utente = ((Anag_Utenti)HttpContext.Current.Session[SessionManager.UTENTE]);

            try
            {
                using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(sqlConstr))
                {
                    using (System.Data.SqlClient.SqlCommand StoreProc = new System.Data.SqlClient.SqlCommand("UpdateDatiAgendaMagazzino"))
                    {
                        using (System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter())
                        {
                            StoreProc.Connection  = con;
                            sda.SelectCommand     = StoreProc;
                            StoreProc.CommandType = CommandType.StoredProcedure;

                            System.Data.SqlClient.SqlParameter id = new System.Data.SqlClient.SqlParameter("@id", datiAgendaMagazzino.Id);
                            id.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id);

                            // PARAMETRI PER LOG UTENTE
                            SqlParameter idUtente = new SqlParameter("@idUtente", utente.id);
                            idUtente.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(idUtente);

                            SqlParameter nomeUtente = new SqlParameter("@nomeUtente", utente.username);
                            nomeUtente.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nomeUtente);
                            // FINE PARAMETRI PER LOG UTENTE

                            SqlParameter id_Agenda = new SqlParameter("@id_Agenda", datiAgendaMagazzino.Id_Agenda);
                            id_Agenda.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Agenda);

                            SqlParameter descrizione_Camera = new SqlParameter("@descrizione_Camera", datiAgendaMagazzino.Descrizione_Camera);
                            descrizione_Camera.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(descrizione_Camera);

                            SqlParameter id_Altro1 = new SqlParameter("@id_Altro1", datiAgendaMagazzino.Id_Altro1);
                            id_Altro1.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Altro1);

                            SqlParameter id_Altro2 = new SqlParameter("@id_Altro2", datiAgendaMagazzino.Id_Altro2);
                            id_Altro2.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Altro2);

                            SqlParameter id_Camera = new SqlParameter("@id_Camera", datiAgendaMagazzino.Id_Camera);
                            id_Camera.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Camera);

                            SqlParameter id_Cavalletto = new SqlParameter("@id_Cavalletto", datiAgendaMagazzino.Id_Cavalletto);
                            id_Cavalletto.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Cavalletto);

                            SqlParameter id_Cavi = new SqlParameter("@id_Cavi", datiAgendaMagazzino.Id_Cavi);
                            id_Cavi.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Cavi);

                            SqlParameter id_Fibra_Trax = new SqlParameter("@id_Fibra_Trax", datiAgendaMagazzino.Id_Fibra_Trax);
                            id_Fibra_Trax.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Fibra_Trax);

                            SqlParameter id_Lensholder = new SqlParameter("@id_Lensholder", datiAgendaMagazzino.Id_Lensholder);
                            id_Lensholder.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Lensholder);

                            SqlParameter id_Loop = new SqlParameter("@id_Loop", datiAgendaMagazzino.Id_Loop);
                            id_Loop.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Loop);

                            SqlParameter id_Mic = new SqlParameter("@id_Mic", datiAgendaMagazzino.Id_Mic);
                            id_Mic.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Mic);

                            SqlParameter id_Ottica = new SqlParameter("@id_Ottica", datiAgendaMagazzino.Id_Ottica);
                            id_Ottica.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Ottica);

                            SqlParameter id_Testa = new SqlParameter("@id_Testa", datiAgendaMagazzino.Id_Testa);
                            id_Testa.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Testa);

                            SqlParameter id_Viewfinder = new SqlParameter("@id_Viewfinder", datiAgendaMagazzino.Id_Viewfinder);
                            id_Viewfinder.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(id_Viewfinder);

                            SqlParameter nome_Altro1 = new SqlParameter("@nome_Altro1", datiAgendaMagazzino.Nome_Altro1);
                            nome_Altro1.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Altro1);

                            SqlParameter nome_Altro2 = new SqlParameter("@nome_Altro2", datiAgendaMagazzino.Nome_Altro2);
                            nome_Altro2.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Altro2);

                            SqlParameter nome_Camera = new SqlParameter("@nome_Camera", datiAgendaMagazzino.Nome_Camera);
                            nome_Camera.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Camera);

                            SqlParameter nome_Cavalletto = new SqlParameter("@nome_Cavalletto", datiAgendaMagazzino.Nome_Cavalletto);
                            nome_Cavalletto.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Cavalletto);

                            SqlParameter nome_Cavi = new SqlParameter("@nome_Cavi", datiAgendaMagazzino.Nome_Cavi);
                            nome_Cavi.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Cavi);

                            SqlParameter nome_Fibra_Trax = new SqlParameter("@nome_Fibra_Trax", datiAgendaMagazzino.Nome_Fibra_Trax);
                            nome_Fibra_Trax.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Fibra_Trax);

                            SqlParameter nome_Lensholder = new SqlParameter("@nome_Lensholder", datiAgendaMagazzino.Nome_Lensholder);
                            nome_Lensholder.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Lensholder);

                            SqlParameter nome_Loop = new SqlParameter("@nome_Loop", datiAgendaMagazzino.Nome_Loop);
                            nome_Loop.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Loop);

                            SqlParameter nome_Mic = new SqlParameter("@nome_Mic", datiAgendaMagazzino.Nome_Mic);
                            nome_Mic.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Mic);

                            SqlParameter nome_Ottica = new SqlParameter("@nome_Ottica", datiAgendaMagazzino.Nome_Ottica);
                            nome_Ottica.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Ottica);

                            SqlParameter nome_Testa = new SqlParameter("@nome_Testa", datiAgendaMagazzino.Nome_Testa);
                            nome_Testa.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Testa);

                            SqlParameter nome_Viewfinder = new SqlParameter("@nome_Viewfinder", datiAgendaMagazzino.Nome_Viewfinder);
                            nome_Viewfinder.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(nome_Viewfinder);

                            SqlParameter attivo = new SqlParameter("@attivo", datiAgendaMagazzino.Attivo);
                            attivo.Direction = ParameterDirection.Input;
                            StoreProc.Parameters.Add(attivo);


                            StoreProc.Connection.Open();

                            int iReturn = StoreProc.ExecuteNonQuery();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                esito.Codice      = Esito.ESITO_KO_ERRORE_SCRITTURA_TABELLA;
                esito.Descrizione = "Dati_Agenda_Magazzino_DAL.cs - AggiornaDatiAgendaMagazzino " + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace;
            }

            return(esito);
        }
示例#53
0
        private void NewUpdate(int year = 0, int month = 0)
        {
            try
            {
                if (year == 0)
                {
                    return;
                }
                if (month == 0)
                {
                    return;
                }

                //string cbVal = inputRow["YEARS"].ToString();

                //задаем значение для combobox1
                //  comboBox2.SelectedValue = cbVal;

                //  string comBoxValue = comboBox2.SelectedValue.ToString();

                String connectionString = "Data Source=ANUTA;Initial Catalog=sbyt;Integrated Security=True";
                string query            = String.Format("SELECT [REQUEST_FOR_SHIPPING].[REQUEST_FOR_SHIPPING_ID] as id_pl ,[REQUEST_FOR_SHIPPING].[CONTRACT_ID],WAYBILL_OUT.[CONTRACT_ID] as Contract_fact ,[REQUEST_FOR_SHIPPING].[JBI_ID] ,[WAYBILL_OUT].[JBI_ID] as jbi_po_faktu ,cast([DATE] as varchar(max)) as Data_po_planu ,cast([FACT_DATE_OF_RELEASE] as varchar(max)) as [FACT_DATE_OF_RELEASE],ISNULL([REQUEST_FOR_SHIPPING].[AMOUNT],0) AS PLANOVOE ,ISNULL(WAYBILL_OUT.AMOUNT,0) AS FAKTOVOE,ISNULL(WAYBILL_OUT.AMOUNT,0)-ISNULL([REQUEST_FOR_SHIPPING].[AMOUNT],0) as Raznica ,CUSTOMERS.CUSTOMER_NAME ,[JBI_NAME],units FROM [sbyt].[dbo].[REQUEST_FOR_SHIPPING] right outer JOIN WAYBILL_OUT ON [REQUEST_FOR_SHIPPING].[REQUEST_FOR_SHIPPING_ID]=WAYBILL_OUT.[REQUEST_FOR_SHIPPING_ID] left outer JOIN CONTRACTS ON WAYBILL_OUT.CONTRACT_ID=CONTRACTS.CONTRACT_ID left outer JOIN CUSTOMERS ON CONTRACTS.[CUSTOMER_ID]=CUSTOMERS.[CUSTOMER_ID] INNER JOIN CATALOG_JBI ON WAYBILL_OUT.[JBI_ID]=CATALOG_JBI.[JBI_ID] WHERE MONTH([FACT_DATE_OF_RELEASE])={0} and YEAR([FACT_DATE_OF_RELEASE])={1} and [DELIVERY-PICKUP]=0 UNION  SELECT [REQUEST_FOR_SHIPPING].[REQUEST_FOR_SHIPPING_ID] ,[REQUEST_FOR_SHIPPING].[CONTRACT_ID] ,WAYBILL_OUT.[CONTRACT_ID] as Contract_fact ,[REQUEST_FOR_SHIPPING].[JBI_ID],[WAYBILL_OUT].[JBI_ID] as jbi_po_faktu ,cast([DATE] as varchar(max)) as Data_po_planu ,cast([FACT_DATE_OF_RELEASE] as varchar(max)) as [FACT_DATE_OF_RELEASE],ISNULL([REQUEST_FOR_SHIPPING].[AMOUNT],0) AS PLANOVOE,ISNULL(WAYBILL_OUT.AMOUNT,0) AS FAKTOVOE,ISNULL(WAYBILL_OUT.AMOUNT,0)-ISNULL([REQUEST_FOR_SHIPPING].[AMOUNT],0) as Raznica ,CUSTOMERS.CUSTOMER_NAME,[JBI_NAME],units FROM [sbyt].[dbo].[REQUEST_FOR_SHIPPING] LEFT outer JOIN WAYBILL_OUT ON [REQUEST_FOR_SHIPPING].[REQUEST_FOR_SHIPPING_ID]=WAYBILL_OUT.[REQUEST_FOR_SHIPPING_ID] left outer JOIN CONTRACTS ON [REQUEST_FOR_SHIPPING].CONTRACT_ID=CONTRACTS.CONTRACT_ID left outer JOIN CUSTOMERS ON CONTRACTS.[CUSTOMER_ID]=CUSTOMERS.[CUSTOMER_ID] INNER JOIN CATALOG_JBI ON [REQUEST_FOR_SHIPPING].[JBI_ID]=CATALOG_JBI.[JBI_ID] WHERE MONTH(DATE)={0} AND YEAR(DATE)={1}  and [DELIVERY-PICKUP]=0", month, year);

                System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString);

                connection.Open();

                SqlDataAdapter adapter = new SqlDataAdapter();

                adapter.SelectCommand = new SqlCommand(query, connection);

                DataTable tempTable = new DataTable();

                adapter.Fill(tempTable);

                connection.Close();

                connection = null;

                foreach (DataRow row in tempTable.Rows)
                {
                    try
                    {
                        DateTime tempTime = Convert.ToDateTime(row["Data_po_planu"].ToString());

                        row["Data_po_planu"] = tempTime.ToShortDateString();
                    }
                    catch (Exception ex)
                    {
                        // MessageBox.Show(ex.Message);
                    }
                }

                foreach (DataRow row in tempTable.Rows)
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(row["FACT_DATE_OF_RELEASE"].ToString()))
                        {
                            DateTime tempTime = Convert.ToDateTime(row["FACT_DATE_OF_RELEASE"].ToString());
                            row["FACT_DATE_OF_RELEASE"] = tempTime.ToShortDateString();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }


                _ListView.ItemsSource = tempTable.DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
示例#54
0
        //private static bool TryReconnect(ref SqlServerConnection connection, string checkConnectionQuery)
        //{
        //  try {
        //    var newConnection = new SqlServerConnection(connection.ConnectionString);
        //    try {
        //      connection.Close();
        //      connection.Dispose();
        //    }
        //    catch { }

        //    connection = newConnection;
        //    connection.Open();

        //    using (var command = connection.CreateCommand()) {
        //      command.CommandText = checkConnectionQuery;
        //      command.ExecuteNonQuery();
        //    }
        //    return true;
        //  }
        //  catch (Exception) {
        //    return false;
        //  }
        //}


        // Constructors

        public Connection(SqlDriver driver, bool checkConnection)
            : base(driver)
        {
            underlyingConnection   = new SqlServerConnection();
            checkConnectionIsAlive = checkConnection;
        }
示例#55
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlCommand    inscommand;
            SqlConnection conn;

            SqlCommand    inscommandtop;
            SqlConnection conntop;
            string        lastname;

            try
            {
                string cs = ConfigurationManager.ConnectionStrings["gitpropertyConnectionString"].ConnectionString;
                //conn = new System.Data.SqlClient.SqlConnection();
                conn = new SqlConnection();

                conn.ConnectionString = cs;

                string cmdtext = "SELECT * FROM [vendors];";
                inscommand = new SqlCommand(cmdtext, conn);

                conn.Open();

                SqlDataReader reader = inscommand.ExecuteReader();
                while (reader.Read())
                {
                    lastname = (string)reader["vendorlastname"];
                }
                inscommand.Dispose();
                conn.Close();
                conn.Dispose();

                conntop = new System.Data.SqlClient.SqlConnection(cs);
                //conntop.ConnectionString = cs;


                string cmdtexttop = "SELECT vendorlastname FROM [vendors];";
                inscommandtop = new SqlCommand(cmdtexttop, conntop);

                conntop.Open();

                GridView3.DataSource = inscommandtop.ExecuteReader();
                GridView3.DataBind();

                // inscommandtop.Dispose();
                // conntop.Close();
                //  conntop.Dispose();
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                case 0:
                    Response.Write("<br/><br/><br/>Cannot connect to server. " +
                                   "<br/>Sql Error Message = " + ex.Message +
                                   "<br/>Sql Error Number = " + ex.Number + "<br/><br/>");
                    break;

                case 1045:
                    Response.Write("Invalid username/password, please try again" +
                                   "<br/>Sql Error Message = " + ex.Message +
                                   "<br/>Sql Error Number = " + ex.Number + "<br/><br/>");
                    break;

                default:
                    Response.Write("<br/>Unknown Error = " + ex.Number +
                                   " Error Message = " + ex.Message);
                    break;
                }
            }
        }
示例#56
0
        private void estudio(string rut)
        {
            tituloEstudio.Visible = true;
            System.Data.SqlClient.SqlConnection adoConn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BaseSqlServer"].ConnectionString);
            adoConn.Open();
            System.Web.UI.WebControls.TableRow  row   = new System.Web.UI.WebControls.TableRow();
            System.Web.UI.WebControls.TableCell cell1 = new System.Web.UI.WebControls.TableCell();
            System.Web.UI.WebControls.TableCell cell2 = new System.Web.UI.WebControls.TableCell();
            System.Web.UI.WebControls.TableCell cell3 = new System.Web.UI.WebControls.TableCell();
            cell2.Font.Bold = true;

            string        sql    = "select anotit, anoegre, rut, nombre_c from MT_ALUMNO, mt_carrer where MT_ALUMNO.codcarpr = mt_carrer.codcarr AND rut = '" + rut + "';";
            SqlCommand    adoCmd = new System.Data.SqlClient.SqlCommand(sql, adoConn);
            SqlDataReader adoDR  = adoCmd.ExecuteReader();

            if (adoDR.HasRows)
            {
                if (adoDR.Read())
                {
                    if ("".Equals(adoDR["anotit"].ToString()) || "null".Equals(adoDR["anotit"].ToString().ToLower()) || "0".Equals(adoDR["anotit"].ToString()))
                    {
                        if ("".Equals(adoDR["anoegre"].ToString()) || "null".Equals(adoDR["anoegre"].ToString().ToLower()) || "0".Equals(adoDR["anoegre"].ToString()))
                        {
                            cell1.Text = "Sin informaci&oacte;n";
                        }
                        else
                        {
                            cell1.Text = adoDR["anoegre"].ToString();
                        }
                    }
                    else
                    {
                        cell1.Text = adoDR["anotit"].ToString();
                    }

                    cell2.Text = adoDR["nombre_c"].ToString() + "<br />Escuela de Contadores Auditores de Santiago";
                    cell3.Text = "Profesional";
                    row.Cells.Add(cell1);
                    row.Cells.Add(cell2);
                    row.Cells.Add(cell3);
                    estudioExtra.Rows.Add(row);
                }
            }

            adoDR.Close();
            adoDR  = null;
            adoCmd = null;
            sql    = "SELECT " + tabla + "tipoEstudio.tipo, " + tabla + "estudioExtra.egreso, " + tabla + "estudioExtra.institucion, " + tabla + "estudioExtra.titulo, " + tabla + "estudioExtra.estudioExtraID FROM " + tabla + "estudioExtra, " + tabla + "tipoEstudio WHERE rut = " + rut + " AND " + tabla + "tipoEstudio.tipoEstudioID = " + tabla + "estudioExtra.tipoEstudioID;";
            adoCmd = new SqlCommand(sql, adoConn);
            adoDR  = adoCmd.ExecuteReader();
            if (adoDR.HasRows)
            {
                while (adoDR.Read())
                {
                    System.Web.UI.WebControls.TableRow  row1    = new System.Web.UI.WebControls.TableRow();
                    System.Web.UI.WebControls.TableCell cell1_1 = new System.Web.UI.WebControls.TableCell();
                    System.Web.UI.WebControls.TableCell cell2_1 = new System.Web.UI.WebControls.TableCell();
                    System.Web.UI.WebControls.TableCell cell3_1 = new System.Web.UI.WebControls.TableCell();
                    cell2_1.Font.Bold = true;
                    cell1_1.Text      = adoDR["egreso"].ToString();
                    cell2_1.Text      = adoDR["titulo"].ToString() + "<br />" + adoDR["institucion"].ToString();
                    cell3_1.Text      = adoDR["tipo"].ToString();
                    row1.Cells.Add(cell1_1);
                    row1.Cells.Add(cell2_1);
                    row1.Cells.Add(cell3_1);
                    System.Web.UI.WebControls.TableCell cellx = new System.Web.UI.WebControls.TableCell();
                    System.Web.UI.WebControls.HyperLink hl    = new System.Web.UI.WebControls.HyperLink();
                    System.Web.UI.WebControls.Image     im    = new System.Web.UI.WebControls.Image();
                    im.ImageUrl      = "imagenes/cross.png";
                    im.AlternateText = "Borrar";
                    hl.Controls.Add(im);
                    hl.NavigateUrl = "borrarEstudio.aspx?rut=" + rut + "&estudioExtraID=" + adoDR["estudioExtraID"].ToString();
                    System.Web.UI.WebControls.HyperLink h2  = new System.Web.UI.WebControls.HyperLink();
                    System.Web.UI.WebControls.Image     im2 = new System.Web.UI.WebControls.Image();
                    im2.ImageUrl      = "imagenes/page_edit.png";
                    im2.AlternateText = "Editar";
                    h2.Controls.Add(im2);
                    h2.NavigateUrl = "agregarEstudio.aspx?rut=" + rut + "&estudioExtraID=" + adoDR["estudioExtraID"].ToString();

                    // Revision de permisos para usuarios con acceso de solo lectura
                    if (Session["ficha"].ToString().Equals(ConfigurationManager.AppSettings["escritura"].ToString()))
                    {
                        cellx.Controls.Add(hl);
                        cellx.Controls.Add(h2);
                    }

                    cellx.Width           = (System.Web.UI.WebControls.Unit) 10;
                    cellx.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Right;
                    row1.Cells.Add(cellx);
                    estudioExtra.Rows.Add(row1);
                }
            }
        }
示例#57
0
        //修改
        private bool EditData(string oldvendorcode, string newvendorcode, string vendorname, string AttachMan, string Telephone, bool disabled)
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
            conn.ConnectionString = rms_var.ConnStr;
            try
            {
                SqlCommand     selectCMD;
                SqlDataAdapter dbDA;
                DataSet        dbDS;

                if (oldvendorcode == newvendorcode)                 //没有改变,直接更新
                {
                    selectCMD                = new SqlCommand();
                    selectCMD.Connection     = conn;
                    selectCMD.CommandTimeout = 30;
                    conn.Open();

                    selectCMD.Connection     = conn;
                    selectCMD.CommandTimeout = 30;
                    selectCMD.CommandText    = "update vendor set " + "vendorname='" + vendorname + "'" + "," + "AttachMan='" + vendorname + "'" + "," + "Telephone='" + vendorname + "'" + "," + "disabled='" + Math.Abs(System.Convert.ToInt32(disabled)).ToString() + "' " + "where vendorcode='" + oldvendorcode + "'";
                    selectCMD.ExecuteNonQuery();

                    return(true);
                }
                else                 //编码改变
                {
                    selectCMD             = new SqlCommand();
                    selectCMD.CommandText = "select vendorcode from vendor where vendorcode='" + newvendorcode + "'" + "' and vendorcode<>'" + oldvendorcode + "'";

                    selectCMD.Connection     = conn;
                    selectCMD.CommandTimeout = 30;
                    dbDA = new SqlDataAdapter();
                    dbDA.SelectCommand = selectCMD;
                    conn.Open();
                    dbDS = new DataSet();
                    dbDA.Fill(dbDS, "t");

                    if (dbDS.Tables[0].Rows.Count > 0)                     //存在该编码
                    {
                        MessageBox.Show("编码或名称重复!");
                        return(false);
                    }
                    else
                    {
                        selectCMD.Connection     = conn;
                        selectCMD.CommandTimeout = 30;
                        selectCMD.CommandText    = "update vendor set " + "vendorcode='" + newvendorcode + "'" + "," + "vendorname='" + newvendorcode + "'" + "," + "AttachMan='" + newvendorcode + "'" + "," + "Telephone='" + Telephone + "'" + "," + "disabled='" + Math.Abs(System.Convert.ToInt32(disabled)).ToString() + "'" + "where vendorcode='" + oldvendorcode + "'";
                        selectCMD.ExecuteNonQuery();

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
            return(false);
        }
示例#58
0
        private void informacionPersonal(string rut)
        {
            string sql = "SELECT rut, dig, codcli, nombre, fecnac, paterno, materno, anoegre, anotit, DATEPART(year, fecing) as anoingreso, mail, estacad, anotit, fecnac, diractual, comuna, ciudadact, fonoact " +
                         "FROM " + tabla + "listado WHERE rut = " + rut;

            System.Data.SqlClient.SqlConnection adoConn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BaseSqlServer"].ConnectionString);
            adoConn.Open();
            System.Data.SqlClient.SqlCommand    adoCmd = new System.Data.SqlClient.SqlCommand(sql, adoConn);
            System.Data.SqlClient.SqlDataReader adoDR  = adoCmd.ExecuteReader();
            if (adoDR.HasRows)
            {
                while (adoDR.Read())
                {
                    nombre.Text          = adoDR["nombre"].ToString() + " " + adoDR["paterno"].ToString() + " " + adoDR["materno"].ToString();
                    direccion.Text       = adoDR["diractual"].ToString() + ". " + adoDR["comuna"].ToString() + " " + adoDR["ciudadact"].ToString();
                    telefono.Text        = adoDR["fonoact"].ToString();
                    estacad.Text         = adoDR["estacad"].ToString();
                    correo.Text          = adoDR["mail"].ToString();
                    anotitulacion.Text   = adoDR["anotit"].ToString() != "0" ? adoDR["anotit"].ToString() : "Sin informaci&oacute;n";
                    anoingreso.Text      = adoDR["anoingreso"].ToString() != "0" ? adoDR["anoingreso"].ToString() : "Sin informaci&oacute;n";
                    anoegreso.Text       = adoDR["anoegre"].ToString() != "0" ? adoDR["anoegre"].ToString() : "Sin informaci&oacute;n";
                    this.rut.Text        = adoDR["rut"].ToString() + "-" + adoDR["dig"].ToString();
                    numeroecas.Text      = adoDR["codcli"].ToString();
                    fechanacimiento.Text = adoDR["fecnac"].ToString().Replace(" 0:00:00", "");
                }
            }
            adoDR.Close();
            adoConn.Close();
            adoDR   = null;
            adoCmd  = null;
            adoConn = null;
            direccionLaboral.Text = "Sin informaci&oacute;n disponible.";
            sql     = "SELECT rut, calle, comuna, ciudad FROM " + tabla + "historiaLaboral WHERE rut = '" + rut + "' AND hastaAnio = -1 AND hastaMes = -1";
            adoConn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BaseSqlServer"].ConnectionString);
            adoConn.Open();
            adoCmd = new System.Data.SqlClient.SqlCommand(sql, adoConn);
            adoDR  = adoCmd.ExecuteReader();
            if (adoDR.HasRows)
            {
                if (adoDR.Read())
                {
                    direccionLaboral.Text = adoDR["calle"].ToString() + ". " + adoDR["comuna"].ToString() + " " + adoDR["ciudad"].ToString();
                }
                else
                {
                    direccionLaboral.Text = "Informaci&oacute;n no disponible.";
                }
            }
            else
            {
                direccionLaboral.Text = "Informaci&oacute;n no disponible.";
            }
            adoDR.Close();
            adoConn.Close();
            adoDR   = null;
            adoCmd  = null;
            adoConn = null;

            // Revision de permisos para usuarios con acceso de solo lectura
            if (!Session["ficha"].ToString().Equals(ConfigurationManager.AppSettings["escritura"].ToString()))
            {
                hlDatosPersonales.Visible = false;
            }
        }
示例#59
0
        }     // End Sub SaveAssembly2

        // http://stackoverflow.com/questions/2885335/clr-sql-assembly-get-the-bytestream
        // http://stackoverflow.com/questions/891617/how-to-read-a-image-by-idatareader
        // http://stackoverflow.com/questions/4103406/extracting-a-net-assembly-from-sql-server-2005
        public virtual void SaveAssembly3(string assemblyName, string path)
        {
            string sql = @"
--DECLARE @__assemblyname nvarchar(260)
--SET @__assemblyname = 'Microsoft.SqlServer.Types'


SELECT 
	 A.name
	,AF.content 
FROM sys.assembly_files AS AF 

INNER JOIN sys.assemblies AS A 
	ON AF.assembly_id = A.assembly_id 
	
WHERE AF.file_id = 1 
AND A.name = @__assemblyname
;

";

            using (System.Data.IDbConnection conn = new System.Data.SqlClient.SqlConnection("context connection=true"))   //Create current context connection
            {
                using (System.Data.IDbCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;

                    System.Data.IDbDataParameter param = cmd.CreateParameter();
                    param.ParameterName = "@__assemblyname";
                    param.DbType        = System.Data.DbType.String;
                    param.Value         = assemblyName;
                    param.Size          = 128;
                    cmd.Parameters.Add(param);
                    cmd.Prepare();


                    using (System.Data.IDataReader reader = cmd.ExecuteReader())
                    {
                        reader.Read();

                        const int BUFFER_SIZE = 1024;
                        byte[]    buffer      = new byte[BUFFER_SIZE];

                        int col       = reader.GetOrdinal("content");
                        int bytesRead = 0;
                        int offset    = 0;

                        // write the byte stream out to disk
                        using (System.IO.FileStream bytestream = new System.IO.FileStream(path, System.IO.FileMode.CreateNew))
                        {
                            while ((bytesRead = (int)reader.GetBytes(col, offset, buffer, 0, BUFFER_SIZE)) > 0)
                            {
                                bytestream.Write(buffer, 0, bytesRead);
                                offset += bytesRead;
                            } // Whend

                            bytestream.Close();
                        } // End Using bytestream

                        reader.Close();
                    } // End Using reader
                }     // End Using cmd
            }         // End Using conn
        }             // End Function SaveAssembly3
示例#60
0
        } // End Sub SaveAssembly

        public static void SaveAssembly2(string assemblyName, string destinationPath)
        {
            string sql = @"SELECT af.name, af.content FROM sys.assemblies a INNER JOIN sys.assembly_files af ON a.assembly_id = af.assembly_id WHERE a.name = @assemblyname";


            using (System.Data.Common.DbConnection conn = new System.Data.SqlClient.SqlConnection("context connection=true"))   //Create current context connection
            {
                using (System.Data.Common.DbCommand cmd = new System.Data.SqlClient.SqlCommand(sql, (System.Data.SqlClient.SqlConnection)conn))
                {
                    System.Data.Common.DbParameter param = new System.Data.SqlClient.SqlParameter("@assemblyname", System.Data.SqlDbType.NVarChar);
                    param.Value = assemblyName;
                    // param.Size = 128;
                    cmd.Parameters.Add(param);


                    using (System.IO.Stream fs = new System.IO.FileStream("logo" + "pub_id" + ".bmp", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
                    {
                        using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))
                        {
                            long startIndex = 0;
                            var  buffer     = new byte[1024];
                            int  bufferSize = buffer.Length;

                            if (cmd.Connection.State != System.Data.ConnectionState.Open)
                            {
                                cmd.Connection.Open();  //Open the context connetion
                            }
                            using (System.Data.Common.DbDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())                              //Iterate through assembly files
                                {
                                    string assemblyFileName = reader.GetString(0); //get assembly file name from the name (first) column

                                    long retval = reader.GetBytes(1, startIndex, buffer, 0, bufferSize);

                                    // Continue reading and writing while there are bytes beyond the size of the buffer.
                                    while (retval == bufferSize)
                                    {
                                        bw.Write(buffer);
                                        bw.Flush();

                                        // Reposition the start index to the end of the last buffer and fill the buffer.
                                        startIndex += bufferSize;
                                        retval      = reader.GetBytes(1, startIndex, buffer, 0, bufferSize);
                                    } // Whend

                                    // Write the remaining buffer.
                                    bw.Write(buffer, 0, (int)retval);
                                    bw.Flush();
                                    bw.Close();
                                } // Whend reader.Read
                            }     // End Using reader
                        }         // End using bw

                        fs.Flush();
                        fs.Close();
                    } // End using fs
                }     // End using cmd

                if (conn.State != System.Data.ConnectionState.Closed)
                {
                    conn.Close();
                }
            } // End Using conn
        }     // End Sub SaveAssembly2