当前位置: 首页>>代码示例>>C#>>正文


C# System.Data.SqlClient.SqlConnection.BeginTransaction方法代码示例

本文整理汇总了C#中System.Data.SqlClient.SqlConnection.BeginTransaction方法的典型用法代码示例。如果您正苦于以下问题:C# System.Data.SqlClient.SqlConnection.BeginTransaction方法的具体用法?C# System.Data.SqlClient.SqlConnection.BeginTransaction怎么用?C# System.Data.SqlClient.SqlConnection.BeginTransaction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Data.SqlClient.SqlConnection的用法示例。


在下文中一共展示了System.Data.SqlClient.SqlConnection.BeginTransaction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AddNewVirtualDealer

        /// <summary>
        /// 
        /// </summary>
        /// <param name="objVirtualDealer"></param>
        /// <returns></returns>
        internal string AddNewVirtualDealer(Business.VirtualDealer objVirtualDealer)
        {
            string result = "-1";
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(DBConnection.DBConnection.Connection);
            System.Data.SqlClient.SqlTransaction trans = null;
            DSTableAdapters.VirtualDealerTableAdapter virtualDealerAdap = new DSTableAdapters.VirtualDealerTableAdapter();
            DSTableAdapters.VirtualDealerConfigTableAdapter dealerConfigAdap = new DSTableAdapters.VirtualDealerConfigTableAdapter();
            DSTableAdapters.IVirtualDealerTableAdapter iVirtualDealerAdap = new DSTableAdapters.IVirtualDealerTableAdapter();
            try
            {
                conn.Open();
                trans = conn.BeginTransaction();

                virtualDealerAdap.Connection = conn;
                virtualDealerAdap.Transaction = trans;
                int id = int.Parse(virtualDealerAdap.AddNewVirtualDealer(objVirtualDealer.Name, "").ToString());
                result = id.ToString();
                if (id == -1)
                {
                    throw new Exception("Data error");
                }

                dealerConfigAdap.Connection = conn;
                dealerConfigAdap.Transaction = trans;
                DateTime DateValue = DateTime.Parse("1753-01-01 00:00:00.000");
                dealerConfigAdap.Insert(null, "Profit max pip", id, "VD01", -1, "NaN", objVirtualDealer.ProfitMaxPip.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Loss max pip", id, "VD02", -1, "NaN", objVirtualDealer.LossMaxPip.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Min volume", id, "VD03", -1, "NaN", objVirtualDealer.StartVolume.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Max volume", id, "VD04", -1, "NaN", objVirtualDealer.EndVolume.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Delay", id, "VD05", -1, "NaN", objVirtualDealer.Delay.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Additional pip", id, "VD06", -1, "NaN", objVirtualDealer.AdditionalPip.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "Mode", id, "VD07", -1, "NaN", objVirtualDealer.Mode.ToString(), DateValue);
                dealerConfigAdap.Insert(null, "IsEnable", id, "VD08", objVirtualDealer.IsEnable ? 1 : 0, "NaN", "NaN", DateValue);
                dealerConfigAdap.Insert(null, "IsLimitAuto", id, "VD09", objVirtualDealer.IsLimitAuto ? 1 : 0, "NaN", "NaN", DateValue);
                dealerConfigAdap.Insert(null, "IsStopAuto", id, "VD10", objVirtualDealer.IsStopAuto ? 1 : 0, "NaN", "NaN", DateValue);
                dealerConfigAdap.Insert(null, "IsStopSlippage", id, "VD11", objVirtualDealer.IsStopSlippage ? 1 : 0, "NaN", "NaN", DateValue);
                dealerConfigAdap.Insert(null, "GroupCondition", id, "VD12", -1, objVirtualDealer.GroupCondition, "NaN", DateValue);
                dealerConfigAdap.Insert(null, "SymbolCodition", id, "VD13", -1, objVirtualDealer.SymbolCondition, "NaN", DateValue);
                iVirtualDealerAdap.Connection = conn;
                iVirtualDealerAdap.Transaction = trans;
                for (int i = 0; i < objVirtualDealer.IVirtualDealer.Count; i++)
                {
                    iVirtualDealerAdap.Insert(objVirtualDealer.IVirtualDealer[i].InvestorGroupID, objVirtualDealer.IVirtualDealer[i].SymbolID, id);
                }
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                return "Data error";
            }
            finally
            {
                virtualDealerAdap.Connection.Close();
                dealerConfigAdap.Connection.Close();
                iVirtualDealerAdap.Connection.Close();
                conn.Close();
            }
            return result;
        }
开发者ID:ngthanhducit,项目名称:TradingServer1502,代码行数:65,代码来源:DBWVirtualDealer.cs

示例2: Persist

        public void Persist(IEnumerable<TradeRecord> trades)
        {
            using (var connection = new System.Data.SqlClient.SqlConnection("Data Source=(local);Initial Catalog=TradeDatabase;Integrated Security=True;"))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    foreach (var trade in trades)
                    {
                        var command = connection.CreateCommand();
                        command.Transaction = transaction;
                        command.CommandType = System.Data.CommandType.StoredProcedure;
                        command.CommandText = "dbo.insert_trade";
                        command.Parameters.AddWithValue("@sourceCurrency", trade.SourceCurrency);
                        command.Parameters.AddWithValue("@destinationCurrency", trade.DestinationCurrency);
                        command.Parameters.AddWithValue("@lots", trade.Lots);
                        command.Parameters.AddWithValue("@price", trade.Price);

                        command.ExecuteNonQuery();
                    }

                    transaction.Commit();
                }
                connection.Close();
            }

            logger.LogInfo("{0} trades processed", trades.Count());
        }
