Example #1
0
 // Занесение новой записи в БД
 public static bool Insert(System.Data.SqlClient.SqlConnection connection, System.Data.DataRow row, out string message)
 {
     bool done = false;
     message = "";
     try{
         connection.Open();
         System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
         string sQuery = "INSERT INTO " + Maker.Table + "\n" +
                         "       (MakerID, Name, MakerCategory, Vendor, Address, Created, Updated)\n" +
                         "VALUES (@MakerID, @Name, @MakerCategory, @Vendor, @Address, GETDATE(), GETDATE())";
         cmd.Parameters.AddWithValue("@MakerID", row["MakerID"]);
         cmd.Parameters.AddWithValue("@Name", row["Name"]);
         cmd.Parameters.AddWithValue("@MakerCategory", row["MakerCategory"]);
         cmd.Parameters.AddWithValue("@Vendor", row["Vendor"]);
         cmd.Parameters.AddWithValue("@Address", row["Address"]);
         //cmd.Parameters.AddWithValue("@Created", row["Created"]);
         //cmd.Parameters.AddWithValue("@Updated", row["Updated"]);
         cmd.Connection = connection;
         cmd.CommandTimeout = 0;
         cmd.CommandType = System.Data.CommandType.Text;
         cmd.CommandText = sQuery;
         cmd.ExecuteNonQuery();
         connection.Close();
         done = true;
     }catch (System.Exception ex){
         message = ex.Message;
     }finally{
         if (connection.State == System.Data.ConnectionState.Open) connection.Close();
     }
     return done;
 }
Example #2
0
 public static bool Delete(System.Data.SqlClient.SqlConnection connection, System.Data.DataRow row, out string message)
 {
     bool done = false;
     message = "";
     try
     {
         connection.Open();
         System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
         string sQuery = "DELETE FROM " + Categories.Table + "\n" +
                         " WHERE CategoryID = @CategoryID";
         cmd.Parameters.AddWithValue("@CategoryID", row["CategoryID"]);
         cmd.Connection = connection;
         cmd.CommandTimeout = 0;
         cmd.CommandType = System.Data.CommandType.Text;
         cmd.CommandText = sQuery;
         cmd.ExecuteNonQuery();
         connection.Close();
         done = true;
     }
     catch (System.Exception ex)
     {
         message = ex.Message;
     }
     finally
     {
         if (connection.State == System.Data.ConnectionState.Open) connection.Close();
     }
     return done;
 }
Example #3
0
 public static bool Exists(System.Data.SqlClient.SqlConnection connection, string category_name, out bool exists, out string message)
 {
     bool ret = false;
     exists = false;
     message = "";
     Guid cat_id = Guid.Empty;
     try
     {
         connection.Open();
         string sQuery = "SELECT CategoryID\n" +
                         "  FROM " + Categories.Table + "\n" +
                         " WHERE CategoryName = @Category";
         System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sQuery);
         cmd.Parameters.AddWithValue("@Category", category_name );
         cmd.Connection = connection;
         object res = cmd.ExecuteScalar();
         if (res != null && !System.Convert.IsDBNull(res)) cat_id = (Guid)res;
         connection.Close();
         exists = (cat_id != Guid.Empty);
         ret = true;
     }
     catch (System.Exception ex)
     {
         message = ex.Message;
     }
     finally
     {
         if (connection.State == System.Data.ConnectionState.Open) connection.Close();
     }
     return ret;
 }
Example #4
0
        /// <summary>
        /// �������� ������ � �� � ���������� �����
        /// </summary>
        /// <param name="connection">��������� � ��</param>
        /// <param name="row">������</param>
        /// <param name="message">�������� ��������� �� ������, ���� ����� ���������� ����</param>
        /// <returns>����� ���������� ������, ���� �� �������� ������; ���� - � ��������� ������</returns>
        public static bool Delete(System.Data.SqlClient.SqlConnection connection, System.Data.DataRow row, /*byte[] image,*/ out string message)
        {
            bool done = false;
            message = "";
            try{
                connection.Open();
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                string sQuery = "IF EXISTS (SELECT DiscountCard\n" +
                                "             FROM Purchases.Receipts\n" +
                                "            WHERE Purchases.Receipts.DiscountCard = @CardID ) \n" +
                                "   UPDATE Purchases.DiscountCards\n" +
                                "      SET Expired = GETDATE()\n" +
                                "    WHERE CardID = @CardID\n" +
                                "ELSE\n" +
                                "   DELETE\n" +
                                "     FROM Purchases.DiscountCards\n" +
                                "    WHERE CardID = @CardID";

                cmd.Parameters.AddWithValue("@CardID", row["CardID"]);
                cmd.Connection = connection;
                cmd.CommandTimeout = 0;
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = sQuery;
                cmd.ExecuteNonQuery();
                connection.Close();
                done = true;
            }catch (System.Exception ex){
                message = ex.Message;
            }finally{
                if (connection.State == System.Data.ConnectionState.Open) connection.Close();
            }
            return done;
        }
