public bool Save(Category category)
        {
            const string sqlStatement =
                "INSERT INTO dbo.category (Description, AddedDate, Inactive) " +
                "VALUES(@description, @addeddate, @inactive); ";

            //Connect to database.
            con = OpenConnection();
            com = new SqlCommand(sqlStatement, con);

            //Set parameter values.
            com.Parameters.AddWithValue("@description", category.Description);
            com.Parameters.AddWithValue("@addeddate", category.AddedDate);
            com.Parameters.AddWithValue("@inactive", category.Inactive);

            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    com.ExecuteNonQuery();
                    scope.Complete();
                    return true;
                }
                catch (Exception)
                {
                    scope.Dispose();
                    throw;
                }
                finally
                {
                    scope.Dispose();
                }
            }
        }
        public void BeginTransaction(TransactionOptions options)
        {
            _scope?.Dispose();

            _scope = new TransactionScope(TransactionScopeOption.Required, options,
                                          TransactionScopeAsyncFlowOption.Enabled);
        }
Example #3
0
        public void InitTransaction()
        {
            if (Transaction != null)
            {
                Transaction?.Dispose();
            }

            Transaction = new TransactionScope(TransactionScopeOption.RequiresNew);
        }
        public bool EditCycle(EditCycle cycleUpdate, int pfNumber)
        {
            TransactionScope scope = new TransactionScope();
            try
            {
                if (this.pcRules.IsPfNumberValid(pfNumber))
                {
                    using (scope)
                    {
                        PerformanceReviewCycle cycle = new PerformanceReviewCycle
                        {
                            Id = cycleUpdate.Id,
                            Year = cycleUpdate.Year,
                            Period = cycleUpdate.Period,
                            StartDate = cycleUpdate.StartDate,
                            CloseDate = cycleUpdate.CloseDate,
                            Status = cycleUpdate.Status
                        };

                        this.db.Entry(cycle).State = EntityState.Modified;
                        this.db.SaveChanges();

                        scope.Complete();
                    }

                    return true;
                }
                else
                {
                    scope.Dispose();
                    return false;
                }
            }
            catch (DataException)
            {
                scope.Dispose();
                return false;
            }
            catch (TransactionAbortedException)
            {
                scope.Dispose();
                return false;
            }
            catch (TransactionException)
            {
                scope.Dispose();
                return false;
            }
            catch (Exception)
            {
                scope.Dispose();
                return false;
            }
        }
Example #5
0
        public void TestDisposeFlagCloning962Test1(
            [DataSources(false)] string context, [Values] bool withScope)
        {
            if (withScope && (
                    TestProvName.AlliSeries.Contains(context) ||
                    context == ProviderName.DB2 ||
                    context == ProviderName.InformixDB2 ||
                    context == ProviderName.MySqlConnector ||
                    context == ProviderName.SapHanaNative ||
                    context == ProviderName.SqlCe ||
                    context == ProviderName.Sybase ||
                    context.Contains("Firebird") ||
                    context.Contains("Oracle") ||
                    context.Contains("PostgreSQL") ||
                    context.Contains("SqlServer") ||
                    context.Contains("SqlAzure") ||
                    context.Contains(ProviderName.SQLiteClassic)
                    ))
            {
                // DB2: ERROR [58005] [IBM][DB2.NET] SQL0902 An unexpected exception has occurred in  Process: 22188 Thread 16 AppDomain: Name:domain-1b9769ae-linq2db.Tests.dll
                // Firebird: SQL error code = -204 Table unknown CATEGORIES
                // Informix DB2: ERROR [2E000] [IBM] SQL1001N  "<DBNAME>" is not a valid database name.  SQLSTATE=2E000
                // MySqlConnector: XAER_RMFAIL: The command cannot be executed when global transaction is in the  ACTIVE state
                // Oracle: Connection is already part of a local or a distributed transaction
                // PostgreSQL: Nested/Concurrent transactions aren't supported.
                // SQLite.Classic: No transaction is active on this connection
                // SAP HANA native: The rollback was caused by an unspecified reason: XA Transaction is rolled back.
                // SQL Server: Cannot drop the table 'Categories', because it does not exist or you do not have permission.
                // SQLCE: SqlCeConnection does not support nested transactions.
                // Sybase native: just crashes without details (as usual for this "provider")
                Assert.Inconclusive("Provider not configured or has issues with TransactionScope or doesn't support DDL in distributed transactions");
            }

            TransactionScope?scope = withScope ? new TransactionScope() : null;

            try
            {
                using (new AllowMultipleQuery())
                    using (var db = new DataConnection(context))
                        using (db.CreateLocalTable(Category.Data))
                            using (db.CreateLocalTable(Product.Data))
                            {
                                var categoryDtos = db.GetTable <Category>().LoadWith(c => c.Products).ToList();

                                scope?.Dispose();
                                scope = null;
                            }
            }
            finally
            {
                scope?.Dispose();
            }
        }
Example #6
0
 public void Commit()
 {
     if (!_domainNotificationHandler.HasNotifications)
     {
         try
         {
             _agendamentoDbContext.SaveChanges();
         }
         finally
         {
             Transaction?.Dispose();
             OpenTransaction();
         }
     }
 }
Example #7
0
        public bool Apply(EF.Shop_Goods goods,EF.Shop_Photo photo)
        {
            //TransactionScope有错误自己回滚
            using (TransactionScope tran = new TransactionScope())
            {
                try
                {
                    DbEntityEntry<EF.Shop_Photo> entry0 = db.Entry<EF.Shop_Photo>(photo);
                    entry0.State = EntityState.Added;
                    db.SaveChanges();
                    goods.PhotoId = photo.PhotoId;

                    goods.BoolYX = true;
                    goods.AddTime = DateTime.Now;
                    DbEntityEntry<EF.Shop_Goods> entry = db.Entry<EF.Shop_Goods>(goods);
                    entry.State = EntityState.Added;
                    db.SaveChanges();
                    tran.Complete();
                    return true;

                }
                catch (Exception)
                {
                    tran.Dispose();

                    return false;
                    throw;
                }
            }
        }
Example #8
0
        public ActionResult Create([Bind(Include = "ID,Name,CategoryID")] Title title)
        {
            using (TransactionScope transactionScope = new TransactionScope())
            {
                try
                {

                    if (ModelState.IsValid)
                    {
                        db.Titles.Add(title);
                        db.SaveChanges();
                        FileStream fs = new FileStream(@"D:\\RE", FileMode.Append);

                    }

                    ViewBag.CategoryID = new SelectList(db.CATEGORies, "ID", "Name", title.CategoryID);
                    transactionScope.Complete();
                    return RedirectToAction("Index");
                }
                catch
                {
                    transactionScope.Dispose();
                }
                finally
                {
                    // transactionScope.Dispose();

                }
                return View(title);

            }
        }
Example #9
0
        public void Explicit_rollback_can_be_used_to_rollback_a_transaction()
        {
            EnsureDatabaseInitialized(() => new SimpleModelContext());

            using (var tx = new TransactionScope())
            {
                using (var context = new SimpleModelContext())
                {
                    var product = new Product
                                      {
                                          Name = "BestTea"
                                      };
                    context.Products.Add(product);
                    context.SaveChanges();

                    Assert.Equal(1, GetTransactionCount(context.Database.Connection));
                    Assert.True(context.Products.Where(p => p.Name == "BestTea").AsNoTracking().Any());

                    // Rollback System Transaction
                    tx.Dispose();

                    Assert.False(context.Products.Where(p => p.Name == "BestTea").AsNoTracking().Any());
                }
            }
        }
Example #10
0
 public void Teardown()
 {
     if (Transaction.Current.TransactionInformation.Status == TransactionStatus.Active)
     {
         scope?.Dispose();
     }
 }
Example #11
0
        public bool Apply(EF.Shop_Photo photo, EF.Shop_People people, EF.Shop_Store shop)
        {
            //TransactionScope有错误自己回滚
            using (TransactionScope tran = new TransactionScope())
            {
                try
                {
                    DbEntityEntry<EF.Shop_Photo> entry = db.Entry<EF.Shop_Photo>(photo);
                    entry.State = EntityState.Added;
                    db.SaveChanges();
                    shop.PhotoId = photo.PhotoId;

                    people.BoolLX = true;
                    DbEntityEntry<EF.Shop_People> entry1 = db.Entry<EF.Shop_People>(people);
                    entry1.State = EntityState.Added;
                    db.SaveChanges();
                    shop.PeopleId = people.PeopleId;

                    shop.BoolPass = false;
                    DbEntityEntry<EF.Shop_Store> entry2 = db.Entry<EF.Shop_Store>(shop);
                    entry2.State = EntityState.Added;
                    db.SaveChanges();
                    tran.Complete();
                    return true;

                }
                catch (Exception)
                {
                    tran.Dispose();

                    return false;
                    throw;
                }
            }
        }
Example #12
0
        protected virtual IEnumerable <T> ExecuteQuery <T>(Func <IDbStatement, IEnumerable <T> > query)
        {
            ThrowWhenDisposed();

            TransactionScope scope       = OpenQueryScope();
            IDbConnection    connection  = null;
            IDbTransaction   transaction = null;
            IDbStatement     statement   = null;

            try
            {
                connection         = _connectionFactory.Open();
                transaction        = _dialect.OpenTransaction(connection);
                statement          = _dialect.BuildStatement(scope, connection, transaction);
                statement.PageSize = _pageSize;

                Logger.LogTrace(Messages.ExecutingQuery);
                return(query(statement));
            }
            catch (Exception e)
            {
                statement?.Dispose();
                transaction?.Dispose();
                connection?.Dispose();
                scope?.Dispose();

                Logger.LogDebug(Messages.StorageThrewException, e.GetType());
                if (e is StorageUnavailableException)
                {
                    throw;
                }

                throw new StorageException(e.Message, e);
            }
        }
        public void Intercept(IInvocation invocation)
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                try
                {
                    if (WriteToLog) Logger.DebugFormat("Transaction Begin: {0}.{1}", invocation.TargetType.FullName, invocation.Method.Name);
                    invocation.Proceed();
                    transaction.Complete();
                    if (WriteToLog) Logger.DebugFormat("Transaction Complete: {0}.{1}", invocation.TargetType.FullName, invocation.Method.Name);
                }
                catch (Exception)
                {
                    // Remember to start the service called "Distributed Transaction Coordinator"
                    //http://social.msdn.microsoft.com/Forums/en-US/3749da7a-59df-4db7-ae2e-6d0e414750d4/msdtc-on-server-xxx-is-unavailable

                    // If transaction is not disposed, there will be an error on tot transaction
                    // http://startbigthinksmall.wordpress.com/2009/05/04/the-transaction-has-aborted-tricky-net-transactionscope-behavior/
                    transaction.Dispose();

                    // The Exception is logged in the LogInterceptor
                    throw;
                }
            }
        }