开发者ID:aleksandrzak-rafal,项目名称:AdaptiveCode,代码行数:28,代码来源:AdoNetTradeStorage.cs

示例3: WithoutUseNHSqlDataProviderWorkProperly

		public void WithoutUseNHSqlDataProviderWorkProperly()
		{
			var createTable = "CREATE TABLE TryDate([Id] [int] IDENTITY(1,1) NOT NULL,[MyDate] [date] NOT NULL)";
			var dropTable = "DROP TABLE TryDate";
			var insertTable = "INSERT INTO TryDate([MyDate]) VALUES(@p0)";
			using(var sqlConnection = new System.Data.SqlClient.SqlConnection(cfg.Properties[Cfg.Environment.ConnectionString]))
			{
				sqlConnection.Open();
				using (var tx = sqlConnection.BeginTransaction())
				{
					var command = sqlConnection.CreateCommand();
					command.Transaction = tx;
					command.CommandText = createTable;
					command.ExecuteNonQuery();
					tx.Commit();
				}

				try
				{
					using (var tx = sqlConnection.BeginTransaction())
					{
						var command = sqlConnection.CreateCommand();
						command.Transaction = tx;
						command.CommandText = insertTable;
						var dateParam = command.CreateParameter();
						dateParam.ParameterName = "@p0";
						dateParam.DbType = DbType.Date;
						dateParam.Value = DateTime.MinValue.Date;
						command.Parameters.Add(dateParam);
						command.ExecuteNonQuery();
						tx.Commit();
					}
				}
				finally
				{
					using (var tx = sqlConnection.BeginTransaction())
					{
						var command = sqlConnection.CreateCommand();
						command.Transaction = tx;
						command.CommandText = dropTable;
						command.ExecuteNonQuery();
						tx.Commit();
					}					
				}
			}

		}
开发者ID:NikGovorov,项目名称:nhibernate-core,代码行数:47,代码来源:SampleTest.cs