Example #5
0
        public static bool ChangeProduct( System.Data.SqlClient.SqlConnection connection,
                                          System.Data.SqlClient.SqlTransaction tran,
                                          object old_product_id, object new_product_id, out string error)
        {
            bool done = false;
            error = "";
            try
            {
                connection.Open();
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                string query = "UPDATE Purchases.ReceiptContents SET ProductID = @NewProduct\n" +
                                "WHERE ProductID = @OldProduct";
                cmd.Parameters.AddWithValue("@NewProduct", new_product_id);
                cmd.Parameters.AddWithValue("@OldProduct", old_product_id);
                cmd.CommandTimeout = 0;
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = query;
                cmd.Connection = connection;
                if (tran != null) cmd.Transaction = tran;
                cmd.ExecuteNonQuery();
                connection.Close();
                done = true;
            }
            catch (System.Exception ex)
            {
                error = ex.Message;
            }
            finally
            {
                if (connection.State == System.Data.ConnectionState.Open) connection.Close();
            }

            return done;
        }
Example #6
0
		/// <summary>
		/// [可重入]打开连接
		/// </summary>
		/// <param name="Connection"></param>
		public static void Open(System.Data.Common.DbConnection Connection)
		{
			if (Connection != null && Connection.State == System.Data.ConnectionState.Closed)
			{
				Connection.Open();
			}
		}
Example #7
0
 public static bool Delete(System.Data.SqlClient.SqlConnection connection,
                           System.Data.SqlClient.SqlTransaction tran,
                           System.Data.DataRow row, out string message)
 {
     bool done = false;
     message = "";
     try
     {
         connection.Open();
         System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
         string sQuery = "DELETE FROM Producer.Products\n" +
                         " WHERE ProductID = @ProductID";
         cmd.Parameters.AddWithValue("@ProductID", row["ProductID"]);
         cmd.Connection = connection;
         if (tran != null) cmd.Transaction = tran;
         cmd.CommandTimeout = 0;
         cmd.CommandType = System.Data.CommandType.Text;
         cmd.CommandText = sQuery;
         cmd.ExecuteNonQuery();
         connection.Close();
         done = true;
     }
     catch (System.Exception ex)
     {
         message = ex.Message;
     }
     finally
     {
         if (connection.State == System.Data.ConnectionState.Open) connection.Close();
     }
     return done;
 }
Example #8
0
        /// <summary>
        /// 构造函数,接收一个SqlServer数据库连接对象SqlConnection
        /// </summary>
        public SqlDbOperHandler(System.Data.SqlClient.SqlConnection _conn)
        {
            conn = _conn;
            dbType = DatabaseType.SqlServer;

            conn.Open();
            cmd = conn.CreateCommand();
            da = new System.Data.SqlClient.SqlDataAdapter();
        }
Example #9
0
 private static void StartService(System.ServiceModel.ServiceHost host, string description)
 {
     host.Open();
     System.Console.WriteLine("Service {0} started.",description);
     foreach (var endpoint in host.Description.Endpoints)
     {
         System.Console.WriteLine("Listening on end point");
         System.Console.WriteLine("Address: {0}, Binding: {1}, Contract: {2}",endpoint.Address.Uri,endpoint.Binding.Name,endpoint.Contract.Name);
         System.Console.WriteLine("");
     }
 }
 private static int GetRightsFromSQL(String query, System.Data.SqlClient.SqlConnection connection)
 {
     int[] results;
     using (var command = new System.Data.SqlClient.SqlCommand(query, connection))
     {
         connection.Open();
         using (var reader = command.ExecuteReader())
         {
             var list = new List<int>();
             while (reader.Read())
                 list.Add(reader.GetInt32(0));
             results = list.ToArray();
         }
         connection.Close();
     }
     return results[0];
 }
Example #11
0
        /// <summary>
        /// Method to insert a new company to database
        /// </summary>
        /// <param name="connection">SQL connection</param>
        /// <param name="row">A row of type System.Data.DataRow - a single company</param>
        /// <param name="message">Error message, if method returns 'false' itself</param>
        /// <returns>Returns 'true' in success, 'false' - in other cases.</returns>
        public static bool Insert(System.Data.SqlClient.SqlConnection connection, ref System.Data.DataRow row, out string message)
        {
            bool done = false;
            message = "";
            try
            {
                connection.Open();
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                string sQuery = "SELECT NEWID() AS NewCompanyID\n" +
                                "  FROM " + Companies.Table;
                cmd.CommandText = sQuery;
                cmd.Connection = connection;
                object res = cmd.ExecuteScalar();
                if (!System.Convert.IsDBNull(res))
                {
                    Guid new_id = (Guid)res;
                    row["CompanyID"] = new_id;

                    sQuery = "INSERT INTO " + Companies.Table + "\n" +
                             "       (CompanyID, ParentID, CompanyName, [Address], WebSite, Phones, Created, Updated)\n" +
                             "VALUES (@CompanyID, @ParentID, @CompanyName, @Address, @WebSite, @Phones, GETDATE(), GETDATE())";
                    cmd.Parameters.AddWithValue("@CompanyID", row["CompanyID"]);
                    cmd.Parameters.AddWithValue("@ParentID", row["ParentID"]);
                    cmd.Parameters.AddWithValue("@CompanyName", row["CompanyName"]);
                    cmd.Parameters.AddWithValue("@Address", row["Address"]);
                    cmd.Parameters.AddWithValue("@WebSite", row["WebSite"]);
                    cmd.Parameters.AddWithValue("@Phones", row["Phones"]);
                    cmd.Connection = connection;
                    cmd.CommandTimeout = 0;
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = sQuery;
                    cmd.ExecuteNonQuery();
                    done = true;
                }
                connection.Close();
            }
            catch (System.Exception ex)
            {
                message = ex.Message;
            }
            finally
            {
                if (connection.State == System.Data.ConnectionState.Open) connection.Close();
            }
            return done;
        }