Example #14
0
        /// <summary>
        /// public method for running this test
        /// </summary>
        protected DbTestRunnerResult ExecuteArrangeActAssert()
        {
            var context = this.TestFixture.Context;
            var result  = new DbTestRunnerResult {
                TestName = this.Name
            };
            TransactionScope transactionScope = null;

            try
            {
                using (transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        using (var handle = ProduceDbHandle())
                        {
                            this.handleInstance = handle;
                            var arrangeResult = ExecuteArrange(context, result, handle);
                            if (arrangeResult.IsSuccessful)
                            {
                                var actResult = ExecuteAct(context, result, handle);

                                if (actResult.IsSuccessful)
                                {
                                    ExecuteAssert(context, result, actResult.Data, handle);
                                }
                            }

                            this.handleInstance = null;
                        }
                    }
                    finally
                    {
                        this.handleInstance = null;
                        if (context.CommitTransactionScope)
                        {
                            transactionScope.Complete();
                        }
                    }
                }
            }
            // catch and re-throw assertions
            catch (XunitException)
            {
                throw;
            }
            catch (Exception e)
            {
                result = DbTestRunnerResult.Failure("Error running DbTest", e);
            }
            finally
            {
                transactionScope?.Dispose();
            }

            DumpRunLog(result);

            return(result);
        }
Example #15
0
        public void TestDisposeFlagCloning962Test2(
            [DataSources(false)] string context, [Values] bool withScope)
        {
            if (withScope && (
                    TestProvName.AlliSeries.Contains(context) ||
                    context == ProviderName.DB2 ||
                    context == ProviderName.InformixDB2 ||
                    context == ProviderName.SapHanaOdbc ||
                    context == ProviderName.SqlCe ||
                    context == ProviderName.Sybase ||
#if !NET472
                    (context.Contains("Oracle") && context.Contains("Managed")) ||
                    context == ProviderName.SapHanaNative ||
#endif
                    TestProvName.AllMySqlData.Contains(context) ||
                    context.StartsWith("Access") ||
                    context.Contains("SqlServer") ||
                    context.Contains("SqlAzure") ||
                    context.Contains("PostgreSQL") ||
                    context.Contains(ProviderName.SQLiteClassic)
                    ))
            {
                // Access: The ITransactionLocal interface is not supported by the 'Microsoft.Jet.OLEDB.4.0' provider.  Local transactions are unavailable with the current provider.
                // Access>ODBC: ERROR [HY092] [Microsoft][ODBC Microsoft Access Driver]Invalid attribute/option identifier
                // DB2: ERROR [58005] [IBM][DB2/NT64] SQL0998N  Error occurred during transaction or heuristic processing.  Reason Code = "16". Subcode = "2-8004D026".
                // Informix DB2: ERROR [2E000] [IBM] SQL1001N  "<DBNAME>" is not a valid database name.  SQLSTATE=2E000
                // MySql.Data: Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported.
                // PostgreSQL: 55000: prepared transactions are disabled
                // SQLite.Classic: The operation is not valid for the state of the transaction.
                // SAP HANA ODBC: ERROR [HYC00] [SAP AG][LIBODBCHDB32 DLL] Optional feature not implemented
                // SQLCE: The connection object can not be enlisted in transaction scope.
                // Sybase native: Only One Local connection allowed in the TransactionScope
                // Oracle managed: Operation is not supported on this platform.
                // SAP.Native: Operation is not supported on this platform.
                // SqlServer: The operation is not valid for the state of the transaction.
                Assert.Inconclusive("Provider not configured or has issues with TransactionScope");
            }

            TransactionScope?scope = withScope ? new TransactionScope() : null;
            try
            {
                using (new AllowMultipleQuery())
                    using (var db = new DataConnection(context))
                    {
                        // test cloned data connection without LoadWith, as it doesn't use cloning in v3
                        db.Select(() => "test1");
                        using (var cdb = ((IDataContext)db).Clone(true))
                        {
                            cdb.Select(() => "test2");

                            scope?.Complete();
                        }
                    }
            }
            finally
            {
                scope?.Dispose();
            }
        }
        public void Create(PloatBooking oPloatBooking)
        {
            using (var scope = new TransactionScope())
            {
                try
                {
                    using (var ctx = new BHGroupEntities())
                    {
                        oPloatBooking.StartDate = DateTime.Now;
                        oPloatBooking.EndDate = DateTime.Now.AddMonths(75);

                        if (oPloatBooking.PloatType == En_PloatType.WeekendHome.ToString())
                        {
                            oPloatBooking.Amt = 600000;
                            oPloatBooking.PlotDesc = "100 sq. yard Net (140 sq. yard Super Build Up)";
                        }
                        else if (oPloatBooking.PloatType == En_PloatType.Villa.ToString())
                        {
                            oPloatBooking.Amt = 600000 * 2;
                            oPloatBooking.PlotDesc = "200 sq. yard Net (280 sq. yard Super Build Up)";
                        }
                        else if (oPloatBooking.PloatType == En_PloatType.FarmHouse.ToString())
                        {
                            oPloatBooking.Amt = 600000 * 3;
                            oPloatBooking.PlotDesc = "400 sq. yard Net (420 sq. yard Super Build Up)";
                        }
                        oPloatBooking.NetAmt = (oPloatBooking.Amt * oPloatBooking.Qty);
                        ctx.PloatBookings.Add(oPloatBooking);

                        int token = 0;
                        if (oPloatBooking.PloatType == En_PloatType.WeekendHome.ToString())
                            token = 1;
                        else if (oPloatBooking.PloatType == En_PloatType.Villa.ToString())
                            token = 2;
                        else if (oPloatBooking.PloatType == En_PloatType.FarmHouse.ToString())
                            token = 3;
                        int count_token = (token * oPloatBooking.Qty);
                        for (int i = 0; i < count_token; i++)
                        {
                            DrowToken oDrow = new DrowToken();
                            oDrow.MemberId = oPloatBooking.MemberId;
                            oDrow.PlotBookingId = oPloatBooking.PloatBookingId;
                            oDrow.Status = En_DrowStatus.Active.ToString();
                            oDrow.Creaton = System.DateTime.Now;
                            oDrow.Modifiedon = System.DateTime.Now;
                            ctx.DrowTokens.Add(oDrow);
                        }
                        ctx.SaveChanges();
                        scope.Complete();
                    }
                }
                catch (Exception ex)
                {
                    scope.Dispose();
                    throw ex;
                }
            }
        }
Example #17
0
 protected override void Dispose(bool explicitDispose)
 {
     if (explicitDispose)
     {
         _realScope?.Dispose();
     }
     _realScope = null;
     //
     base.Dispose(explicitDispose);
 }
        protected virtual void Dispose(bool disposing)
        {
            Logger.LogTrace(Messages.DisposingStatement);

            _transaction?.Dispose();

            _connection?.Dispose();

            _scope?.Dispose();
        }
Example #19
0
 public override void After(MethodInfo methodUnderTest)
 {
     try
     {
         _transaction?.Dispose();
     }
     finally
     {
         Monitor.Exit(GlobalLock);
     }
 }
Example #20
0
        private void btnChange_Click(object sender, EventArgs e)
        {
            string sourceFileName = "";
            string code = "";
            string savefileName = "";
            if (this.txtselectedFile.Text.Trim() != "")
            {
                sourceFileName = this.txtselectedFile.Text.Trim();
            }
            else
            {
                MessageBox.Show("请选择加密文件!");
                return;
            }
            if (this.txtCode.Text.Trim() != "")
            {
                code = this.txtCode.Text.Trim();
            }
            else
            {
                MessageBox.Show("请输入密码!");
                return;
            }

            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择保存路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                savefileName = dialog.SelectedPath;
            }
            else
            {
                return;
            }

            using (TransactionScope scope = new TransactionScope())
            {
                DECAllFileEncryption decAll = new DECAllFileEncryption(code);
                DirectoryInfo sourceInfo = new DirectoryInfo(sourceFileName);
                try
                {
                    decAll.EncryptAllFiles(sourceInfo, savefileName);
                    scope.Complete();
                    MessageBox.Show("加密成功!");
                    this.txtCode.Text = "";
                    this.txtselectedFile.Text = "";
                }
                catch
                {
                    scope.Dispose();
                    MessageBox.Show("加密失败!");
                }
            }
        }
Example #21
0
 public virtual void Dispose()
 {
     DbTransaction?.Dispose();
     DbConnection?.Dispose();
     TransactionScope?.Dispose();
     DbTransaction       = null;
     DbConnection        = null;
     TransactionScope    = null;
     Transaction.Current = null;
     Disposed            = true;
 }
Example #22
0
 protected virtual void Dispose(Boolean disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             transactionScope?.Dispose();
             disposed = true;
         }
     }
 }