示例4: ProcessCheck

        public double ProcessCheck(double value)
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
            string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["HuberTrackerConnection"].ToString();
            conn.ConnectionString = connectionstring;
            conn.Open();
            System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand();
            comm.Connection = conn;

            System.Data.SqlClient.SqlTransaction trans;
            trans = conn.BeginTransaction();
            comm.Transaction = trans;

            string sql = "update huber_accounts set balance = balance - @balance where accountid = 1";

            comm.CommandText = sql;
            comm.Parameters.AddWithValue("@balance", value);

            comm.ExecuteNonQuery();

            sql = "select balance from huber_accounts where accountid = 1";

            comm.Parameters.Clear();
            comm.CommandText = sql;
            object result = comm.ExecuteScalar();

            if (Convert.ToDouble(result) < .01)
            {
                trans.Rollback();
                conn.Close();

            }
            else
            {
                trans.Commit();
                conn.Close();

            }
            return Convert.ToDouble(result);
        }
开发者ID:jasonhuber,项目名称:CIS407_2012FALLB,代码行数:40,代码来源:week5.aspx.cs

示例5: btnProcess_Click

        private void btnProcess_Click(object sender, EventArgs e)
        {
            System.Data.SqlClient.SqlConnection connection =
                new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TransactionProcessingTest.Properties.Settings.devrystudentsp10ConnectionString"].ConnectionString);
            connection.Open();
            System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();
            command.Connection = connection;
            System.Data.SqlClient.SqlTransaction transaction = connection.BeginTransaction(IsolationLevel.RepeatableRead);
            command.Transaction = transaction;
            string sql = "";
            bool isGood = true;
            for (int i = 0; i < int.Parse(txtTimes.Text); i++)
            {
                sql = "update huber_bankcustomers set balance = balance - @balance where customerid = @customerid";
                command.Parameters.Clear();
                command.Parameters.AddWithValue("@balance",int.Parse(txtAmount.Text));
                command.Parameters.AddWithValue("@customerid",txtCustomerId.Text);
                command.CommandText = sql;
                command.ExecuteNonQuery();

                sql = "select balance from huber_bankcustomers where customerid = @customerid";
                command.Parameters.Clear();
                command.Parameters.AddWithValue("@customerid", txtCustomerId.Text);
                command.CommandText = sql;
                if (int.Parse(command.ExecuteScalar().ToString()) < 0)
                {
                    transaction.Rollback();
                    isGood = false;
                    i = int.Parse(txtTimes.Text);
                    MessageBox.Show("Sorry that transaction was rolled back. The customer is not allowed to go below a 0 balance.");
                }

            }
            if (isGood)
            {
                transaction.Commit();
            }
            LoadGrid();
        }
开发者ID:jasonhuber,项目名称:2010Spring_CIS407,代码行数:39,代码来源:Form1.cs