Example #12
0
 public static bool Exists(System.Data.SqlClient.SqlConnection connection,
                           System.Data.DataRow row,
                           out int products,
                           out int receipts,
                           out string message)
 {
     bool done = false;
     products = 0;
     receipts = 0;
     message = "";
     try
     {
         connection.Open();
         System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
         string sQuery = "SELECT COUNT(DISTINCT p.ProductID) AS prod_amount,\n" +
                         "       COUNT(DISTINCT rc.ReceiptID) AS rec_amount\n" +
                         "  FROM Producer.Products AS p\n" +
                         "  LEFT JOIN Purchases.ReceiptContents AS rc\n"+
                         "    ON rc.ProductID = p.ProductID\n" +
                         " WHERE p.Category = @Category AND\n" +
                         "       p.Type = @Type";
         cmd.Parameters.AddWithValue("@Category", row["Category"]);
         cmd.Parameters.AddWithValue("@Type", row["TypeId"]);
         cmd.Connection = connection;
         cmd.CommandTimeout = 0;
         cmd.CommandType = System.Data.CommandType.Text;
         cmd.CommandText = sQuery;
         System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
         while (dr.Read())
         {
             products = (int)dr[0];
             receipts = (int)dr[1];
         }
         done = true;
     }
     catch (System.Exception ex)
     {
         message = ex.Message;
     }
     finally
     {
         connection.Close();
     }
     return done;
 }
        static void Add(System.Data.SqlClient.SqlConnection conn, string propertyName, string value, SqlParameter[] storedProcParameters)
        {
            try
            {
                SqlCommand cmd = new SqlCommand("sp_addextendedproperty", conn);
				cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@name", SqlDbType.VarChar, 128).Value = propertyName;
                cmd.Parameters.AddWithValue("@value", SqlDbType.DateTime).Value = value;
                cmd.Parameters.AddRange(storedProcParameters);
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
Example #14
0
 /// <summary>
 /// Get new identifier for vendor
 /// </summary>
 /// <param name="connection">SqlConnection object</param>
 /// <param name="message">Error message if error occurs</param>
 /// <returns>Returns empty identifier if error occurs, the new identifier otherwise</returns>
 public static Guid NewId( System.Data.SqlClient.SqlConnection connection, out string message )
 {
     Guid new_id = Guid.Empty;
     message = "";
     try{
         connection.Open();
         string sQuery = "SELECT NEWID() AS NewVendorID\n" +
                         "  FROM " + Vendor.Table;
         System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sQuery);
         cmd.Connection = connection;
         object res = cmd.ExecuteScalar();
         if (!System.Convert.IsDBNull(res))
             new_id = (Guid)res;
         connection.Close();
     }catch(System.Exception ex ){
         message = ex.Message;
     }finally{
         if (connection.State == System.Data.ConnectionState.Open) connection.Close();
     }
     return new_id;
 }
Example #15
0
 // Занесение новой записи в БД о продавце
 public static bool Insert(System.Data.SqlClient.SqlConnection connection, System.Data.DataRow row, out string message)
 {
     bool done = false;
     message = "";
     try{
         connection.Open();
         System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
         string sQuery = "INSERT INTO " + Vendor.Table + "\n" +
                         "            (VendorID, ParentCompany, VendorName, VendorType, Phones, Address, Logo,\n" +
                         "             INoTP, Web, Created, Updated, Deleted)\n" +
                         "     VALUES (@VendorID, @CompanyID, @VendorName, @VendorType, @Phones, @Address, @Logo,\n" +
                         "             @INoTP, @Web, @Created, @Updated, @Deleted)";
         cmd.Parameters.AddWithValue("@VendorID", row["VendorID"]);
         cmd.Parameters.AddWithValue("@CompanyID", row["ParentCompany"]);
         cmd.Parameters.AddWithValue("@VendorName", row["VendorName"]);
         cmd.Parameters.AddWithValue("@VendorType", row["VendorType"]);
         cmd.Parameters.AddWithValue("@Phones", row["Phones"]);
         cmd.Parameters.AddWithValue("@Address", row["Address"]);
         cmd.Parameters.AddWithValue("@Logo", row["Logo"]);
         cmd.Parameters.AddWithValue("@INoTP", row["INoTP"]);
         cmd.Parameters.AddWithValue("@Web", row["Web"]);
         cmd.Parameters.AddWithValue("@Created", row["Created"]);
         cmd.Parameters.AddWithValue("@Updated", row["Updated"]);
         cmd.Parameters.AddWithValue("@Deleted", row["Deleted"]);
         cmd.Connection = connection;
         cmd.CommandTimeout = 0;
         cmd.CommandType = System.Data.CommandType.Text;
         cmd.CommandText = sQuery;
         cmd.ExecuteNonQuery();
         connection.Close();
         done = true;
     }catch (System.Exception ex){
         message = ex.Message;
     }finally{
         if (connection.State == System.Data.ConnectionState.Open) connection.Close();
     }
     return done;
 }
Example #16
0
        public static bool Insert(System.Data.SqlClient.SqlConnection connection, System.Data.DataRow row, out string message)
        {
            bool done = false;
            message = "";
            try{
                connection.Open();
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                string sQuery = "INSERT INTO " + sTable + "\n" +
                                "           (ProductID, ProductName, Category, Type, Maker, Barcode,\n" +
                                "            Comment, Created, Updated, Deleted)\n" +
                                "VALUES (@ProductID, @ProductName, @Category, @Type, @Maker, @Barcode,\n" +
                                "        @Comment, @Created, @Updated, @Deleted)";

                cmd.Parameters.AddWithValue("@ProductID", row["ProductID"]);
                cmd.Parameters.AddWithValue("@ProductName", row["ProductName"]);
                cmd.Parameters.AddWithValue("@Category", row["Category"]);
                cmd.Parameters.AddWithValue("@Type", row["Type"]);
                cmd.Parameters.AddWithValue("@Maker", row["Maker"]);
                cmd.Parameters.AddWithValue("@Barcode", row["Barcode"]);
                cmd.Parameters.AddWithValue("@Comment", row["Comment"]);
                cmd.Parameters.AddWithValue("@Created", row["Created"]);
                cmd.Parameters.AddWithValue("@Updated", row["Updated"]);
                cmd.Parameters.AddWithValue("@Deleted", row["Deleted"]);

                cmd.Connection = connection;
                cmd.CommandTimeout = 0;
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = sQuery;
                cmd.ExecuteNonQuery();
                connection.Close();
                done = true;
            }catch (System.Exception ex){
                message = ex.Message;
            }finally{
                if (connection.State == System.Data.ConnectionState.Open) connection.Close();
            }
            return done;
        }
Example #17
0
        private static bool OpenConnection(System.Data.SqlClient.SqlConnection _SqlConnection)
        {
            bool result = false;
            try
            {
                if (_SqlConnection.State != ConnectionState.Open)
                {
                    _SqlConnection.Open();
                    result = true;
                }
                else
                {
                    result = true;
                }
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                ApplicationLog.WriteError("打开数据库连接错误:" + ex.Message.Trim());
                result = false;
            }

            return result;
        }
Example #18
0
        public void processFile(System.IO.FileInfo finfo)
        {
            char[] separators = { ' ', '"' };
            StreamReader sr = new StreamReader(finfo.Open(FileMode.Open));

            string line;
            while ((line = sr.ReadLine()) != null)
            {
                string[] words = line.Split(separators);

                foreach (string word in words)
                {
                    if (wordFrequency.ContainsKey(word) == false)
                    {
                        wordFrequency[word] = 1;
                    }
                    else
                    {
                        wordFrequency[word] += 1;
                    }
                }
            }
        }
Example #19
0
 /// <summary>
 /// Method to insert new row into the card balance table
 /// </summary>
 /// <param name="connection">Database connection</param>
 /// <param name="row">Database row</param>
 /// <param name="message">If method returns 'false' this parameter contains a detailed error</param>
 /// <returns>'true' if no error occurs, 'false' in other case</returns>
 public static bool Insert(System.Data.SqlClient.SqlConnection connection, System.Data.DataRow row, out string message)
 {
     bool done = false;
     message = "";
     try
     {
         connection.Open();
         System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
         string sQuery = "INSERT INTO " + CardBalance.Table + "\n" +
                         "            (CardID, OverallBalance, DiscountBalance,\n" +
                         "             LastReceiptID, Points)\n" +
                         "     VALUES (@Card, @OverallBalance, @DiscountBalance,\n" +
                         "             @LastReceipt, @Points)\n";
         cmd.Parameters.AddWithValue("@Card", row["CardID"]);
         cmd.Parameters.AddWithValue("@OverallBalance", row["OverallBalance"]);
         cmd.Parameters.AddWithValue("@DiscountBalance", row["DiscountBalance"]);
         cmd.Parameters.AddWithValue("@LastReceipt", row["LastReceiptID"]);
         cmd.Parameters.AddWithValue("@Points", row["Points"]);
         cmd.Connection = connection;
         cmd.CommandTimeout = 0;
         cmd.CommandType = System.Data.CommandType.Text;
         cmd.CommandText = sQuery;
         cmd.ExecuteNonQuery();
         connection.Close();
         done = true;
     }
     catch (System.Exception ex)
     {
         message = ex.Message;
     }
     finally
     {
         if (connection.State == System.Data.ConnectionState.Open) connection.Close();
     }
     return done;
 }
 static void Main(string[] args)
 {
     Start();
     try
     {
         
         Console.WriteLine("Data writed into properties");
         ServiceHost sh = new ServiceHost(typeof());
         sh.AddServiceEndpoint(
             typeof(),
             new WSHttpBinding(),
             "http://localhost/MyClass/Ep1"
             );
         sh.Open();
         Console.WriteLine("Для завершения нажмите <ENTER>\n");
         Console.ReadLine();
         sh.Close();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
   
 }
Example #21
0
        /// <summary>
        /// Method to update a company
        /// </summary>
        /// <param name="connection">SQL connection</param>
        /// <param name="row">A row of type System.Data.DataRow - a single company</param>
        /// <param name="message">Error message, if method returns 'false' itself</param>
        /// <returns>Returns 'true' in success, 'false' - in other cases.</returns>
        public static bool Update(System.Data.SqlClient.SqlConnection connection, System.Data.DataRow row, out string message)
        {
            bool done = false;
            message = "";
            try
            {
                connection.Open();
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                string sQuery = "UPDATE " + Companies.Table + "\n" +
                                "   SET ParentID = @ParentID,\n" +
                                "       CompanyName = @Name,\n" +
                                "       Address = @Address,\n" +
                                "       WebSite = @WebSite,\n" +
                                "       Phones = @Phones,\n" +
                                "       Updated = GETDATE()\n" +
                                " WHERE CompanyID = @CompanyID";

                cmd.Parameters.AddWithValue("@CompanyName", row["CompanyName"]);
                cmd.Parameters.AddWithValue("@ParentID", row["ParentID"]);
                cmd.Parameters.AddWithValue("@Address", row["Address"]);
                cmd.Parameters.AddWithValue("@WebSite", row["WebSite"]);
                cmd.Parameters.AddWithValue("@CompanyID", row["CompanyID"]);
                cmd.Parameters.AddWithValue("@Phones", row["Phones"]);
                cmd.Connection = connection;
                cmd.CommandTimeout = 0;
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = sQuery;
                cmd.ExecuteNonQuery();
                connection.Close();
                done = true;
            }
            catch (System.Exception ex)
            {
                message = ex.Message;
            }
            finally
            {
                if (connection.State == System.Data.ConnectionState.Open) connection.Close();
            }
            return done;
        }
Example #22
0
 public void UpdateSerialPort(System.IO.Ports.SerialPort sPort, string strPortID)
 {
     spUsbOut = sPort;
     txtOutput.Text = strPortID;
     try
     {
         spUsbOut.Open();
     }
     catch (Exception ex)
     {
         txtOutput.Text = ex.ToString();
     }
 }
Example #23
0
        /// <summary>
        /// Helper method with logic to handle opening a database in possibly encrypted format
        /// </summary>
        /// <param name="con">The SQLite connection object</param>
        internal static void OpenDatabase(System.Data.IDbConnection con)
        {
            bool noEncryption = !Program.UseDatabaseEncryption;
            string password = Environment.GetEnvironmentVariable(DB_KEY_ENV_NAME);

            System.Reflection.MethodInfo setPwdMethod = con.GetType().GetMethod("SetPassword", new Type[] { typeof(string) });
            string attemptedPassword;

            if (noEncryption || string.IsNullOrEmpty(password))
                attemptedPassword = null; //No encryption specified, attempt to open without
            else
                attemptedPassword = password; //Encryption specified, attempt to open with

            setPwdMethod.Invoke(con, new object[] { attemptedPassword });

            try
            {
                //Attempt to open in preferred state
                con.Open();
            }
            catch
            {
                try
                {
                    //We can't try anything else without a password
                    if (string.IsNullOrEmpty(password))
                        throw;

                    //Open failed, now try the reverse
                    if (attemptedPassword == null)
                        attemptedPassword = password;
                    else
                        attemptedPassword = null;

                    setPwdMethod.Invoke(con, new object[] { attemptedPassword });
                    con.Open();
                }
                catch
                {
                }

                //If the db is not open now, it won't open
                if (con.State != System.Data.ConnectionState.Open)
                    throw; //Report original error

                //The open method succeeded with the non-default method, now change the password
                System.Reflection.MethodInfo changePwdMethod = con.GetType().GetMethod("ChangePassword", new Type[] { typeof(string) });
                changePwdMethod.Invoke(con, new object[] { noEncryption ? null : password });
            }
        }
Example #24
0
 /// <summary>
 /// Opens the specified host.
 /// </summary>
 /// <param name="host">The host.</param>
 private void OpenHost(System.ServiceModel.ServiceHost host)
 {
     // Open the host
     host.Open();
     // Add the host to the list of opened hosts
     hosts.Add(host);
 }
Example #25
0
 public AutomaticOpenClose(System.Data.SQLite.SQLiteConnection conn)
 {
     connection = conn;
     connection.Open();
 }
Example #26
0
        private static void Reversion(
            System.IO.FileInfo fi
            )
        {
            System.IO.FileStream fs = null ;

            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex
            (
                "^(?'Part1'\\s*\\[\\s*assembly\\s*:.*AssemblyVersion\\s*\\(\\s*\")" +
                "(?'Major'\\d+)\\.(?'Minor'\\d+)\\.(?'Build'\\d+)\\.(?'Rever'\\d+)" +
                "(?'Part2'\"\\s*\\)\\s*].*)"
            ) ;

            System.Text.RegularExpressions.MatchCollection mat ;

            string[]  lines ;
            decimal[] vvals = new decimal [ 4 ] ;

            try
            {
                fs = fi.Open
                (
                    System.IO.FileMode.Open
                ,
                    System.IO.FileAccess.Read
                ,
                    System.IO.FileShare.None
                ) ;

                lines = (new System.IO.StreamReader(fs)).ReadToEnd().Split
                (
                    new char[] { '\n' }
                ,
                    System.StringSplitOptions.RemoveEmptyEntries
                ) ;
            }
            catch ( System.Exception err )
            {
                throw ( new System.Exception ( "Could not read file" , err ) ) ;
            }
            finally
            {
                if ( fs != null )
                {
                    fs.Close() ;
                    fs = null ;
                }
            }

            for ( int runner = 0 ; runner < lines.Length ; runner++ )
            {
                mat = reg.Matches ( lines [ runner ] ) ;

                if ( mat.Count == 1 )
                {
                    try
                    {
                        checked
                        {
                            vvals [ 0 ] = decimal.Parse ( mat [ 0 ].Groups [ "Major" ].Value ) ;
                            vvals [ 1 ] = decimal.Parse ( mat [ 0 ].Groups [ "Minor" ].Value ) ;
                            vvals [ 2 ] = decimal.Parse ( mat [ 0 ].Groups [ "Build" ].Value ) ;
                            vvals [ 3 ] = decimal.Parse ( mat [ 0 ].Groups [ "Rever" ].Value ) ;
                        }

                        if ( ( vvals [ 0 ] < ushort.MaxValue ) &&
                             ( vvals [ 1 ] < ushort.MaxValue ) &&
                             ( vvals [ 2 ] < ushort.MaxValue ) &&
                             ( vvals [ 3 ] < ushort.MaxValue ) )
                        {
                            vvals [ 3 ] += 1 ;

                            if ( vvals [ 3 ] >= ushort.MaxValue )
                            {
                                vvals [ 3 ] = 0 ;
                                vvals [ 2 ] += 1 ;

                                if ( vvals [ 2 ] >= ushort.MaxValue )
                                {
                                    vvals [ 2 ] = 0 ;
                                    vvals [ 1 ] += 1 ;

                                    if ( vvals [ 1 ] >= ushort.MaxValue )
                                    {
                                        vvals [ 1 ] = 0 ;
                                        vvals [ 0 ] += 1 ;

                                        if ( vvals [ 0 ] >= ushort.MaxValue )
                                        {
                                            System.Console.WriteLine
                                            (
                                                "AssemblyVersion hit the max: " + lines [ runner ]
                                            ) ;

                                            continue ;
                                        }
                                    }
                                }
                            }

                            lines [ runner ] = string.Format
                            (
                               "{0}{1}.{2}.{3}.{4}{5}"
                            ,
                                mat [ 0 ].Groups [ "Part1" ].Value
                            ,
                                vvals [ 0 ]
                            ,
                                vvals [ 1 ]
                            ,
                                vvals [ 2 ]
                            ,
                                vvals [ 3 ]
                            ,
                                mat [ 0 ].Groups [ "Part2" ].Value
                            ) ;
                        }
                        else
                        {
                            System.Console.WriteLine ( "Invalid AssemblyVersion entry: " + lines [ runner ] ) ;
                        }
                    }
                    catch
                    {
                        System.Console.WriteLine ( "Invalid AssemblyVersion entry: " + lines [ runner ] ) ;
                    }
                }
            }

            try
            {
                fs = fi.Open
                (
                    System.IO.FileMode.Create
                ,
                    System.IO.FileAccess.Write
                ,
                    System.IO.FileShare.None
                ) ;

                using ( System.IO.StreamWriter sw = new System.IO.StreamWriter ( fs ) )
                {
                    for ( int runner = 0 ; runner < lines.Length ; runner++ )
                    {
                        sw.WriteLine ( lines [ runner ].Trim ( new char [] { '\r' } ) ) ;
                    }
                }
            }
            catch ( System.Exception err )
            {
                throw ( new System.Exception ( "Could not write file" , err ) ) ;
            }
            finally
            {
                if ( fs != null )
                {
                    fs.Close() ;
                    fs = null ;
                }
            }
        }
Example #27
0
		public static void Main(string[] args) {
			
			DBConnection _con = new DBConnection_PostgreSQL(
				"Server=127.0.0.1;Port=5432;User ID=postgres;Password=passpub;Database=OGen-NTier_UTs;", 
				#if !NET_1_1
				System.Configuration.ConfigurationManager.AppSettings["DBLogfile"]
				#else
				System.Configuration.ConfigurationSettings.AppSettings["DBLogfile"]
				#endif
			);
			_con.Open();
			_con.Transaction.Begin();
			try {
				
				#region _con.Execute_SQLQuery_returnDataTable(...);
				DataTable _datatable = _con.Execute_SQLQuery_returnDataTable("select * from \"User\"");
				for (int r = 0; r < _datatable.Rows.Count; r++) {
					if (r == 0) {
						for (int c = 0; c < _datatable.Columns.Count; c++) {
							Console.Write("{0}\t", _datatable.Columns[c].Caption);
						}
						Console.WriteLine();
					}
					for (int c = 0; c < _datatable.Columns.Count; c++) {
						Console.Write("{0}\t", _datatable.Rows[r][c]);
					}
					Console.WriteLine();
				}
				#endregion
				
				#region ...; _con.getTables(); ...
				string[] _dbs = _con.getDBs();
				for (int d = 0; d < _dbs.Length; d++) {
					Console.WriteLine("#{0}/{1} - {2}", d + 1, _dbs.Length, _dbs[d]);
				}
				
				DBTableField[] _fields;
				DBTable[] _tables = _con.getTables();
				for (int t = 0; t < _tables.Length; t++) {
					Console.WriteLine(
						"\t#{0}/{1} - {2}", 
						t + 1, 
						_tables.Length, 
						_tables[t].Name
					);

					_fields = _con.getTableFields(_tables[t].Name);
					for (int f = 0; f < _fields.Length; f++) {
						Console.WriteLine(
							"\t\t#{0}/{1} - {2}", 
							f + 1, 
							_fields.Length, 
							_fields[f].Name
						);
					}
				}
				#endregion
				
				_con.Transaction.Commit();
			} catch (Exception _ex) {
				Console.WriteLine(_ex.Message);
				_con.Transaction.Rollback();
			} 
			_con.Transaction.Terminate();
			_con.Close();
			//_con.Dispose();
			
			Console.Write("Press any key to continue . . . ");
			#if !NET_1_1
			Console.ReadKey(true);
			#else
			Console.ReadLine();
			#endif
		}
Example #28
0
        /// <summary>
        /// ���������� ������ � �� � ���������� �����
        /// </summary>
        /// <param name="connection">��������� � ��</param>
        /// <param name="row">������</param>
        /// <param name="message">�������� ��������� �� ������, ���� ����� ���������� ����</param>
        /// <returns>����� ���������� ������, ���� �� �������� ������; ���� - � ��������� ������</returns>
        public static bool Update(System.Data.SqlClient.SqlConnection connection, System.Data.DataRow row, /*byte[] image,*/ out string message)
        {
            bool done = false;
            message = "";
            try{
                connection.Open();
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                string sQuery = "UPDATE " + DiscountCard.Table + "\n" +
                                "   SET CardOwner = @CardOwner, VendorID = @VendorID, CardName = @CardName,\n" +
                                "       CardNumber = @CardNumber, DiscountPercent = @DiscountPercent, DiscountType = @DiscountType,\n" +
                                "       Since = @Since, Added = @Added, Expired = @Expired\n" +
                                " WHERE CardID = @CardID";

                cmd.Parameters.AddWithValue("@CardID", row["CardID"]);
                cmd.Parameters.AddWithValue("@CardOwner", row["CardOwner"]);
                cmd.Parameters.AddWithValue("@VendorID", row["VendorID"]);
                cmd.Parameters.AddWithValue("@CardName", row["CardName"]);
                cmd.Parameters.AddWithValue("@CardNumber", row["CardNumber"]);
                cmd.Parameters.AddWithValue("@DiscountPercent", row["DiscountPercent"]);
                cmd.Parameters.AddWithValue("@DiscountType", row["DiscountType"]);
                cmd.Parameters.AddWithValue("@Since", row["Since"]);
                cmd.Parameters.AddWithValue("@Added", row["Added"]);
                cmd.Parameters.AddWithValue("@Expired", row["Expired"]);
                cmd.Connection = connection;
                cmd.CommandTimeout = 0;
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = sQuery;
                cmd.ExecuteNonQuery();
                connection.Close();
                done = true;
            }catch (System.Exception ex){
                message = ex.Message;
            }finally{
                if (connection.State == System.Data.ConnectionState.Open) connection.Close();
            }
            return done;
        }
Example #29
0
        /// <summary>
        /// Helper method with logic to handle opening a database in possibly encrypted format
        /// </summary>
        /// <param name="con">The SQLite connection object</param>
        internal static void OpenDatabase(System.Data.IDbConnection con)
        {
            bool noEncryption = !Program.UseDatabaseEncryption;
            string password = Environment.GetEnvironmentVariable(DB_KEY_ENV_NAME);

            System.Reflection.MethodInfo setPwdMethod = con.GetType().GetMethod("SetPassword", new Type[] { typeof(string) });
            string attemptedPassword;

            if (noEncryption || string.IsNullOrEmpty(password))
                attemptedPassword = null; //No encryption specified, attempt to open without
            else
                attemptedPassword = password; //Encryption specified, attempt to open with

            if (setPwdMethod != null)
                setPwdMethod.Invoke(con, new object[] { attemptedPassword });

            try
            {
                //Attempt to open in preferred state
                con.Open();

                // Do a dummy query to make sure we have a working db
                using (var cmd = con.CreateCommand())
                {
                    cmd.CommandText = "SELECT COUNT(*) FROM SQLITE_MASTER";
                    cmd.ExecuteScalar();
                }
            }
            catch
            {
                try
                {
                    //We can't try anything else without a password
                    if (string.IsNullOrEmpty(password))
                        throw;

                    //Open failed, now try the reverse
                    if (attemptedPassword == null)
                        attemptedPassword = password;
                    else
                        attemptedPassword = null;

                    con.Close();
                    setPwdMethod.Invoke(con, new object[] { attemptedPassword });
                    con.Open();

                    // Do a dummy query to make sure we have a working db
                    using (var cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "SELECT COUNT(*) FROM SQLITE_MASTER";
                        cmd.ExecuteScalar();
                    }
                }
                catch
                {
                    try { con.Close(); }
                    catch { }
                }

                //If the db is not open now, it won't open
                if (con.State != System.Data.ConnectionState.Open)
                    throw; //Report original error

                //The open method succeeded with the non-default method, now change the password
                System.Reflection.MethodInfo changePwdMethod = con.GetType().GetMethod("ChangePassword", new Type[] { typeof(string) });
                changePwdMethod.Invoke(con, new object[] { noEncryption ? null : password });
            }
        }
Example #30
0
 /// <summary>
 /// ��������� ����� ������ � �� � ���������� �����
 /// </summary>
 /// <param name="connection">��������� � ��</param>
 /// <param name="row">������</param>
 /// <param name="message">�������� ��������� �� ������, ���� ����� ���������� ����</param>
 /// <returns>����� ���������� ������, ���� �� �������� ������; ���� - � ��������� ������</returns>
 public static bool Insert(System.Data.SqlClient.SqlConnection connection, System.Data.DataRow row, out string message)
 {
     bool done = false;
     message = "";
     try{
         connection.Open();
         System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
         string sQuery = "INSERT INTO " + DiscountCard.Table + "\n" +
                         "            (CardOwner, CompanyID, VendorID, CardName,\n" +
                         "             CardNumber, DiscountPercent, DiscountType,\n" +
                         "             Since, Added, Expired)\n" +
                         "     VALUES (@CardOwner, @CompanyID, @VendorID, @CardName,\n" +
                         "             @CardNumber, @DiscountPercent, @DiscountType,\n" +
                         "             @Since, @Added, @Expired)";
         cmd.Parameters.AddWithValue("@CardOwner", row["CardOwner"]);
         cmd.Parameters.AddWithValue("@CompanyID", row["CompanyID"]);
         cmd.Parameters.AddWithValue("@VendorID", row["VendorID"]);
         cmd.Parameters.AddWithValue("@CardName", row["CardName"]);
         cmd.Parameters.AddWithValue("@CardNumber", row["CardNumber"]);
         cmd.Parameters.AddWithValue("@DiscountPercent", row["DiscountPercent"]);
         cmd.Parameters.AddWithValue("@DiscountType", row["DiscountType"]);
         cmd.Parameters.AddWithValue("@Since", row["Since"]);
         cmd.Parameters.AddWithValue("@Added", row["Added"]);
         cmd.Parameters.AddWithValue("@Expired", row["Expired"]);
         cmd.Connection = connection;
         cmd.CommandTimeout = 0;
         cmd.CommandType = System.Data.CommandType.Text;
         cmd.CommandText = sQuery;
         cmd.ExecuteNonQuery();
         connection.Close();
         done = true;
     }catch (System.Exception ex){
         message = ex.Message;
     }finally{
         if (connection.State == System.Data.ConnectionState.Open) connection.Close();
     }
     return done;
 }