Example #23
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                _transaction?.Dispose();
                Context?.Dispose();
            }
        }
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var response = default(TResponse);
            var typeName = request.GetGenericTypeName();
            TransactionScope transaction = null;

            try
            {
                if (hasActiveTransaction)
                {
                    return(await next());
                }

                try
                {
                    transaction = new TransactionScope();
                    unitOfWork.BeginTransaction();
                    hasActiveTransaction = true;

                    logger.LogInformation("----- Begin transaction for {CommandName} ({@Command})", typeName, request);

                    response = await next();

                    logger.LogInformation("----- Commit transaction for {CommandName}", typeName);

                    unitOfWork.CommitTransaction();
                    transaction?.Complete();
                }
                catch
                {
                    unitOfWork.RollbackTransaction();
                    throw;
                }
                finally
                {
                    transaction?.Dispose();
                    hasActiveTransaction = false;
                }

                await excecuteOnFinish?.Invoke(cancellationToken);

                return(response);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "ERROR Handling transaction for {CommandName} ({@Command})", typeName, request);

                throw;
            }
        }
Example #25
0
        //Method that creates new Address for specific Company
        public bool CreateNewAddress(AddressDTO AddressNew)
        {
            bool check = false;
            using (TransactionScope transaction = new TransactionScope())
            {

                try
                {
                    Address AddressIn = new Address();
                    //Data transfer to the the AddressIn
                    AddressIn.Address1 = AddressNew.Address1;
                    AddressIn.Address2 = AddressNew.Address2;
                    AddressIn.City = AddressNew.City;
                    AddressIn.State = AddressNew.State;
                    AddressIn.PostalCode = AddressNew.PostalCode;
                    AddressIn.Country = AddressNew.Country;

                    using (var context = new RFQEntities())
                    {
                        //Finding references for the Foreign Keys
                        Company existingCompany = context.Companies.Single(p => p.CompanyID == AddressNew.CompanyID);

                        //Adding refernces
                        AddressIn.Company = existingCompany;

                        if (AddressIn.EntityState == EntityState.Detached)
                        {
                            context.Addresses.AddObject(AddressIn);
                        }

                        context.SaveChanges();

                    }

                }

                catch (Exception e)
                {
                    transaction.Dispose();
                    check = false;
                    return check;

                }
                transaction.Complete();
                check = true;
                return check;

            }
        }
        protected void AddInvoiceType_Click(object sender, EventArgs e)
        {
            bool insertUpdateOk = true;
            using (TransactionScope ts = new TransactionScope())
            {
                DataClasses1DataContext dbContext = new DataClasses1DataContext();

                try
                {
                    RadButton AddInvoiceType = ((RadButton)sender);
                    GridDataItem myItem = AddInvoiceType.Parent.Parent.Parent.Parent as GridDataItem;
                    RadComboBox cmbSelectedType = AddInvoiceType.Parent.FindControl("cmbInvoiceTypes") as RadComboBox;

                    if (myItem != null && myItem["Id"].Text != string.Empty && !String.IsNullOrEmpty(myItem["Id"].Text) && cmbSelectedType != null
                        && cmbSelectedType.SelectedValue != string.Empty && !String.IsNullOrEmpty(cmbSelectedType.SelectedValue))
                    {
                        var customer = dbContext.LargeCustomer.FirstOrDefault(q => q.CustomerId == Int32.Parse(myItem["Id"].Text));
                        if (customer != null)
                        {
                            customer.InvoiceTypesID = Int32.Parse(cmbSelectedType.SelectedValue);
                            dbContext.SubmitChanges();
                        }
                        ts.Complete();

                    }
                }
                catch (Exception ex)
                {
                    insertUpdateOk = false;
                    if (ts != null)
                        ts.Dispose();
                    RadWindowManagerLargeCustomer.RadAlert(Server.HtmlEncode(ex.Message).RemoveLineEndings(), 380, 180, "Fehler", "");
                    try
                    {
                        dbContext = new DataClasses1DataContext(Int32.Parse(Session["CurrentUserId"].ToString()));
                        dbContext.WriteLogItem("AddInvoiceType_Click Error " + ex.Message, LogTypes.ERROR, "Customer");
                        dbContext.SubmitChanges();
                    }
                    catch { }
                }

            }
            if (insertUpdateOk)
            {
                getAllCustomer.EditIndexes.Clear();
                getAllCustomer.MasterTableView.IsItemInserted = false;
                getAllCustomer.MasterTableView.Rebind();
            }
        }
        private void Dispose(Boolean disposing)
        {
            //if (_isDisposed)
            //    return;

            if (disposing)
            {
                _connection?.Close();

                _transaction?.Dispose();
                _connection?.Dispose();

                //_transaction = null;
                //_connection = null;
            }
            //_isDisposed = true;
        }
        public void AddReport_ApprovedBySupAndApprovedByAcc_GetReportStatus()
        {
            DateTime date = DateTime.Now.Date;
            string reportName = "REPORT";
            string location = "Broadway";
            string description = "food";
            string strAmount = "100.1111";
            double amount = Math.Round(100.1111, 2);
            double amount_aud = 148.16;
            string currency = "Euros";
            byte[] receipt = new byte[] { 2, 3, 4, 2 };
            int reportId = GetCurrentRowOfReportsTable() + 1;
            int expenseId = GetCurrentRowOfExpensesTable() + 1;
            Consultant consultant = new Consultant("con_he5");
            Supervisor supervisor = new Supervisor("sup_he1");
            AccountsStaff accountsStaff = new AccountsStaff("acc1");

            // start transaction
            using (TransactionScope testTransaction = new TransactionScope())
            {
                consultant.CreateExpense(date, location, description, strAmount, currency, receipt);
                consultant.AddExpenses(reportId);
                consultant.AddReport(reportName);
                supervisor.Approve(reportId);
                accountsStaff.Approve(reportId);

                ReportsTableAdapter adapter = new ReportsTableAdapter();
                Reports.ReportsDataTable reportsTable = new Reports.ReportsDataTable();
                adapter.FillById(reportsTable, reportId);

                foreach (Reports.ReportsRow report in reportsTable)
                {
                    Assert.AreEqual(reportId, report.Id);
                    Assert.AreEqual(reportName, report.Report_name);
                    Assert.AreEqual(amount, report.Total_amount);
                    Assert.AreEqual("APPROVED", report.Supervisor_approval);
                    Assert.AreEqual("APPROVED", report.Accounts_approval);
                    Assert.AreEqual(consultant.Department, report.Department);
                    Assert.AreEqual(consultant.Username, report.Consultant_id);
                    Assert.AreEqual("NONE", report.Supervisor_id);
                }

                testTransaction.Dispose(); // rollback
            }
        }
Example #29
0
        //Method that creates new Company
        public bool CreateNewCompany(CompanyDTO CompanyNew)
        {
            bool check = false;
            using (TransactionScope transaction = new TransactionScope())
            {

                try
                {
                    Company CompanyIn = new Company();
                    //Data transfer to the new company
                    CompanyIn.Name = CompanyNew.Name;

                    using (var context = new RFQEntities())
                    {
                        //Finding references for the Foreign Keys
                        Category existingCategory = context.Categories.Single(p => p.CategoryID == CompanyNew.CategoryID);
                        CompanyType existingCompanyType = context.CompanyTypes.Single(p => p.CompanyTypeID == CompanyNew.CompanyTypeID);
                        //Adding refernces
                        CompanyIn.Category = existingCategory;
                        CompanyIn.CompanyType = existingCompanyType;

                        if (CompanyIn.EntityState == EntityState.Detached)
                        {
                            context.Companies.AddObject(CompanyIn);
                        }

                        context.SaveChanges();

                    }

                }

                catch (Exception e)
                {
                    transaction.Dispose();
                    check = false;
                    return check;

                }
                transaction.Complete();
                check = true;
                return check;

            }
        }