示例6: InsertRequest

        public int InsertRequest(string companyName, string customerNumber, string firstName, string lastName,
            string email, string phone, string title, DateTime timestamp, string locale)
        {
            var connection = new System.Data.SqlClient.SqlConnection(_connString);
            connection.Open();

            using (IDbTransaction transaction = connection.BeginTransaction())
            {
                const string sqlStr = "INSERT INTO [dbo].[Requests] ([CompanyName], [CustomerNumber], [FirstName], " +
                                      "[LastName], [Email], [Phone], [Title], [Timestamp], [Locale]) VALUES " +
                                      "(@CompanyName, @CustomerNumber, @FirstName, @LastName, @Email, @Phone, @Title, @Timestamp, @Locale);" +
                                      "SELECT @@IDENTITY";

                IDbCommand cmd = connection.CreateCommand();
                cmd.CommandText = sqlStr;
                var parameter = cmd.CreateParameter();
                parameter.ParameterName = "CompanyName";
                parameter.DbType = DbType.String;
                parameter.Value = companyName;
                cmd.Parameters.Add(parameter);
                parameter = cmd.CreateParameter();
                parameter.ParameterName = "CustomerNumber";
                parameter.DbType = DbType.String;
                parameter.Value = customerNumber;
                cmd.Parameters.Add(parameter);
                parameter = cmd.CreateParameter();
                parameter.ParameterName = "FirstName";
                parameter.DbType = DbType.String;
                parameter.Value = firstName;
                cmd.Parameters.Add(parameter);
                parameter = cmd.CreateParameter();
                parameter.ParameterName = "LastName";
                parameter.DbType = DbType.String;
                parameter.Value = lastName;
                cmd.Parameters.Add(parameter);
                parameter = cmd.CreateParameter();
                parameter.ParameterName = "Email";
                parameter.DbType = DbType.String;
                parameter.Value = email;
                cmd.Parameters.Add(parameter);
                parameter = cmd.CreateParameter();
                parameter.ParameterName = "Phone";
                parameter.DbType = DbType.String;
                parameter.Value = phone;
                cmd.Parameters.Add(parameter);
                parameter = cmd.CreateParameter();
                parameter.ParameterName = "Title";
                parameter.DbType = DbType.String;
                parameter.Value = title;
                cmd.Parameters.Add(parameter);
                parameter = cmd.CreateParameter();
                parameter.ParameterName = "Timestamp";
                parameter.DbType = DbType.DateTime;
                parameter.Value = timestamp;
                cmd.Parameters.Add(parameter);
                parameter = cmd.CreateParameter();
                parameter.ParameterName = "Locale";
                parameter.DbType = DbType.String;
                parameter.Value = locale;
                cmd.Parameters.Add(parameter);
                transaction.Commit();

                return Convert.ToInt32(cmd.ExecuteScalar());
            }
        }
开发者ID:CoolCriSyS,项目名称:ProductManagement,代码行数:65,代码来源:DataAccess.cs

示例7: CreateSyncRepository

        public override void CreateSyncRepository()
        {
            if (_ConnectionString == null) throw new InvalidOperationException();

            IDbConnection conn = new System.Data.SqlClient.SqlConnection(_ConnectionString);
            conn.Open();

            IDbTransaction t = conn.BeginTransaction();

            IDbCommand com = conn.CreateCommand();
            com.Transaction = t;

            StringBuilder createLogin = new StringBuilder();
            createLogin.Append("CREATE LOGIN ").Append(_AccountUsername).Append(" WITH PASSWORD='").Append(_AccountPassword).Append("'");
            com.CommandText = createLogin.ToString();
            com.ExecuteNonQuery();

            StringBuilder createUser = new StringBuilder();
            createUser.Append("CREATE USER ").Append(_AccountUsername).Append(" WITH DEFAULT_SCHEMA=").Append(_AccountUsername);
            com.CommandText = createUser.ToString();
            com.ExecuteNonQuery();

            StringBuilder createSchema = new StringBuilder();
            createSchema.Append("CREATE SCHEMA ").Append(_AccountUsername).Append(" AUTHORIZATION ").Append(_AccountUsername);
            com.CommandText = createSchema.ToString();
            com.ExecuteNonQuery();

            StringBuilder createSyncItem = new StringBuilder();
            createSyncItem.Append("CREATE TABLE ").Append(_AccountUsername).Append(".SyncItem").
                Append("(SyncID INT PRIMARY KEY IDENTITY, SyncFK INT, ClassID nvarchar(255), HashCode nvarchar(32), ").
                Append("SyncGuid UNIQUEIDENTIFIER, RowGuid UNIQUEIDENTIFIER)");
            com.CommandText = createSyncItem.ToString();
            com.ExecuteNonQuery();

            StringBuilder createFieldState = new StringBuilder();
            createFieldState.Append("CREATE TABLE ").Append(_AccountUsername).Append(".FieldState").
                Append("(SyncFK INT, FieldName nvarchar(255), HashCode nvarchar(32), ").
                Append("RowGuid UNIQUEIDENTIFIER, PRIMARY KEY (SyncFK, FieldName))");
            com.CommandText = createFieldState.ToString();
            com.ExecuteNonQuery();

            t.Commit();

            conn.Close();
            conn.Dispose();
        }