Example #30
0
 public void Dispose()
 {
     try
     {
         m_connection?.Dispose();
     }
     catch {; }
     finally
     {
         try
         {
             m_scope?.Dispose();
         }
         catch {; }
         finally
         {
             m_owner.RemoveCurrentTransaction();
         }
     }
 }
        /// <summary>
        /// 产生包裹事务 不去触发MSDTC(分布式事务)
        /// 支持LINQ表提交,并同时返回提交结果到实体
        /// </summary>
        /// <param name="db">数据上下文,多个方法使用的上下文必须是同一个</param>
        /// <param name="isOutermost">是否为最外层,默认为false</param>
        /// <param name="action">处理代码块</param>
        public static void UsingTransactionNoMsdtc(DbContext db, bool isOutermost, Action action)
        {
            var objectContext = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext;
            try
            {
                if (objectContext.Connection.State == ConnectionState.Closed)
                    objectContext.Connection.Open();

                using (TransactionScope trans = new TransactionScope())
                //using(DbContextTransaction trans=db.Database.BeginTransaction())
                {
                    try
                    {
                        action();
                        trans.Complete();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        trans.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (isOutermost)//如果是最外层事务,而将连接关闭
                {
                    objectContext.Connection.Close();
                }
            }
        }
Example #32
0
    public static void InsertUser(string userName)
    {
        using (TransactionScope scope = new TransactionScope())
        {
            using (GroupsEntities context = new GroupsEntities())
            {
                Group adminGroup = new Group { GroupName = "Admins" };
                if (context.Groups.Count(x => x.GroupName == "Admins") == 0)
                {
                    context.Groups.Add(adminGroup);
                    context.SaveChanges();
                    scope.Complete();
                }
                else
                {
                    if (context.Users.Count(x => x.UserName == userName) > 0)
                    {
                        Console.WriteLine("User already exists.");
                        scope.Dispose();
                    }

                    Group currentgroup = context.Groups
                        .Where(x => x.GroupName == "Admins").First();

                    User newUser = new User()
                    {
                        UserName = userName,
                        GroupID = currentgroup.GroupID
                    };

                    context.Users.Add(newUser);
                    context.SaveChanges();
                    scope.Complete();
                }
            }
        }

    }
Example #33
0
        public static int ConfirmOrder(int orderId, ref long orderSessionVal, int msnType, string message, string orders, out string msg)
        {
            msg = string.Empty;
            int nResult = -1;
            TransactionScope ts = new TransactionScope( );
            SharedDbConnectionScope ss = new SharedDbConnectionScope( );
            try
            {
                lock (LockScopeAction(orderId))
                {
                    Order order = Order.FetchByID(orderId);
                    if (!CheckSendMessagePostData(order, out msg))
                        goto lbl_return;
                    if ((order.OrderUpdateOn.Value.Ticks) != (orderSessionVal))
                    {
                        msg = "该订单已修改,请重新查看.";
                        nResult = -2;
                        goto lbl_return;
                    }
                    var oldStatus = order.OrderStatus;
                    var chgData = Utilities.JSONToObj<Dictionary<int, OrderDetailItem>>(orders);
                    bool isChanged, hasChangePrice = false;
                    decimal dSum = 0;
                    SysCompany company = SysCompany.FetchByID(order.OrderSellerID);
                    if (msnType == 1) //暂缺或价格调整
                    {
                        OrdersDetail itemDetail = null;
                        var details = GetOrderAllDetailByOrderId(orderId).ToDictionary(d => d.MenuId, d =>
                            {
                                if (d.MenuId < 0)
                                    itemDetail = d;
                                return d;
                            });
                        //check sum
                        if (itemDetail != null)
                        {
                            decimal itemChgSum = chgData.Values.Sum(item =>
                            {
                                if (item.IsCompanyItem)
                                {
                                    if (item.NewPrice > 0)
                                    {
                                        itemDetail.IsChgPrice = true;
                                        return item.NewPrice;
                                    }
                                    else
                                        return item.OrderPrice;
                                }
                                else
                                    return 0;
                            });
                            if (itemChgSum <= itemDetail.OrderPrice.Value)
                            {
                                msg = "餐点调的新价不能小于促销项目的现金支付金额.";
                                goto lbl_return;
                            }
                            else if (itemDetail.IsChgPrice.Value)
                                CompanyItemBLL.UpdateCompanyItemSum(itemDetail.MenuId, itemChgSum);
                            dSum = itemDetail.OrderPrice.Value;
                        }
                        //bool isOutOfStock;
                        foreach (var item in chgData.Values)
                        {
                            isChanged = false;
                            var detail = details.ContainsKey(item.MenuId) ? details[item.MenuId] : (OrdersDetail)null;
                            if (detail != null)
                            {
                                if (detail.IsOutOfStock != item.IsOutOfStock)
                                {
                                    detail.IsOutOfStock = item.IsOutOfStock;
                                    MealMenuBLL.ChangeMenuOutOfStokcStatus(item.MenuId, item.IsOutOfStock);
                                    isChanged = true;
                                    if (item.IsOutOfStock)
                                        order.HasOutOfStock = item.IsOutOfStock;
                                }

                                if (item.NewPrice > 0 && detail.OrderPrice.Value != item.NewPrice)
                                {
                                    detail.OrderPrice = item.NewPrice;
                                    detail.IsChgPrice = true;
                                    hasChangePrice = true;
                                    isChanged = true;
                                    MealMenuBLL.ChangeMenuPrice(item.MenuId, item.NewPrice);
                                }

                                if (!detail.IsOutOfStock.Value)
                                    dSum += detail.OrderQty.Value * detail.OrderPrice.Value;
                                if (isChanged)
                                    detail.Save( );
                            }
                        }
                        dSum = Math.Round(dSum, 1);
                    }
                    isChanged = false;

                    SysMember user = SysMember.FetchByID(order.OrderMemberID);
                    if (msnType == 1 || hasChangePrice) //某菜单缺货或价格更改
                    {
                        isChanged = true;
                        order.OrderSum = dSum;
                        order.OrderSumOk = order.ServiceSum.HasValue ? (order.ServiceSum.Value + dSum) : dSum;
                        order.OrderPay = order.ServiceSum.HasValue ? (order.ServiceSum.Value + dSum) : dSum;
                        order.OrderPrePoint = (RewardBLL.OrderMealRewardRate(company) / 100M) * dSum; //赠送积分
                        order.OrderRate = RewardBLL.OrderMealRewardRate(company) / 100M;  //赠送比例
                    }

                    if (msnType == 2 || msnType == 4) //商家不外送,订单取消
                    {
                        isChanged = true;
                        if (msnType == 2)
                            order.IsNonOut = true;
                        order.OrderStatus = (int)OrderStatus.Canceled;
                        order.OrderUpdateOn = DateTime.Now;
                        if (!CompanyItemBLL.CancelMemberMealItem(order, out msg))
                            goto lbl_return;
                        RewardBLL.CancelRewardMemberPointForOrderMeal(order);
                    }
                    else //if (msnType != 3)  //自定义回复
                    {
                        if (msnType != 3 ||
                            (msnType == 3 && (oldStatus == (int)OrderStatus.NotStart || oldStatus == (int)OrderStatus.Modified)))
                            order.OrderStatus = (int)OrderStatus.InProgress;
                        order.OrderUpdateOn = DateTime.Now;
                        order.MsnType = msnType == 3 && oldStatus == (int)OrderStatus.InProgress ? 0 : msnType;
                        order.ModifiedOn = DateTime.Now;
                        isChanged = true;
                    }
                    //if (msnType == 0 || (msnType == 1 && !order.HasOutOfStock.Value))
                    //{
                    //    order.OrderPoint = order.OrderPrePoint;
                    //}

                    if (!order.OrderOper.HasValue || order.OrderOper.Value == 0)
                        order.OrderOper = AppContextBase.Context.User.Id;
                    order.Save( );

                    if (msnType == 0 || (msnType == 1 && !order.HasOutOfStock.Value))
                    {
                        RewardBLL.RewardMemberPointForOrderMeal(user, company, order);
                        //OrderBLL.UpdateBalance( );
                    }
                    RemoveLockScopeAction(orderId);
                    ts.Complete( );
                    ss.Dispose( );
                    ss = null;
                    ts.Dispose( );
                    ts = null;
                    OrderProgressBLL.AddOrderConfirmLog(order, company, msnType, hasChangePrice, message);
                    string msnContent = string.Empty;
                    if (msnType == 0)
                    {
                        if (UserIsFirstOrder(order.OrderMemberID))
                        {
                            msnContent = string.Format("亲爱的用户:{0}已经收到您的订单,餐厅正在备餐。您本次订单总计{1}元。预计{2}分钟左右为您送达(仅供参考,高峰时段以实际送达时间为准)。",
                                                        company.CompanyName, order.OrderSumOk, company.OrderElapsed);

                        }
                    }
                    else if (msnType == 1 && order.HasOutOfStock.HasValue && order.HasOutOfStock.Value)
                        msnContent = "亲爱的用户:" + message;
                    else if (msnType == 2)
                        msnContent = "亲爱的用户:很抱歉," + company.CompanyName + "表示,当前暂不提供外送,请选择其他餐厅。";
                    else if (msnType == 3)
                        msnContent = "亲爱的用户:" + message;
                    if (!string.IsNullOrEmpty(msnContent))
                    {
                        int logId;
                        string phone = string.IsNullOrEmpty(user.MemberMsnPhone) ? user.MemberPhoneNumber : user.MemberMsnPhone;
                        if (!MsnBLL.SendMessage(phone, msnContent, order.Id, out msg, out logId))
                            goto lbl_return;
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                Logging.Log("OrderMealBLL->ConfirmOrder", ex, true);
                goto lbl_return;
            }
            finally
            {
                if (ss != null)
                    ss.Dispose( );
                if (ts != null)
                    ts.Dispose( );
            }
            msg = "发送成功";
            nResult = 0;
            orderSessionVal = GetOrderUpdateOn(orderId).Ticks;
            lbl_return:
            RemoveLockScopeAction(orderId);
            return nResult;
        }
 protected override void before_each()
 {
     base.before_each();
     scope?.Dispose();
     scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
 }
        public void TearDown()
        {
#if TRANSACTIONS
            scope?.Dispose();
#endif
        }
Example #36
0
 protected void DisposeTranScope()
 {
     _transactionScope?.Dispose();
     _transactionScope = null;
 }
Example #37
0
 void ClearTransaction()
 {
     _transaction?.Dispose();
     _transaction = null;
 }
Example #38
0
        /// <summary>
        /// 作者:Primo
        /// 日期:2014.07.23
        /// 描述:更新ContractTypeProductLevel
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool UpdateContractTypeProductLevel(ContractTypeProductLevel model)
        {
            using (var edb = new EmeEntities())
            {
                using (var tran = new TransactionScope())
                {
                    try
                    {
                        //获取更新对象
                        var modelObj = edb.ContractTypeProductLevel.FirstOrDefault(p => p.Id == model.Id);

                        modelObj.MajorTotal = model.MajorTotal;
                        modelObj.ElectiveTotal = model.ElectiveTotal;
                        modelObj.Absence = model.Absence;
                        modelObj.Repair = model.Repair;

                        edb.Entry(modelObj).State = EntityState.Modified;

                        var result = edb.SaveChanges() > 0;
                        tran.Complete();
                        return result;
                    }
                    catch (Exception e)
                    {
                        tran.Dispose();
                        // 异常日志消息队列
                        Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs()
                        {
                            ExceptionType = CommonHelper.To<int>(ExceptionType.Function),
                            Message = string.Format("StudentBLL-UpdateContractTypeProductLevel:{0};{1};{2}", e.Message, e.InnerException.Message, e.HelpLink),
                            IsTreat = false,
                            CreateBy = model.UpdateBy,
                            CreateTime = DateTime.Now
                        });
                        return false;
                    }
                }
            }
        }
Example #39
0
        /// <summary>
        /// 作者:Primo
        /// 日期:2014.07.23
        /// 描述:添加ContractTypeProductLevel
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool CreateContractTypeProductLevel(ContractTypeProductLevel model)
        {
            using (var edb = new EmeEntities())
            {
                using (var tran = new TransactionScope())
                {
                    try
                    {
                        //创建添加对象
                        var modelObj = new ContractTypeProductLevel()
                        {
                            BranchId = model.BranchId,
                            ContractTypeId = model.ContractTypeId,
                            ProductLevelId = model.ProductLevelId,
                            MajorTotal = model.MajorTotal,
                            ElectiveTotal = model.ElectiveTotal,
                            Absence = model.Absence,
                            Repair = model.Repair,
                            IsSystem = false,
                            Status = ConvertEnum.StatusTypeForActive,
                            CreateBy = model.CreateBy,
                            CreateTime = DateTime.Now
                        };

                        edb.Entry(modelObj).State = EntityState.Added;

                        var result = edb.SaveChanges() > 0;
                        tran.Complete();
                        return result;
                    }
                    catch (Exception e)
                    {
                        tran.Dispose();
                        // 异常日志消息队列
                        Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs()
                        {
                            ExceptionType = CommonHelper.To<int>(ExceptionType.Function),
                            Message = string.Format("StudentBLL-UpdateContractTypeProductLevel:{0};{1};{2}", e.Message, e.InnerException.Message, e.HelpLink),
                            IsTreat = false,
                            CreateBy = model.UpdateBy,
                            CreateTime = DateTime.Now
                        });
                        return false;
                    }
                }
            }
        }
Example #40
0
        /// <summary>
        /// 作者:Kylin
        /// 时间:2014.04.10
        /// 描述:创建培训计划 (test ing )
        /// </summary>
        /// <param name="trainSchedule"></param>
        /// <param name="trainBranchRights">分配的中心Ids</param>
        /// <param name="createBy"></param>
        /// <returns></returns>
        public static int CreateTrainSchedule(TrainSchedule trainSchedule, string[] trainBranchRights, int createBy)
        {
            using (var edb = new EmeEntities())
            {
                using (var tran = new TransactionScope())
                {
                    try
                    {
                        //针对主讲人生成订课记录
                        var result = 100; //Default Create Result
                        if (trainSchedule.SpeakerId.HasValue)
                        {

                            if (
                                edb.UserSchedule.Any(
                                    p => p.BeginTime < trainSchedule.EndTime && p.EndTime > trainSchedule.BeginTime
                                         && p.Status == ConvertEnum.StatusTypeForActive
                                         && p.UserId == trainSchedule.SpeakerId))
                            {
                                result = 101; //已存在其他安排
                                return result;
                            }
                            if (
                                edb.TrainSchedule.Any(
                                    p => p.BeginTime < trainSchedule.EndTime && p.EndTime > trainSchedule.BeginTime
                                         && p.SpeakerId == trainSchedule.SpeakerId &&
                                         p.Status == ConvertEnum.StatusTypeForActive))
                            {
                                result = 103; //已存在其他培训
                                return result;
                            }
                            if (edb.TrainRecord.Any(p =>
                                p.TrainSchedule.BeginTime < trainSchedule.EndTime &&
                                p.TrainSchedule.EndTime > trainSchedule.BeginTime
                                && p.Status == ConvertEnum.StatusTypeForActive
                                && p.UserId == trainSchedule.SpeakerId))
                            {
                                return 104; //主讲人已预订其他培训
                            }

                            edb.Entry(trainSchedule).State = EntityState.Added;
                            edb.SaveChanges();

                            if (trainBranchRights.Length > 0)
                            {
                                //Create Train Branch Rights
                                foreach (var bId in trainBranchRights.Select(CommonHelper.To<int>))
                                {
                                    if (bId > 0)
                                    {
                                        edb.TrainRights.Add(new TrainRights()
                                        {
                                            BranchId = bId,
                                            TrainScheduleId = trainSchedule.Id,
                                            CreateBy = createBy,
                                            CreateTime = DateTime.Now
                                        });
                                    }
                                }
                            }

                            //当主讲人是老师时直接写入主讲人订课记录,提供老师端登入,并且视为主讲人进入会议平台
                            if (
                                edb.Teacher.Any(
                                    p =>
                                        p.UserId == trainSchedule.SpeakerId &&
                                        p.Status == ConvertEnum.StatusTypeForActive))
                            {
                                if (trainSchedule.SpeakerId != null)
                                {
                                    var model = new TrainRecord()
                                    {
                                        TrainScheduleId = trainSchedule.Id,
                                        UserId = trainSchedule.SpeakerId.Value,
                                        MeetingAttendType = ConvertEnum.MeetingAttendTypeForSpeaker,
                                        IsUnBook = false,
                                        Status = ConvertEnum.StatusTypeForActive,
                                        CreateBy = createBy,
                                        CreateTime = DateTime.Now
                                    };

                                    edb.Entry(model).State = EntityState.Added;
                                }
                            }
                        }

                        //写入任务
                        if (trainSchedule.SpeakerId != null)
                        {
                            var userTaskModel = new UserTask()
                            {
                                IsSystem = true,
                                IsComplete = false,
                                Status = ConvertEnum.StatusTypeForActive,
                                BeginTime = trainSchedule.BeginTime,
                                EndTime = trainSchedule.EndTime,
                                TaskValue = trainSchedule.Id,
                                TaskNum = 1,
                                TaskType = ConvertEnum.TaskTypeForTraining,
                                CreateBy = createBy,
                                CreateTime = DateTime.Now,
                                UserId = trainSchedule.SpeakerId.Value
                            };
                            edb.Entry(userTaskModel).State = EntityState.Added;
                        }
                        result = edb.SaveChanges() > 0 ? 100 : 102; //添加需要指定中心权限
                        tran.Complete();
                        return result;
                    }
                    catch (Exception e)
                    {
                        tran.Dispose();

                        // 异常日志消息队列
                        Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs()
                        {
                            ExceptionType = CommonHelper.To<int>(ExceptionType.Function),
                            Message =
                                string.Format("TrainBLL-CreateTrainSchedule:{0};{1};{2}", e.Message,
                                    e.InnerException.Message, e.HelpLink),
                            IsTreat = false,
                            CreateBy = createBy,
                            CreateTime = DateTime.Now
                        });

                        return 105;
                    }
                }

            }
        }
Example #41
0
 public void Dispose()
 {
     _transaction?.Dispose();
 }
Example #42
0
        public void TransactionScope()
        {
            using (var connection = GetConnection())
            {
                using (var txscope = new TransactionScope())
                {
                    connection.Open();  //connection MUST be opened inside the transactionscope

                    var id = connection.Insert(new Car { Name = "one car" });   //inser car within transaction

                    txscope.Dispose();  //rollback

                    connection.Get<Car>(id).IsNull();   //returns null - car with that id should not exist
                }
            }
        }
Example #43
0
        /// <summary>
        /// 作者:Kylin
        /// 时间:2014.04.10
        /// 描述:创建培训计划 (test ing )
        /// </summary>
        /// <param name="trainSchedule"></param>
        /// <param name="trainBranchRights">分配的中心Ids</param>
        /// <param name="editSpeaker"></param>
        /// <param name="updateBy"></param>
        /// <returns></returns>
        public static int UpdateTrainSchedule(TrainSchedule trainSchedule, string[] trainBranchRights, int editSpeaker, int updateBy)
        {
            using (var edb = new EmeEntities())
            {
                using (var tran = new TransactionScope())
                {
                    try
                    {
                        //针对主讲人生成订课记录
                        if (trainSchedule.Id <= 0 || !edb.TrainSchedule.Any(p => p.Id == trainSchedule.Id && p.Status == ConvertEnum.StatusTypeForActive))
                        {
                            return 106; // no schedule existed
                        }

                        //check online training is booked for any students
                        if (edb.TrainSchedule.Any(p => p.Id == trainSchedule.Id && p.Status == ConvertEnum.StatusTypeForActive
                            && p.MeetingPlatformType != trainSchedule.MeetingPlatformType
                            && p.TrainRecord.Any(t => t.TrainScheduleId == p.Id && !t.IsUnBook && t.Status == ConvertEnum.StatusTypeForActive && t.UserId != p.SpeakerId)))
                        {
                            return 108; // exist anyone booked this shcedule and try to change online or offline setting
                        }

                        if (trainSchedule.SpeakerId.HasValue)
                        {

                            //Check is validate for speaker
                            var isValidate = CheckTrainingScheduleIsValidate(trainSchedule, trainSchedule.SpeakerId == editSpeaker);
                            if (isValidate > 0)
                            {
                                return isValidate;
                            }

                            //Delete history schedule speaker's schedule and tasks
                            #region update schedule

                            //update主讲人记录
                            var speakerRecords = edb.TrainRecord.Where(p => p.TrainScheduleId == trainSchedule.Id
                           && p.Status == ConvertEnum.StatusTypeForActive
                           && p.UserId == editSpeaker);
                            if (speakerRecords.Any())
                            {
                                foreach (var trainRecord in speakerRecords)
                                {
                                    trainRecord.Status = ConvertEnum.StatusTypeForActive;
                                    trainRecord.UpdateBy = updateBy;
                                    trainRecord.UpdateTime = DateTime.Now;
                                    trainRecord.UserId = (int)trainSchedule.SpeakerId;
                                    edb.Entry(trainRecord).State = EntityState.Modified;
                                }
                            }
                            else
                            {
                                //当主讲人是老师时直接写入主讲人订课记录,提供老师端登入,并且视为主讲人进入会议平台
                                if (
                                    edb.Teacher.Any(
                                        p =>
                                            p.UserId == trainSchedule.SpeakerId &&
                                            p.Status == ConvertEnum.StatusTypeForActive))
                                {
                                    if (trainSchedule.SpeakerId != null)
                                    {
                                        var model = new TrainRecord()
                                        {
                                            TrainScheduleId = trainSchedule.Id,
                                            UserId = trainSchedule.SpeakerId.Value,
                                            MeetingAttendType = ConvertEnum.MeetingAttendTypeForSpeaker,
                                            IsUnBook = false,
                                            Status = ConvertEnum.StatusTypeForActive,
                                            CreateBy = updateBy,
                                            CreateTime = DateTime.Now
                                        };

                                        edb.Entry(model).State = EntityState.Added;
                                    }
                                }
                            }

                            var trainRights = edb.TrainRights.Where(p => p.TrainScheduleId == trainSchedule.Id);

                            foreach (var right in trainRights) //删除历史中心权限
                            {
                                edb.Entry(right).State = EntityState.Deleted;
                            }

                            var trainAttachment = trainSchedule.TrainAttachment;

                            foreach (var attachment in trainAttachment) //删除历史附件
                            {

                                attachment.UpdateBy = updateBy;
                                attachment.UpdateTime = DateTime.Now;
                                attachment.Status = ConvertEnum.StatusTypeForDelete;
                                edb.Entry(attachment).State = EntityState.Modified;
                            }

                            //取消任务
                            var modelUserTaskList = edb.UserTask.Where(p => p.TaskType == ConvertEnum.TaskTypeForTraining
                                && p.TaskValue == trainSchedule.Id
                                && p.BeginTime == trainSchedule.BeginTime
                                && p.EndTime == trainSchedule.EndTime).ToList();
                            foreach (var item in modelUserTaskList)
                            {
                                item.UpdateTime = DateTime.Now;
                                item.UpdateBy = updateBy;
                                item.Status = ConvertEnum.StatusTypeForDelete;
                                edb.Entry(item).State = EntityState.Modified;
                            }

                            #endregion

                            //update Schedule
                            trainSchedule.UpdateBy = updateBy;
                            trainSchedule.UpdateTime = DateTime.Now;
                            edb.Entry(trainSchedule).State = EntityState.Modified;

                            //Create BranchRights
                            if (trainBranchRights.Length > 0)
                            {
                                //Create Train Branch Rights
                                foreach (var bId in trainBranchRights.Select(CommonHelper.To<int>))
                                {
                                    if (bId > 0)
                                    {
                                        edb.TrainRights.Add(new TrainRights()
                                        {
                                            BranchId = bId,
                                            TrainScheduleId = trainSchedule.Id,
                                            CreateBy = updateBy,
                                            CreateTime = DateTime.Now
                                        });
                                    }
                                }
                            }

                            //写入任务
                            if (trainSchedule.SpeakerId != null)
                            {
                                var userTaskModel = new UserTask()
                                {
                                    IsSystem = true,
                                    IsComplete = false,
                                    Status = ConvertEnum.StatusTypeForActive,
                                    BeginTime = trainSchedule.BeginTime,
                                    EndTime = trainSchedule.EndTime,
                                    TaskValue = trainSchedule.Id,
                                    TaskNum = 1,
                                    TaskType = ConvertEnum.TaskTypeForTraining,
                                    CreateBy = updateBy,
                                    CreateTime = DateTime.Now,
                                    UserId = trainSchedule.SpeakerId.Value
                                };
                                edb.Entry(userTaskModel).State = EntityState.Added;
                            }
                            var result = edb.SaveChanges() > 0 ? 100 : 102; //添加需要指定中心权限
                            tran.Complete();
                            return result;
                        }
                        else
                        {
                            return 107;//speaker not exists
                        }
                    }
                    catch (Exception e)
                    {
                        tran.Dispose();

                        // 异常日志消息队列
                        Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs()
                        {
                            ExceptionType = CommonHelper.To<int>(ExceptionType.Function),
                            Message =
                                string.Format("TrainBLL-UpdateTrainSchedule:{0};{1};{2}", e.Message,
                                    e.InnerException.Message, e.HelpLink),
                            IsTreat = false,
                            CreateBy = updateBy,
                            CreateTime = DateTime.Now
                        });

                        return 105;
                    }
                }

            }
        }
 public void Dispose()
 {
     _transaction?.Dispose();
     _enumerator?.Dispose();
 }
 /// <summary>
 ///
 /// </summary>
 public void End()
 {
     _transaction.Complete();
     _transaction?.Dispose();
 }
 public virtual void Dispose()
 {
     Transaction.Current?.Rollback();
     _transactionScope?.Dispose();
 }
Example #47
0
        /// <summary>
        /// 作者:Raymond
        /// 日期:2014-5-13
        /// 描述:更新合同及其明细(合同冻结、解冻、延期)
        /// </summary>
        /// <param name="contract"></param>
        /// <param name="endDate"></param>
        /// <param name="updateTime"></param>
        /// <param name="updateBy"></param>
        /// <param name="contractStatusType"></param>
        /// <returns></returns>
        public static bool UpdateContract(Contract contract, DateTime endDate, DateTime? updateTime, int updateBy, int contractStatusType, int loginUserId)
        {
            using (var edb = new EmeEntities())
            {
                using (var tran = new TransactionScope())
                {
                    try
                    {
                        //获取新对象
                        var contractObj = edb.Contract.FirstOrDefault(p => p.Id == contract.Id);

                        //合同主表信息
                        contractObj.EndDate = endDate;
                        contractObj.UpdateTime = updateTime;
                        contractObj.UpdateBy = updateBy;
                        //是否合同结束,合同结束status状态设置为不可用。
                        if (contractStatusType == CommonHelper.To<int>(ContractStatusType.Over))
                            contractObj.Status = ConvertEnum.StatusTypeForInactive;
                        edb.Entry(contractObj).State = EntityState.Modified;
                        //处理合同明细
                        foreach (var detail in contractObj.ContractDetail)
                        {
                            detail.EndDate = endDate;
                            detail.ContractStatusType = contractStatusType;
                            detail.UpdateBy = updateBy;
                            detail.UpdateTime = updateTime;
                            //是否合同结束,合同结束status状态设置为不可用。
                            if (contractStatusType == CommonHelper.To<int>(ContractStatusType.Over))
                            {
                                detail.Status = ConvertEnum.StatusTypeForInactive;
                                //合同级别信息的状态也设置为不可用
                                foreach (var level in detail.ContractLevel)
                                {
                                    level.Status = ConvertEnum.StatusTypeForInactive;
                                    edb.Entry(level).State = EntityState.Modified;
                                }
                            }
                            edb.Entry(detail).State = EntityState.Modified;
                        }
                        var result = edb.SaveChanges() > 0;
                        tran.Complete();
                        return result;
                    }
                    catch (Exception e)
                    {
                        tran.Dispose();
                        // 异常日志消息队列
                        Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs()
                        {
                            ExceptionType = CommonHelper.To<int>(ExceptionType.Function),
                            Message = string.Format("StudentBLL-UpdateContract:{0};{1};{2}", e.Message, e.InnerException.Message, e.HelpLink),
                            IsTreat = false,
                            CreateBy = loginUserId,
                            CreateTime = DateTime.Now
                        });

                        return false;
                    }
                }
            }
        }