开发者ID:Tobias-Schneider,项目名称:DiversityMobile,代码行数:46,代码来源:SyncDBManager.cs

示例8: Open

 public void Open(bool transaction)
 {
     connection = new System.Data.SqlClient.SqlConnection(connstring);
     connection.Open();
     comm = new System.Data.SqlClient.SqlCommand("", connection);
     if (transaction)
     {
         comm.Transaction = connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
     }
 }
开发者ID:xescrp,项目名称:breinstormin,代码行数:10,代码来源:SQLServerEngine.cs

示例9: BeginTransaction

 public override void BeginTransaction(string connectionString)
 {
     System.Data.SqlClient.SqlConnection oSqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
     oSqlConnection.Open();
     _SqlTransaction = oSqlConnection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
 }
开发者ID:kdmerkle,项目名称:Swimomatic,代码行数:6,代码来源:SwimomaticServiceProviderSQL.cs

示例10: CreateCustomer

        public void CreateCustomer(CustomerInfo customerInfo)
        {
            //FYI: Validation check
            if (customerInfo.FirstName == null)
            {
                Console.WriteLine("Error: First Name is required");
                return;
            }

            if (customerInfo.LastName == null)
            {
                Console.WriteLine("Error: Last Name is required");
                return;
            }

            if (customerInfo.Email == null)
            {
                Console.WriteLine("Error: Email is required");
                return;
            }

            bool isEmail = Regex.IsMatch(customerInfo.Email,
                @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z",
                RegexOptions.IgnoreCase);

            if (!isEmail)
            {
                Console.WriteLine("Error: Email is not valid");
                return;
            }

            //FYI: Insert user to db.
            using (var connection = new System.Data.SqlClient.SqlConnection("DataSource=(local);Initial Catalog=CustomerDatabase;Integrated Security=True"))
            {
                connection.Open();
                using (var transaction = connection.BeginTransaction())
                {
                    var command = connection.CreateCommand();
                    command.Transaction = transaction;
                    command.CommandType = System.Data.CommandType.StoredProcedure;
                    command.CommandText = "dbo.usp_InsertCustomer";
                    command.Parameters.AddWithValue("@FirstName", customerInfo.FirstName);
                    command.Parameters.AddWithValue("@LastName", customerInfo.LastName);
                    command.Parameters.AddWithValue("@Email", customerInfo.Email);
                    command.ExecuteNonQuery();

                    transaction.Commit();
                }
                connection.Close();
            }

            //FYI: Send email
            var client = new SmtpClient
            {
                Port = 587,
                Host = "smtp.gmail.com",
                EnableSsl = true,
                Timeout = 10000,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new System.Net.NetworkCredential("[email protected]", "password")
            };

            var mm = new MailMessage("[email protected]", customerInfo.Email, "New Account", "Congratulations!")
            {
                BodyEncoding = Encoding.UTF8,
                DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
            };

            client.Send(mm);
        }
开发者ID:ChrisGatzo,项目名称:SOLID-Principles,代码行数:71,代码来源:CustomerService.cs