Example #48
0
        public void ExplicitTransaction6b()
        {
            CommittableTransaction ct = new CommittableTransaction();

            IntResourceManager irm = new IntResourceManager(1);

            Transaction.Current = ct;
            try
            {
                TransactionScope scope1 = new TransactionScope();
                /* Enlist */
                irm.Value = 2;

                scope1.Complete();

                Assert.Throws<TransactionAbortedException>(() => ct.Commit());
                irm.Check(0, 0, 1, 0, "irm");

                scope1.Dispose();
            }
            finally
            {
                Transaction.Current = null;
            }
        }
Example #49
0
        /// <summary>
        /// 作者:beta
        /// 时间:2014.07.22
        /// 描述:更新当前合同级别 (修改合同执行级别、订退课记录、修改置换级别)
        /// </summary>
        /// <param name="higestContractLevelId"></param>
        /// <param name="currContractLevelId"></param>
        /// <param name="contractLevelId"></param>
        /// <param name="studentId"></param>
        /// <param name="productLevelId"></param>
        /// <param name="updateUser"></param>
        /// <returns></returns>
        public static bool UpdateContractLevel(int higestContractLevelId, int currContractLevelId, int contractLevelId, int studentId, int productLevelId, int updateUser)
        {
            using (var edb = new EmeEntities())
            {
                using (var tran = new TransactionScope())
                {
                    try
                    {
                        //更新合同级别信息
                        var contractLevelObj = edb.ContractLevel.FirstOrDefault(p => p.Id == contractLevelId);
                        contractLevelObj.IsCurrent = false;
                        contractLevelObj.UpdateBy = updateUser;
                        contractLevelObj.UpdateTime = DateTime.Now;
                        edb.Entry(contractLevelObj).State = EntityState.Modified;

                        //更改订退课记录信息
                        var bookRecordObj = edb.BookRecord.Where(p => p.StudentId == studentId
                            && p.Status == ConvertEnum.StatusTypeForActive && !p.IsUnBook &&
                            p.ArrangeCourse.ProductLevelCourseTypeCourse.ProductLevelCourseType.ProductLevelId == productLevelId
                            && !p.ContractLevelId.HasValue);
                        if (null != bookRecordObj)
                        {
                            foreach (var record in bookRecordObj)
                            {
                                record.ContractLevelId = contractLevelId;
                                edb.Entry(record).State = EntityState.Modified;
                            }
                        }

                        //修改置换级别状态
                        var replaceContractLevel = edb.ContractLevel.FirstOrDefault(p => p.Id == higestContractLevelId && p.Status == ConvertEnum.StatusTypeForActive);
                        replaceContractLevel.Status = ConvertEnum.StatusTypeForInactive;
                        edb.Entry(replaceContractLevel).State = EntityState.Modified;

                        var result = edb.SaveChanges() > 0;
                        tran.Complete();
                        return result;
                    }
                    catch (Exception e)
                    {
                        tran.Dispose();
                        // 异常日志消息队列
                        Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs()
                        {
                            ExceptionType = CommonHelper.To<int>(ExceptionType.Function),
                            Message = string.Format("StudentBLL-UpdateContract:{0};{1};{2}", e.Message, e.InnerException.Message, e.HelpLink),
                            IsTreat = false,
                            CreateBy = updateUser,
                            CreateTime = DateTime.Now
                        });

                        return false;
                    }
                }
            }
        }
Example #50
0
        public void ExplicitTransaction6e()
        {
            CommittableTransaction ct = new CommittableTransaction();

            IntResourceManager irm = new IntResourceManager(1);

            Transaction.Current = ct;
            try
            {
                TransactionScope scope1 = new TransactionScope();
                /* Enlist */
                irm.Value = 2;

                TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress);
                Assert.Throws<InvalidOperationException>(() => scope1.Dispose());
                scope2.Dispose();
            }
            finally
            {
                Transaction.Current = null;
            }
        }