示例11: FuctionChangePassword

        public static bool FuctionChangePassword(string _emplId, string _password, string _key)
        {

            bool ret = false;
            string queryRun = @"";
            string newPassword = ClassCryptography.TripleDESEncrypt(_password, _key, true);

            queryRun = string.Format(@"UPDATE HROS_TSYSUSER SET PWPASS = @PWPASS, UPDATEPASSDATE = CONVERT(NVARCHAR, GETDATE(), 23), UPDATEPASSTIME = CONVERT(NVARCHAR, GETDATE(), 108) WHERE PWEMPLOYEE = @EMPLID", _emplId);

            using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(DatabaseConfig.ServerConStr))
            {
                System.Data.SqlClient.SqlTransaction tranLocal = null;
                try
                {
                    con.Open();
                    tranLocal = con.BeginTransaction("UPDATEPASS");
                    using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand())
                    {
                        command.Connection = con;
                        command.Transaction = tranLocal;
                        command.CommandType = CommandType.Text;
                        command.CommandText = @queryRun;

                        command.Parameters.AddWithValue(@"PWPASS", newPassword);
                        command.Parameters.AddWithValue(@"EMPLID", _emplId);

                        if (command.ExecuteNonQuery() > 0)
                        {
                            try
                            {
                                tranLocal.Commit();
                                ret = true;
                            }
                            catch (Exception)
                            {
                                ret = false;
                            }
                        }
                        else
                        {
                            ret = false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        tranLocal.Rollback();                        
                    }
                    catch (Exception) { }
                    ret = false;
                }
                finally
                {
                    con.Close();
                }            
            }

            return ret;
        }
开发者ID:SUPCDEV,项目名称:HROS,代码行数:61,代码来源:ClassCryptography.cs

示例12: AddNewAgent

        /// <summary>
        /// 
        /// </summary>
        /// <param name="AgentGroupID"></param>
        /// <param name="Name"></param>
        /// <returns></returns>
        internal int AddNewAgent(Business.Agent agent)
        {
            int idAgent = -1;
            System.Data.SqlClient.SqlTransaction trans = null;
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(DBConnection.DBConnection.Connection);
            DSTableAdapters.AgentTableAdapter adapAgent = new DSTableAdapters.AgentTableAdapter();
            DSTableAdapters.IAgentGroupTableAdapter adapIAgentGroup = new DSTableAdapters.IAgentGroupTableAdapter();
            try
            {
                conn.Open();
                trans                                          = conn.BeginTransaction();
                adapAgent.Connection                           = conn;
                adapAgent.Transaction                          = trans;

                adapIAgentGroup.Connection                     = conn;
                adapIAgentGroup.Transaction                    = trans;

                #region Create Investor
                Business.Investor investor                     = new Business.Investor();
                investor.InvestorStatusID                      = -1;
                investor.InvestorGroupInstance                 = new Business.InvestorGroup();
                investor.InvestorGroupInstance.InvestorGroupID = -1;
                investor.AgentID                               = string.Empty;
                investor.Balance                               = 0;
                investor.Credit                                = 0;
                investor.Code                                  = agent.Code;
                investor.PrimaryPwd                            = agent.Pwd;
                investor.ReadOnlyPwd                           = "";
                investor.PhonePwd                              = "";
                investor.IsDisable                             = true;
                investor.TaxRate                               = 0;
                investor.Leverage                              = 0;
                //Investor Profile
                DateTime registerDay                           = new DateTime();
                investor.Address                               = "";
                investor.Phone                                 = "";
                investor.City                                  = "";
                investor.Country                               = "";
                investor.Email                                 = "";
                investor.ZipCode                               = "";
                investor.RegisterDay                           = registerDay;
                investor.Comment                               = "";
                investor.State                                 = "";
                investor.NickName                              = "";
                investor.AllowChangePwd                        = false;
                investor.ReadOnly                              = false;
                investor.SendReport                            = false;
                #endregion

                int idInvestor = TradingServer.Facade.FacadeAddNewInvestor(investor);
                if (idInvestor < 1)
                {
                    throw new Exception("Data error");
                }

                agent.InvestorID = idInvestor;
                if (agent.AgentGroupID == -1)
                {
                    idAgent = int.Parse(adapAgent.AddNewAgent(null, agent.Name, agent.InvestorID, agent.Comment, agent.IsDisable, agent.IsIpFilter, agent.IpForm, agent.IpTo, agent.GroupCondition).ToString());
                }
                else idAgent = int.Parse(adapAgent.AddNewAgent(agent.AgentGroupID, agent.Name, agent.InvestorID, agent.Comment, agent.IsDisable, agent.IsIpFilter, agent.IpForm, agent.IpTo, agent.GroupCondition).ToString());
                if (idAgent < 1)
                {
                    throw new Exception("Data error");
                }

                List<int> listInvestorGroupIDs = new List<int>();
                listInvestorGroupIDs = agent.MakeListIAgentGroupManager(agent.GroupCondition);
                int count = listInvestorGroupIDs.Count;
                for (int i = 0; i < count; i++)
                {
                    int idIAgentGroup = int.Parse(adapIAgentGroup.AddIAgentGroup(idAgent, listInvestorGroupIDs[i]).ToString());
                    if (idIAgentGroup < 1)
                    {
                        throw new Exception("Data error");
                    }
                }

                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                idAgent = -1;
            }
            finally
            {
                adapAgent.Connection.Close();
                adapIAgentGroup.Connection.Close();
                conn.Close();
            }

            return idAgent;
        }