Example #51
0
        /// <summary>
        /// 作者:Vincen
        /// 时间:2014.05.02
        /// 描述:创建合同级别课程类型(对应V3.0Topic自选)
        /// </summary>
        /// <param name="studentId"></param>
        /// <param name="productLevelId"></param>
        /// <param name="productLevelCourseTypeIdList"></param>
        /// <param name="createBy"></param>
        /// <returns></returns>
        public static bool CreateContractLevelCourseType(int studentId, int productLevelId, string productLevelCourseTypeIdList, int createBy)
        {
            using (var edb = new EmeEntities())
            {
                using (var tran = new TransactionScope())
                {
                    try
                    {
                        // 检验合同级别是否匹配
                        var contractLevel = edb.ContractLevel.FirstOrDefault(p => p.ContractDetail.Contract.StudentId == studentId && p.ProductLevelId == productLevelId && p.Status == ConvertEnum.StatusTypeForActive);
                        if (null == contractLevel) return false;

                        // 实例化 ContractLevelCourseType 集合
                        var plctlist = productLevelCourseTypeIdList.Trim().Trim(',').Split(',');

                        foreach (var item in plctlist.Select(a => new ContractLevelCourseType()
                        {
                            ContractLevelId = contractLevel.Id,
                            ProductLevelCourseTypeId = CommonHelper.To<int>(a),
                            Status = ConvertEnum.StatusTypeForActive,
                            CreateBy = createBy,
                            CreateTime = DateTime.Now
                        }))
                        {
                            edb.Entry(item).State = EntityState.Added;
                        }

                        var result = edb.SaveChanges() > 0;
                        tran.Complete();
                        return result;
                    }
                    catch (Exception e)
                    {
                        tran.Dispose();

                        // 异常日志消息队列
                        Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs()
                        {
                            ExceptionType = CommonHelper.To<int>(ExceptionType.Function),
                            Message = string.Format("StudentBLL-CreateContractLevelCourseType:{0};{1};{2}", e.Message, e.InnerException.Message, e.HelpLink),
                            IsTreat = false,
                            CreateBy = createBy,
                            CreateTime = DateTime.Now
                        });

                        return false;
                    }
                }
            }
        }
Example #52
0
 public void Dispose()
 {
     _transactionScope?.Dispose();
 }
Example #53
0
        void Import( )
        {
            DataTable dt = CacheTable(null);
            if (dt == null)
            {
                lblErrorInfo2.Text = "导入数据不存在!";
                return;
            }
            DataColumn cCol = dt.Columns[CHECK_COL];
            string strCheck;
            TransactionScope ts = new TransactionScope( );
            SharedDbConnectionScope ss = new SharedDbConnectionScope( );
            try
            {
                foreach (DataRow row in dt.Rows)
                {
                    strCheck = Utilities.ToString(row[cCol]);
                    if (strCheck == string.Empty || strCheck == "-1")
                        continue;
                    SysMember user = SaveMemberData(row);
                    SaveMemberCash(row, user);
                    SaveMemberCompany(row, user);

                }
                AppContext.Context.Company.MarkClean( );
                AppContext.Context.Company.MarkOld( );
                AppContext.Context.Company.IsUseFinger = false;
                AppContext.Context.Company.Save( );
                OrderBLL.UpdateBalance( );
                ts.Complete( );
                lblErrorInfo2.Text = "导入成功!";
                btnPost.Enabled = false;
            }
            catch (Exception ex)
            {
                Logging.Log("MemberExportIn->Import", ex,true);
                lblErrorInfo2.Text = ex.Message + Environment.NewLine + ex.StackTrace;
            }
            finally
            {
                ss.Dispose( );
                ts.Dispose( );
                tbPost.Visible = true;
                btnPost.Enabled = false;
                btnCheck.Enabled = false;
            }
        }
        public ActionResult _CreateOrUpdateFile(TD_FileHoSoDinhKem obj)
        {
            var user = S4T_HaTinhBase.GetUserSession();
            if (user == null) return RedirectToAction("Login", "Account", new { returnUrl = Request.Url.PathAndQuery });
            var per = S4T_HaTinhBase.CheckPermission(Request.RequestContext.RouteData.GetRequiredString("controller"));
            if (per != PermissionType.Write) return Content(ExceptionViewer.GetMessage("UPDATE_NOT_PERMISSION"));

            List<TD_FileHoSoDinhKem> list = (List<TD_FileHoSoDinhKem>)TempData["TD_FileHoSoDinhKem_" + user.Id];
            if (list == null) list = new List<TD_FileHoSoDinhKem>();
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    if (Request.Files.Count > 0)
                    {
                        var file = Request.Files[0];
                        if (file.ContentLength > 0)
                        {
                            var maxSize = 16384 * 1024; // in Byte

                            // Kiểm tra giới hạn dung lượng file upload cho phép
                            if (file.ContentLength > maxSize)
                            {
                                ModelState.AddModelError("", "Dung lượng file vượt quá dung lượng cho phép tải lên");
                                return View(obj);
                            }

                            if (string.IsNullOrEmpty(pathSource)) return Content("Không tìm thấy đường dẫn file");

                            // Xóa file tạm trong db
                            if (!string.IsNullOrEmpty(obj.TenFile))
                            {
                                TD_FileHoSoDinhKem objRemove = list.FirstOrDefault(o => o.TenFile == obj.TenFile);
                                list.Remove(objRemove);
                                System.IO.File.Delete(objRemove.DuongDan);
                            }

                            // Lưu đường dẫn file theo mã hồ sơ
                            string duongDan = pathSource + "/TD_HoSoDuAn/Upload/" + User.Identity.GetUserId();
                            if (!Directory.Exists(duongDan)) Directory.CreateDirectory(duongDan);
                            string fileName = obj.MaHoSo + "_" + Guid.NewGuid().ToString() + "_" + User.Identity.GetUserId() + "_" + Path.GetFileName(file.FileName);

                            // Lưu file vào thư mục tạm của hệ thống
                            string path = Path.Combine(duongDan, fileName);
                            file.SaveAs(path);

                            #region Lưu đường dẫn, thông tin file vào db
                            obj.DuongDan = path;
                            obj.TenFile = fileName;
                            obj.TenHienThi = Path.GetFileName(file.FileName);
                            obj.TrangThai = TrangThai.HoatDong;
                            
                            if (obj.VanBan_ID == 0)
                            {
                                ViewBag.btnId = "btnRefreshListFile";
                                string phuLucHoSoKhac = ConfigurationManager.AppSettings["PhuLucHoSoKhac"];
                                obj.VanBan_ID = string.IsNullOrEmpty(phuLucHoSoKhac) ? 0 : Convert.ToInt32(phuLucHoSoKhac);
                            }
                            else
                            {
                                ViewBag.btnId = "btnRefreshListFileQuyetDinh";
                            }

                            list.Add(obj);

                            TempData["TD_FileHoSoDinhKem_" + user.Id] = list;

                            scope.Complete();
                            #endregion Lưu đường dẫn, thông tin file vào db
                        }
                        else
                        {
                            ViewBag.Mess = "<span style=\"color:red;\">Chưa chọn file</span>";
                            return View(obj);
                        }
                    }
                    else
                    {
                        ViewBag.Mess = "<span style=\"color:red;\">Chưa chọn file</span>";
                        return View(obj);
                    }

                    // Close popup và refresh form main
                    ViewBag.RefreshPage = true;
                }
                catch (DbEntityValidationException ex)
                {
                    var exc = new ExceptionViewer();
                    ViewBag.Mess = exc.GetError(ex);
                    scope.Dispose();
                }
            }

            return View(obj);
        }