开发者ID:ngthanhducit,项目名称:TradingServer1502,代码行数:100,代码来源:DBWAgent.cs

示例13: ProcessTrades

        public void ProcessTrades(Stream stream)
        {
            // read rows
            var lines = new List<string>();
            using (var reader = new StreamReader(stream))
            {
                string line;
                while((line = reader.ReadLine()) != null)
                {
                    lines.Add(line);
                }
            }

            var trades = new List<TradeRecord>();

            var lineCount = 1;
            foreach (var line in lines)
            {
                var fields = line.Split(new char[] { ',' });

                if(fields.Length != 3)
                {
                    Console.WriteLine("WARN: Line {0} malformed. Only {1} field(s) found.", lineCount, fields.Length);
                    continue;
                }

                if(fields[0].Length != 6)
                {
                    Console.WriteLine("WARN: Trade currencies on line {0} malformed: '{1}'", lineCount, fields[0]);
                    continue;
                }

                int tradeAmount;
                if(!int.TryParse(fields[1], out tradeAmount))
                {
                    Console.WriteLine("WARN: Trade amount on line {0} not a valid integer: '{1}'", lineCount, fields[1]);
                }

                decimal tradePrice;
                if(!decimal.TryParse(fields[2], out tradePrice))
                {
                    Console.WriteLine("WARN: Trade price on line {0} not a valid decimal: '{1}'", lineCount, fields[2]);
                }

                var sourceCurrencyCode = fields[0].Substring(0, 3);
                var destinationCurrencyCode = fields[0].Substring(3, 3);

                // calculate values
                var trade = new TradeRecord
                {
                    SourceCurrency = sourceCurrencyCode,
                    DestinationCurrency = destinationCurrencyCode,
                    Lots = tradeAmount / LotSize,
                    Price = tradePrice
                };

                trades.Add(trade);

                lineCount++;
            }

            using (var connection = new System.Data.SqlClient.SqlConnection("Data Source=(local);Initial Catalog=TradeDatabase;Integrated Security=True;"))
            {
                connection.Open();
                using(var transaction = connection.BeginTransaction())
                {
                    foreach(var trade in trades)
                    {
                        var command = connection.CreateCommand();
                        command.Transaction = transaction;
                        command.CommandType = System.Data.CommandType.StoredProcedure;
                        command.CommandText = "dbo.insert_trade";
                        command.Parameters.AddWithValue("@sourceCurrency", trade.SourceCurrency);
                        command.Parameters.AddWithValue("@destinationCurrency", trade.DestinationCurrency);
                        command.Parameters.AddWithValue("@lots", trade.Lots);
                        command.Parameters.AddWithValue("@price", trade.Price);

                        command.ExecuteNonQuery();
                    }

                    transaction.Commit();
                }
                connection.Close();
            }

            Console.WriteLine("INFO: {0} trades processed", trades.Count);
        }
开发者ID:aleksandrzak-rafal,项目名称:AdaptiveCode,代码行数:87,代码来源:TradeProcessor.cs

示例14: DeleteVirtualDealer

        /// <summary>
        /// 
        /// </summary>
        /// <param name="virtualDealerID"></param>
        /// <returns></returns>
        internal string DeleteVirtualDealer(int virtualDealerID)
        {
            string result = "-1";
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(DBConnection.DBConnection.Connection);
            DSTableAdapters.VirtualDealerTableAdapter virtualDealerAdap = new DSTableAdapters.VirtualDealerTableAdapter();
            DSTableAdapters.IVirtualDealerTableAdapter iVirtualDealerAdap = new DSTableAdapters.IVirtualDealerTableAdapter();
            DSTableAdapters.VirtualDealerConfigTableAdapter configDealerAdap = new DSTableAdapters.VirtualDealerConfigTableAdapter();
            System.Data.SqlClient.SqlTransaction trans = null;
            try
            {
                conn.Open();
                trans = conn.BeginTransaction();

                configDealerAdap.Connection = conn;
                configDealerAdap.Transaction = trans;
                configDealerAdap.DeleteVirtualConfigByVirtualDealerID(virtualDealerID);

                iVirtualDealerAdap.Connection = conn;
                iVirtualDealerAdap.Transaction = trans;
                iVirtualDealerAdap.DeleteByVirtualDealerID(virtualDealerID);

                virtualDealerAdap.Connection = conn;
                virtualDealerAdap.Transaction = trans;
                int resultDelete = virtualDealerAdap.DeleteVirtualDealer(virtualDealerID);

                if (resultDelete == 0)
                {
                    throw new Exception("Data error");
                }
                result = resultDelete.ToString();
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                return "Data error";
            }
            finally
            {
                virtualDealerAdap.Connection.Close();
                iVirtualDealerAdap.Connection.Close();
                configDealerAdap.Connection.Close();
                conn.Close();
            }

            return result;
        }
开发者ID:ngthanhducit,项目名称:TradingServer1502,代码行数:52,代码来源:DBWVirtualDealer.cs

示例15: UpdateVirtualSymbol

        /// <summary>
        /// 
        /// </summary>
        /// <param name="objVirtualDealer"></param>
        /// <returns></returns>
        internal string UpdateVirtualSymbol(Business.VirtualDealer objVirtualDealer)
        {
            string result = "";
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(DBConnection.DBConnection.Connection);
            DSTableAdapters.IVirtualDealerTableAdapter iVirtualDealerAdap = new DSTableAdapters.IVirtualDealerTableAdapter();
            System.Data.SqlClient.SqlTransaction trans = null;
            try
            {
                conn.Open();
                trans = conn.BeginTransaction();

                iVirtualDealerAdap.Connection = conn;
                iVirtualDealerAdap.Transaction = trans;
                int rowEffect = iVirtualDealerAdap.DeleteByVirtualDealerID(objVirtualDealer.ID);
                for (int i = 0; i < objVirtualDealer.IVirtualDealer.Count; i++)
                {
                    rowEffect = iVirtualDealerAdap.Insert(objVirtualDealer.IVirtualDealer[i].InvestorGroupID, objVirtualDealer.IVirtualDealer[i].SymbolID, objVirtualDealer.ID);
                    if (rowEffect == 0)
                    {
                        throw new Exception("Can't insert IDealer");
                    }
                }
                result = "1";
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                result = "Data error";
            }
            finally
            {
                iVirtualDealerAdap.Connection.Close();
                conn.Close();
            }
            return result;
        }
开发者ID:ngthanhducit,项目名称:TradingServer1502,代码行数:42,代码来源:DBWVirtualDealer.cs


注:本文中的System.Data.SqlClient.SqlConnection.BeginTransaction方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。