Example #55
0
 public virtual void Dispose()
 {
     _transaction?.Dispose();
     _serviceProvider?.Dispose();
 }
        //[ValidateAntiForgeryToken]
        //public ActionResult UpdateThongTinChung(TD_HoSoDuAn tD_HoSoDuAn, List<TD_FileHoSoDinhKem> listFile, HttpPostedFileBase upload_0, HttpPostedFileBase upload_1, HttpPostedFileBase upload_2)
        public ActionResult UpdateThongTinChung(TD_HoSoDuAn tD_HoSoDuAn, List<TD_FileHoSoDinhKem> listFile, List<HttpPostedFileBase> listFileUp)
        {
            var user = S4T_HaTinhBase.GetUserSession();
            if (user == null)
                return RedirectToAction("Login", "Account", new { returnUrl = Request.Url.PathAndQuery });

            // Kiểm tra quyền truy cập và cập nhật
            var per = CheckPermission(user);
            if (!per.isEdit)
                return Content("Bạn không có quyền thực hiện chức năng này");

            var obj = db.TD_HoSoDuAn.FirstOrDefault(o => o.HoSoDuAn_ID == tD_HoSoDuAn.HoSoDuAn_ID);
            ModelState.Remove("TenDuAn");
            if (ModelState.IsValid)
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    try
                    {
                        // Mapping obj in db
                        obj.str1 = tD_HoSoDuAn.str1;
                        obj.NhaThau = tD_HoSoDuAn.NhaThau;
                        obj.MucTieu = obj.MucTieu;
                        obj.QuyMo = tD_HoSoDuAn.QuyMo;
                        obj.DiaDiem = tD_HoSoDuAn.DiaDiem;
                        obj.NguonVon = tD_HoSoDuAn.NguonVon;
                        obj.HinhThucQuanLy_ID = tD_HoSoDuAn.HinhThucQuanLy_ID;
                        obj.HinhThucQuanLyKhac = tD_HoSoDuAn.HinhThucQuanLyKhac;
                        obj.int1 = tD_HoSoDuAn.int1;
                        obj.int2 = tD_HoSoDuAn.int2;
                        obj.QuyTrinhQuanLy = tD_HoSoDuAn.QuyTrinhQuanLy;
                        obj.NhomDuAn_ID = tD_HoSoDuAn.NhomDuAn_ID;
                        obj.LoaiDuAn_ID = tD_HoSoDuAn.LoaiDuAn_ID;
                        obj.TinhChatDuAn_ID = tD_HoSoDuAn.TinhChatDuAn_ID;
                        obj.TinhTrangThucHien = tD_HoSoDuAn.TinhTrangThucHien;
                        obj.TongMucDauTu = tD_HoSoDuAn.TongMucDauTu;
                        obj.ChiPhiXayLap = tD_HoSoDuAn.ChiPhiXayLap;
                        obj.ChiPhiThietBi = tD_HoSoDuAn.ChiPhiThietBi;
                        obj.ChiPhiQuanLy = tD_HoSoDuAn.ChiPhiQuanLy;
                        obj.ChiPhiTuVan = tD_HoSoDuAn.ChiPhiTuVan;
                        obj.ChiPhiKhac = tD_HoSoDuAn.ChiPhiKhac;
                        obj.ChiPhiDuPhong = tD_HoSoDuAn.ChiPhiDuPhong;
                        obj.NganSachTrungUong = tD_HoSoDuAn.NganSachTrungUong;
                        obj.NganSachTinh = tD_HoSoDuAn.NganSachTinh;
                        obj.NganSachDonVi = tD_HoSoDuAn.NganSachDonVi;
                        obj.NguonKhac = tD_HoSoDuAn.NguonKhac;
                        obj.HangMucTrienKhai = tD_HoSoDuAn.HangMucTrienKhai;
                        obj.ThoiGianHoanThanh = tD_HoSoDuAn.ThoiGianHoanThanh;
                        obj.SanPhamHangMuc = tD_HoSoDuAn.SanPhamHangMuc;
                        obj.KinhPhiThucHienHangMuc = tD_HoSoDuAn.KinhPhiThucHienHangMuc;
                        obj.KetQuaDauTu = tD_HoSoDuAn.KetQuaDauTu;

                        db.Entry(obj).State = EntityState.Modified;
                        db.SaveChanges();

                        // Lưu file vào hệ thống
                        List<TD_FileHoSoDinhKem> list = (List<TD_FileHoSoDinhKem>)TempData["TD_FileHoSoDinhKem_" + user.Id];
                        if (list.Any())
                        {
                            TempData["TD_FileHoSoDinhKem_" + user.Id] = list;
                            string duongDanVatLy = pathSource + "/TD_HoSoDuAn";
                            string phuLucHoSoKhac = ConfigurationManager.AppSettings["PhuLucHoSoKhac"];
                            int intPhuLucHoSoKhac = string.IsNullOrEmpty(phuLucHoSoKhac) ? 0 : Convert.ToInt32(phuLucHoSoKhac);
                            if (!Directory.Exists(duongDanVatLy))
                                Directory.CreateDirectory(duongDanVatLy);

                            var listFileInDb = db.TD_FileHoSoDinhKem.Where(o => o.TrangThai == TrangThai.HoatDong && o.MaHoSo == obj.MaHoSo && o.VanBan_ID == intPhuLucHoSoKhac);

                            for (var i = 0; i < list.Count; i++)
                            {
                                // Insert
                                if (list[i].FileHoSoDinhKem_ID == 0)
                                {
                                    string path = Path.Combine(duongDanVatLy, list[i].TenFile);

                                    // To copy a file to another location and 
                                    // overwrite the destination file if it already exists.
                                    System.IO.File.Copy(list[i].DuongDan, path, true);

                                    // đổi đường dẫn file
                                    list[i].DuongDan = path;

                                    // Lưu obj file vào db
                                    db.TD_FileHoSoDinhKem.Add(list[i]);
                                    db.SaveChanges();
                                }
                                //Update
                                else
                                {

                                }
                            }
                        }

                        // Lưu các file quyết định phê duyệt (nếu có đính kèm)
                        if(Request.Files.Count > 0)
                        {
                            if (string.IsNullOrEmpty(pathSource)) return Content("Không tìm thấy đường dẫn file");

                            //var duongDan = pathSource + "/TD_HoSoDuAn/NewUpload/" + User.Identity.GetUserId();
                            //if (!Directory.Exists(duongDan))
                            //    Directory.CreateDirectory(duongDan);

                            var duongDanVatLy = pathSource + "/TD_HoSoDuAn";
                            if (!Directory.Exists(duongDanVatLy))
                                Directory.CreateDirectory(duongDanVatLy);
                            
                            var indexFile = 0;
                            var stt = db.TD_FileHoSoDinhKem.Where(o => o.TrangThai == TrangThai.HoatDong && o.MaHoSo == tD_HoSoDuAn.MaHoSo).Max(o => o.STT);
                            if (stt == null || stt == 0)
                                stt = 1;

                            for (int i = 0; i < Request.Files.Count; i++)
                            {
                                var file = Request.Files[i];
                                if (file.ContentLength > 0)
                                {
                                    // Tạo tên file lưu trên hệ thống
                                    var fileName = tD_HoSoDuAn.HoSoDuAn_ID + "_" + tD_HoSoDuAn.LoaiDuAn_ID + "_" + Guid.NewGuid().ToString() + "_" + Path.GetFileName(file.FileName);

                                    // Lưu file lên hệ thống
                                    var path = Path.Combine(duongDanVatLy, fileName);
                                    file.SaveAs(path);

                                    // Tạo object TD_FileHoSoDinhKem                                    
                                    var objFileDinhKem = new TD_FileHoSoDinhKem
                                    {
                                        DuongDan = path,
                                        SoKyHieu = listFile[indexFile].SoKyHieu,
                                        MaHoSo = tD_HoSoDuAn.MaHoSo,
                                        STT = stt,
                                        TenFile = fileName,
                                        TenHienThi = Path.GetFileName(file.FileName),
                                        TrichYeu = listFile[indexFile].TrichYeu,
                                        VanBan_ID = listFile[indexFile].VanBan_ID,
                                        TrangThai = TrangThai.HoatDong
                                    };

                                    // Lưu thông tin file vào db
                                    db.TD_FileHoSoDinhKem.Add(objFileDinhKem);
                                    stt++; // Cộng số thứ tự file thêm 1 nếu đã lưu 1 file thành công
                                }
                                indexFile++;
                            }
                        }

                        db.SaveChanges();
                        scope.Complete();

                        // Xóa file đã đính kèm trước đó đi trong thư mục
                        if (Directory.Exists(pathSource + "/TD_HoSoDuAn/Upload/" + User.Identity.GetUserId()))
                        {
                            string[] filesPath = Directory.GetFiles(pathSource + "/TD_HoSoDuAn/Upload/" + User.Identity.GetUserId());
                            if (filesPath.Length > 0)
                            {
                                foreach (string item in filesPath)
                                {
                                    if (!string.IsNullOrEmpty(item))
                                        System.IO.File.Delete(item);
                                }
                            }
                        }

                        return RedirectToAction("ThongTinChung");
                    }
                    catch (DbEntityValidationException ex)
                    {
                        scope.Dispose();
                        var exc = new ExceptionViewer();
                        exc.GetError(ex);
                    }
                }
            }
            GetModelStateError(ViewData);
            ViewBag.TenDuAn = obj.TenDuAn;
            ViewBag.ChuDauTu = obj.ChuDauTu;
            var listVBQuyetDinh = db.View_Loai_Nhom_VanBan.Where(o => o.TrangThai == TrangThai.HoatDong && o.MaNhomVanBan == "QuyetDinhPheDuyet");
            ViewBag.ListVBQuyetDinh = listVBQuyetDinh.Any() ? listVBQuyetDinh.ToList() : new List<View_Loai_Nhom_VanBan>();
            var _listFile = db.TD_FileHoSoDinhKem.Where(o => o.TrangThai == TrangThai.HoatDong && o.MaHoSo == tD_HoSoDuAn.MaHoSo);
            if (_listFile.Any())
                tD_HoSoDuAn.ListFile = _listFile.ToList();
            else
                tD_HoSoDuAn.ListFile = new List<TD_FileHoSoDinhKem>();
            GetViewBag(ViewReport.Edit);
            return View(tD_HoSoDuAn);
        }
Example #57
0
        /// <summary>
        /// 作者:Primo
        /// 日期:2014.06.24
        /// 描述:新增产品课节
        /// </summary>
        /// <param name="pLevelCourseTypeCourse"></param>
        /// <param name="course"></param>
        /// <returns></returns>
        public static bool CreateProductLevelCourseTypeCourse(ProductLevelCourseTypeCourse pLevelCourseTypeCourse, Course course, int loginUserId)
        {
            using (var edb = new EmeEntities())
            {
                using (var tran = new TransactionScope())
                {
                    try
                    {
                        var result = false;
                        var modelCourse = edb.Course.FirstOrDefault(p => p.CName == course.CName && p.Status == ConvertEnum.StatusTypeForActive);
                        var courseId = 0;

                        edb.Entry(course).State = EntityState.Added;
                        result = edb.SaveChanges() > 0;
                        courseId = course.Id;

                        pLevelCourseTypeCourse.CourseId = courseId;
                        edb.Entry(pLevelCourseTypeCourse).State = EntityState.Added;
                        result = edb.SaveChanges() > 0;
                        tran.Complete();
                        return result;
                    }
                    catch (Exception e)
                    {
                        tran.Dispose();
                        // 异常日志消息队列
                        Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs()
                        {
                            ExceptionType = CommonHelper.To<int>(ExceptionType.Function),
                            Message = string.Format("ProductBLL-CreateProductLevelCourseTypeCourse:{0};{1};{2}", e.Message, e.InnerException.Message, e.HelpLink),
                            IsTreat = false,
                            CreateBy = loginUserId,
                            CreateTime = DateTime.Now
                        });
                        return false;
                    }
                }
            }
        }
 public void TearDown()
 {
     tarnsaction?.Dispose();
 }
Example #59
0
 public void AfterTest(ITest test)
 {
     _scope?.Dispose();
     _scope = null;
 }
Example #60
0
 public void Complete()
 {
     scope?.Complete();
     scope?.Dispose();
 }