Complete() 공개 메소드

public Complete ( ) : void
리턴 void
예제 #1
1
        public void GuardarAsignaciones(IList<int> ordenesVenta, IList<Usuario> asistentes)
        {
            try
            {
                var transactionOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted };

                using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
                {
                    foreach (var idOrdenVenta in ordenesVenta)
                    {
                        var ordenVenta = _orderVentaDA.ObtenerPorID(idOrdenVenta);

                        var asistenteConMenorCarga = asistentes.OrderBy(p => p.CantidadOV).FirstOrDefault();

                        if (asistenteConMenorCarga != null)
                        {
                            asistenteConMenorCarga.CantidadOV++;

                            ordenVenta.Estado = Constantes.EstadoOrdenVenta.Asignado;
                            ordenVenta.AsistentePlaneamiento = asistenteConMenorCarga;

                            _orderVentaDA.AsignarAsistentePlaneamiento(ordenVenta);
                        }
                    }

                    transactionScope.Complete();
                }
            }
            catch (Exception ex)
            {
                throw ThrowException(ex, MethodBase.GetCurrentMethod().Name);
            }
        }
		public void TransactionScopeCompleted3 ()
		{
			using (TransactionScope scope = new TransactionScope ()) {
				scope.Complete ();
				scope.Complete ();
			}
		}
예제 #3
0
        /// <summary>
        /// ���޸Ŀ����ǰ��ɣ�����ǰ������Ͳ����ˡ�
        /// </summary>
        /// <param name="productSysNo">��Ʒ���</param>
        /// <param name="hereQty">��������</param>
        /// <param name="hereCost">���γɱ�</param>
        public void SetCost(int productSysNo, int hereQty, decimal hereCost)
        {
            TransactionOptions options = new TransactionOptions();
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            options.Timeout = TransactionManager.DefaultTimeout;

            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
            {
                //��ȡ����Ʒ�ĵ�ǰ�ɱ�
                InventoryManager.GetInstance().InitInventory(productSysNo);
                InventoryInfo oInv = InventoryManager.GetInstance().LoadInventory(productSysNo);
                ProductPriceInfo oPrice = ProductManager.GetInstance().LoadPrice(productSysNo);

                int curQty = oInv.AccountQty;
                decimal curCost = oPrice.UnitCost;

                //�����ǰ�ɱ����ڱ��γɱ����ø�����
                if (curCost == hereCost)
                {
                    scope.Complete();
                    return;
                }

                decimal newCost = AppConst.DecimalNull;

                //�������Ϊ����߼�������ijɱ�Ϊ�����ñ��γɱ�����
                if ( curQty + hereQty == 0 )
                    newCost = hereCost;
                else
                {
                    newCost = Decimal.Round( (curQty*curCost + hereQty*hereCost) / ( curQty+hereQty)*1.0M, 2);
                    if ( newCost < 0 )
                        newCost = hereCost;
                }

                //�������������Ҳ���ø���
                if (newCost == curCost)
                {
                    scope.Complete();
                    return;
                }

                if ( newCost == AppConst.DecimalNull )
                    throw new BizException("calc cost error");

                //���³ɱ������ݿ�
                if ( 1!=new ProductPriceDac().UpdateCost(productSysNo, newCost))
                    throw new BizException("expected one-row update failed, cancel verify failed ");
                scope.Complete();
            }
        }
        public void Raven_dtc_bug()
        {
            new MessageQueue(QueueAddress, QueueAccessMode.ReceiveAndAdmin)
            .Purge();

            using (var tx = new TransactionScope())
            {

                using (var session = store.OpenSession())
                {
                    session.Store(new GatewayMessage());
                    session.SaveChanges();
                }

                using (var q = new MessageQueue(QueueAddress, QueueAccessMode.Send))
                {
                    var toSend = new Message { BodyStream = new MemoryStream(new byte[8]) };

                    //sending a message to a msmq queue causes raven to promote the tx
                    q.Send(toSend, MessageQueueTransactionType.Automatic);
                }

                //when we complete raven commits it tx but the DTC tx is never commited and eventually times out
                tx.Complete();
            }
            Thread.Sleep(1000);

            Assert.AreEqual(1,new MessageQueue(QueueAddress, QueueAccessMode.ReceiveAndAdmin)
            .GetAllMessages().Length);
        }
예제 #5
0
        public void addClickCount(string _code)
        {
            try
            {
                var r = DB.tblAdvertisements.Single(p => p.Code == _code);

                using (TransactionScope ts = new TransactionScope())
                {

                    if (r != null)
                    {
                        r.ClickCount += 1;
                        DB.SubmitChanges();
                        ts.Complete();
                    }
                }
            }
            catch (Exception e)
            {
                log.writeLog(DBHelper.strPathLogFile, e.Message
                                                        + CommonConstants.NEWLINE
                                                        + e.Source
                                                        + CommonConstants.NEWLINE
                                                        + e.StackTrace
                                                        + CommonConstants.NEWLINE
                                                        + e.HelpLink);
            }
        }
        /// <summary>
        /// To Save Settlement Of Accounts
        /// </summary>
        /// <param name="settlementOfAcct"></param>
        /// <returns></returns>
        public int SaveSettlementOfAccounts(SettlementOfAccountsDTO settlementOfAcct)
        {
            settlementofaccount settlementOfAcctEntity = new settlementofaccount();

            using (TransactionScope transactionScope = new TransactionScope())
            {
                AutoMapper.Mapper.Map(settlementOfAcct, settlementOfAcctEntity);

                ESalesUnityContainer.Container.Resolve<IGenericRepository<settlementofaccount>>().Save(settlementOfAcctEntity);

                BookingService bookingService = new BookingService();
                BookingDTO bookingDetail = bookingService.GetBookingDetailByBookingId(settlementOfAcct.Account_Booking_Id, true);

                //Set money receipt issued status flag to true and save booking details in database
                bookingDetail.Booking_AccountSettled = true;
                bookingDetail.Booking_AccountSettledDate = DateTime.Now.Date;   // Added by ansharma on 26-Sep-2012

                bookingService.SaveAndUpdateBookingDetail(bookingDetail);

                transactionScope.Complete();
            }

            //return value
            return settlementOfAcctEntity.Account_Id;
        }
예제 #7
0
        private static void list_video()
        {
            using (TransactionScope transactionScope = new TransactionScope())
            {
                SqlConnection sqlConnection = connect_database();

                using (SqlCommand command = new SqlCommand())
                {

                    command.Connection = sqlConnection;
                    command.CommandType = System.Data.CommandType.Text;
                    command.CommandText = String.Format("SELECT PkId,Id,Description FROM {0}", table_name);

                    try
                    {
                        SqlDataReader reader = command.ExecuteReader();
                        Console.WriteLine("\n List Video in Database");
                        Console.WriteLine("==============================");
                        while (reader.Read())
                        {
                            Console.WriteLine("ID: {0}, Name : {1}, Identifier : {2}", reader.GetValue(0), reader.GetValue(2), reader.GetValue(1));
                        }
                        Console.WriteLine("============================== \n");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("{0}", e);
                    }
                }
                disconnect_database(sqlConnection);
                transactionScope.Complete();
            }
        }
예제 #8
0
        public ActionResult CambiarVersionActualRubrica(String RubricaId, String Version, String TipoArtefacto)
        {
            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    var Actuales = RubricOnRepositoryFactory.GetVersionesRubricasRepository().GetWhere(x => x.RubricaId == RubricaId && x.TipoArtefacto == TipoArtefacto && x.EsActual == true);
                    foreach (var actual in Actuales)
                        actual.EsActual = false;

                    RubricOnRepositoryFactory.GetVersionesRubricasRepository().Update(Actuales);
                    RubricOnRepositoryFactory.SubmitChanges(true);

                    var VersionActual = RubricOnRepositoryFactory.GetVersionesRubricasRepository().GetOne(RubricaId, TipoArtefacto, Version);
                    VersionActual.EsActual = true;
                    RubricOnRepositoryFactory.GetVersionesRubricasRepository().Update(VersionActual);
                    RubricOnRepositoryFactory.SubmitChanges(true);

                    scope.Complete();

                    PostMessage("La version actual ha sido cambiada exitosamente.", MessageType.Success);
                }
            }
            catch (Exception ex)
            {
                PostMessage("Ha ocurrido un error.", MessageType.Error);
            }

            return RedirectToAction("ListarVersionesRubrica", new { RubricaId = RubricaId, TipoArtefacto = TipoArtefacto });
        }
예제 #9
0
 public void Wrapper(Action method)
 {
     using (var scope = new TransactionScope())
     {
         var retries = 3;
         var succeeded = false;
         while (!succeeded)
         {
             try
             {
                 method();
                 scope.Complete();
                 succeeded = true;
             }
             catch (Exception ex)
             {
                 if (retries >= 0)
                     retries--;
                 else
                 {
                     if (!Exceptions.Handle(ex))
                         throw;
                 }
             }
         }
     }
 }
예제 #10
0
        public async Task SendsMessageOnlyWhenTransactionScopeIsCompleted(bool completeTheScope, bool throwException, bool expectToReceiveMessage)
        {
            var gotMessage = false;
            _activator.Handle<string>(async str => gotMessage = true);

            try
            {
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    scope.EnlistRebus();

                    await _bus.SendLocal("hallå i stuen!1");

                    if (throwException)
                    {
                        throw new ApplicationException("omg what is this?????");
                    }

                    if (completeTheScope)
                    {
                        scope.Complete();
                    }
                }
            }
            catch(ApplicationException exception) when (exception.Message == "omg what is this?????")
            {
                Console.WriteLine("An exception occurred... quite expected though");
            }

            await Task.Delay(1000);

            Assert.That(gotMessage, Is.EqualTo(expectToReceiveMessage), "Must receive message IFF the tx scope is completed");
        }
예제 #11
0
        public void RabbitMQBinding_TransactionalDispatching_ExceptionIfTransactionalChannelUsedOutOfTheTransactionScope()
        {
            IOneWayService channel = _channelFactory.CreateChannel();

            Data data = new Data
                {
                    Id = 1,
                    Name = "Rabbit"
                };

            A.CallTo(() => _errorProcessorFake.Say(A<Data>._)).DoesNothing();
            A.CallTo(() => _processorFake.Say(A<Data>.Ignored)).Invokes(() => _ev.Set());

            using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                channel.Say(data);

                // Complete the transaction
                transaction.Complete();
            }

            bool wait = _ev.Wait(TimeSpan.FromSeconds(10));

            Assert.IsTrue(wait, "Service were not being invoked");

            // Same channel instance can't be used outsode transaction scope
            channel.Say(new Data());

            Assert.Fail("Same channel instance can't be used outsode transaction scope");
        }
예제 #12
0
        public void CreateCustomer(Customer customer)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    Log.Info($"Criando um novo usuário com o CPF {customer.CPF}");

                    if (this.ExistsCustomer(customer))
                        throw new Exception($"CPF {customer.CPF} já cadastrado");

                    var userId = Guid.NewGuid();
                    customer.Id = userId;
                    customer.Password = Infra.Utils.SecurityUtils.HashSHA1(customer.Password);

                    this.customerRepository.Save(customer);

                    if (!this.Login(customer.Email, customer.Password, true, false))
                        throw new Exception("Usuário não cadastrado, por favor tente mais tarde");

                }
                catch (Exception ex)
                {
                    Log.Error(ex.Message, ex);
                    this.LogOut();
                    throw;
                }
                finally
                {
                    Log.Info($"Finalizando a criação de um novo usuário com o CPF {customer.CPF}");
                    scope.Complete();
                }
            }
        }
예제 #13
0
        //private static readonly String sPublishQueuePath = ".\\private$\\BankTransferQueueTransacted";
        //private static void EnsureMessageQueuesExists()
        //{
        //    // Create the transacted MSMQ queue if necessary.
        //    if (!MessageQueue.Exists(sPublishQueuePath))
        //        MessageQueue.Create(sPublishQueuePath, true);
        //}

        private static void CreateDummyEntities()
        {
            using (TransactionScope lScope = new TransactionScope())
            using (BankEntityModelContainer lContainer = new BankEntityModelContainer())
            {
                if (lContainer.Accounts.Count() == 0)
                {
                    Customer lVideoStore = new Customer();
                    Account lVSAccount = new Account() { AccountNumber = 123, Balance = 0 };
                    lVideoStore.Accounts.Add(lVSAccount);

                    Customer lCustomer = new Customer();
                    Account lCustAccount = new Account() { AccountNumber = 456, Balance = 20 };
                    lCustomer.Accounts.Add(lCustAccount);


                    lContainer.Customers.AddObject(lVideoStore);
                    lContainer.Customers.AddObject(lCustomer);


                    lContainer.SaveChanges();
                    lScope.Complete();
                }
            }
        }
예제 #14
0
파일: DtcBlues.cs 프로젝트: nzdunic/ravendb
		public void CanQueryDtcForUncommittedItem()
		{
			using (GetNewServer())
			using (var store = new DocumentStore { Url = "http://localhost:8080" }.Initialize())
			{
				for (int i = 0; i < 150; i++)
				{
					string id;
					using (var tx = new TransactionScope())
					{
						System.Transactions.Transaction.Current.EnlistDurable(ManyDocumentsViaDTC.DummyEnlistmentNotification.Id,
																			  new ManyDocumentsViaDTC.DummyEnlistmentNotification(),
																			  EnlistmentOptions.None);

						using (var session = store.OpenSession())
						{
							var entity = new User();
							session.Store(entity);
							session.SaveChanges();
							id = entity.Id;
						}


						tx.Complete();
					}
					using (var session = store.OpenSession())
					{
						session.Advanced.AllowNonAuthoritiveInformation = false;
						var user = session.Load<User>(id);
						Assert.NotNull(user);
					}
				}
			}
		}
        public void RegisterCustomer(string name, CustomerType customerType)
        {            
            try
            {
                using (var transaction = new TransactionScope())
                {
                    Customer customer = new Customer();
                    customer.Name = name;
                    customer.Type = customerType;

                    customer.Agreements.Add(
                        new Agreement
                            {
                                Number = agreementManagementService.GenerateAgreementNumber(),
                                CreatedOn = DateTime.Now,
                                Customer = customer
                            });

                    repository.Save(customer);
                    repository.Commit();

                    transaction.Complete();
                }
            }
            catch (Exception ex)
            {                
                throw new RegistrationException(string.Format("Failed to register customer with name '{0}' and type {1}.", name, customerType), ex);
            }                                
        }
        public static void HandleError(MsmqPoisonMessageException error)
        {
            ProcessorQueue processorQueue = (ProcessorQueue)error.Data["processorQueue"];
            MessageQueue poisonQueue = new System.Messaging.MessageQueue(processorQueue.PoisonQueue);
            MessageQueue errorQueue = new System.Messaging.MessageQueue(processorQueue.ErrorQueue);

            using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                try
                {
                    // Send the message to the poison and error message queues.
                    poisonQueue.Send((IWorkflowMessage)error.Data["message"], MessageQueueTransactionType.Automatic);
                    errorQueue.Send((WorkflowErrorMessage)error.Data["errorMessage"], MessageQueueTransactionType.Automatic);
                    txScope.Complete();
                }
                catch (InvalidOperationException)
                {

                }
                finally
                {
                    poisonQueue.Dispose();
                    errorQueue.Dispose();
                }
            }
        }
예제 #17
0
        public void CreateAccount(String accountName, int customerID, int roleID)
        {
            Customer customer = _repository.Get<Customer>(customerID);
            if (customer == null)
            {
                throw new AccountServicesException("No customer found for the ID: " + customerID);
            }

            Role role = _repository.Get<Role>(roleID);
            if (role == null)
            {
                throw new AccountServicesException("No role found for the ID: " + roleID);
            }

            Account account = new Account();
            account.Name = accountName;
            customer.RelatedAccounts.Add(account, role);
            account.RelatedCustomers.Add(customer, role);

            using (TransactionScope scope = new TransactionScope())
            {
                _repository.Save<Account>(account);
                _repository.SaveOrUpdate<Customer>(customer);
                scope.Complete();
            }
        }
예제 #18
0
        public void MessageQueuedForReceive_EventIsRaised()
        {
            using (var sender = SetupSender())
            using (var receiver = SetupReciever())
            {
                receiver.MessageQueuedForReceive += RecordMessageEvent;

                using (var tx = new TransactionScope())
                {
                    sender.Send(
                        new Uri("file://localhost/h"),
                        new MessagePayload
                        {
                            Data = new byte[] { 1, 2, 4, 5 }
                        });

                    tx.Complete();
                }

                while (_messageEventCount == 0)
                    Thread.Sleep(100);

                receiver.MessageQueuedForReceive -= RecordMessageEvent;
            }

            Assert.NotNull(_messageEventArgs);
            Assert.Equal("h", _messageEventArgs.Message.Queue);
        }
예제 #19
0
		public void DtcCommitWillGiveOldResult()
		{
			using(var documentStore = NewDocumentStore())
			{
				using(var s = documentStore.OpenSession())
				{
					s.Store(new AccurateCount.User{ Name = "Ayende"});	
					s.SaveChanges();
				}

				using (var s = documentStore.OpenSession())
				using (var scope = new TransactionScope())
				{
					var user = s.Load<AccurateCount.User>("users/1");
					user.Name = "Rahien";
					s.SaveChanges();
					scope.Complete();
				}


				using (var s = documentStore.OpenSession())
				{
					var user = s.Load<AccurateCount.User>("users/1");
					Assert.Equal("Ayende", user.Name);
				}
			}
		}
예제 #20
0
 public void GermanString()
 {
   UInt64 id = 0;
   using (SessionNoServer session = new SessionNoServer(s_systemDir))
   {
     using (var trans = new TransactionScope())
     {
       session.BeginUpdate();
       VelocityDbSchema.Person person = new VelocityDbSchema.Person();
       person.LastName = "Med vänliga hälsningar";
       id = session.Persist(person);
       trans.Complete();
     }
   }
   using (SessionNoServer session = new SessionNoServer(s_systemDir))
   {
     using (var trans = new TransactionScope())
     {
       session.BeginUpdate();
       VelocityDbSchema.Person person = session.Open<VelocityDbSchema.Person>(id);
       person.LastName = "Mit freundlichen Grüßen";
       trans.Complete();
     }
   }
   using (SessionNoServer session = new SessionNoServer(s_systemDir))
   {
     using (var trans = new TransactionScope())
     {
       session.BeginUpdate();
       VelocityDbSchema.Person person = session.Open<VelocityDbSchema.Person>(id);
       person.LastName = "Med vänliga hälsningar";
       trans.Complete();
     }
   }
 }
        static bool AddUserToGroup(string userName, string groupName)
        {
            using (UsersGroupsEntities context = new UsersGroupsEntities())
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    if (!context.Groups.Where(g => g.Name == groupName).Any())
                    {
                        context.Groups.Add(new Group() { Name = groupName });
                        context.SaveChanges();
                    }

                    Group groupToAddIn = context.Groups.Where(g => g.Name == groupName).First();
                    if (groupToAddIn.Users.Where(u => u.Name == userName).Any())
                    {
                        scope.Dispose();
                        return false;
                    }
                    else
                    {
                        User newUser = new User() { Name = userName };
                        groupToAddIn.Users.Add(newUser);
                        context.SaveChanges();
                        scope.Complete();
                        return true;
                    }
                }
            }
        }
예제 #22
0
        private static void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

            System.Console.WriteLine("Looking for Products at {0} ", DateTime.Now.ToString());

            ProductManager productManager = new ProductManager();

            var products = productManager.GetAllProducts();

            if (products != null)
            {
                foreach (var product in products)
                {
                    using (TransactionScope scope = new TransactionScope())
                    {
                        try
                        {
                            //productManager.DeleteProduct(product.ProductId);
                            System.Console.WriteLine("Deleting Product '{0}'.", product.Name);
                            scope.Complete();
                        }
                        catch (Exception)
                        {
                            System.Console.WriteLine("There was an excpetion when attempting to delete product {0}", product.ProductId);
                        }

                    }
                }
            }
        }
        private void Handle(IReadOnlyCollection<IAggregateCommand> commands)
        {
            var aggregateRootTypes = commands.Select(x => x.AggregateRootType).ToArray();
            var actors = _aggregateActorFactory.Create(aggregateRootTypes);

            // TODO: Can agreggate actors be executed in parallel? See https://github.com/2gis/nuclear-river/issues/76
            foreach (var actor in actors)
            {
                var actorName = actor.GetType().GetFriendlyName();

                using (var transaction = new TransactionScope(
                    TransactionScopeOption.Required,
                    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.Zero }))
                {
                    using (Probe.Create($"ETL2 {actorName}"))
                    {
                        actor.ExecuteCommands(commands);
                    }

                    transaction.Complete();
                }
            }

            _telemetryPublisher.Publish<StatisticsProcessedOperationCountIdentity>(commands.Count);
        }
예제 #24
0
 /// <summary>
 /// add number
 /// </summary>
 /// <param name="_code"></param>
 /// <param name="_newVal"></param>
 public void add(string _code, string _newVal)
 {
     LTDHDataContext DB = new LTDHDataContext(@strPathDB);
     try
     {
         using (TransactionScope ts = new TransactionScope())
         {
             var r = DB.tblStatistics.Single(p => p.Code == _code);
             long oldVal = long.Parse(r.Value);
             long newVal = long.Parse(_newVal);
             if (oldVal > 0 || newVal > 0)
             {
                 oldVal += newVal;
             }
             r.Value = oldVal.ToString();
             DB.SubmitChanges();
             ts.Complete();
         }
     }
     catch (Exception e)
     {
         log.writeLog(DBHelper.strPathLogFile, e.Message
                                                 + CommonConstants.NEWLINE
                                                 + e.Source
                                                 + CommonConstants.NEWLINE
                                                 + e.StackTrace
                                                 + CommonConstants.NEWLINE
                                                 + e.HelpLink);
     }
 }
        public void GetSession_WhenInDifferentTransaction_ThenDifferentSessionAreUsed()
        {
            this.pooledPooledSessionFactoryMock.EnqueueNewSessions(2);

            ISession session1;
            ISession session2;

            using (var tx1 = new TransactionScope())
            {
                session1 = this.testee.GetSession();
                this.testee.Release(session1);

                using (var tx2 = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    session2 = this.testee.GetSession();
                    this.testee.Release(session2);

                    tx2.Complete();
                }

                tx1.Complete();
            }

            session1.Should().NotBeSameAs(session2);
        }
예제 #26
0
파일: DtcBlues.cs 프로젝트: nzdunic/ravendb
		public void CanQueryDtcForUncommittedItem()
		{
			using(var store = NewDocumentStore())
			{
				using(var tx = new TransactionScope())
				{
					System.Transactions.Transaction.Current.EnlistDurable(ManyDocumentsViaDTC.DummyEnlistmentNotification.Id,
					                                                      new ManyDocumentsViaDTC.DummyEnlistmentNotification(),
					                                                      EnlistmentOptions.None);

					using(var session = store.OpenSession())
					{
						session.Store(new User());
						session.SaveChanges();
					}


					tx.Complete();
				}
				using (var session = store.OpenSession())
				{
					session.Advanced.AllowNonAuthoritiveInformation = false;
					var user = session.Load<User>("users/1");
					Assert.NotNull(user);
				}
			}
		}
		public void MakeSureThatWeDoNotHaveTimeoutExceptionDueToStaleIndexes()
		{
			// This must run on ESENT to expose the failure
			using (var store = NewRemoteDocumentStore(databaseName: "Test", requestedStorage: "esent"))
			{
				for (var i = 1; i < 10; i++)
				{
					try
					{
						using (var scope = new TransactionScope())
						using (var session = store.OpenSession())
						{
							session.Store(new Foo {Bar = "aaa"});
							session.SaveChanges();

							scope.Complete();
						}

						using (var session = store.OpenSession())
						{
							var count = session.Query<Foo>()
								.Customize(customization => customization.WaitForNonStaleResultsAsOfNow(TimeSpan.FromSeconds(5)))
								.Count();
							Assert.Equal(i, count);
						}
					}
					catch (Exception)
					{
						Console.WriteLine(i);
						throw;
					}
				}
			}
		}
예제 #28
0
파일: BizItem.cs 프로젝트: chae87/First
        /// <summary>등록 상품 삭제</summary>
        public bool DeleteItem(BmItem pDataRq)
        {
            try
            {
                using (SqlConn = new SqlConnection(ConnectionString))
                {
                    using (TransactionScope scope = new TransactionScope())
                    {
                        try
                        {
                            SqlConn.Open();

                            var result = dac.DeleteItem(pDataRq);

                            scope.Complete();
                            return result;
                        }
                        catch (Exception ex)
                        {

                            throw ex;
                        }
                        finally
                        {
                            SqlConn.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog("Exception", ex.Message);
                return false;
            }
        }
예제 #29
0
        public void Init()
        {
            using (var transaction = new TransactionScope(TransactionScopeOption.Suppress))
            using (var session = subscriptionStorageSessionProvider.OpenStatelessSession())
            using (var tx = session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
            {
                var v2XSubscriptions = session.QueryOver<Subscription>()
                    .Where(s => s.TypeName == null)
                    .List();
                if (v2XSubscriptions.Count == 0)
                    return;

                Logger.DebugFormat("Found {0} v2X subscriptions going to upgrade", v2XSubscriptions.Count);

                foreach (var v2XSubscription in v2XSubscriptions)
                {
                    var mt = new MessageType(v2XSubscription.MessageType);
                    v2XSubscription.Version = mt.Version.ToString();
                    v2XSubscription.TypeName = mt.TypeName;

                    session.Update(v2XSubscription);
                }

                tx.Commit();
                transaction.Complete();

                Logger.InfoFormat("{0} v2X subscriptions upgraded", v2XSubscriptions.Count);
            }
        }
예제 #30
0
 private void SendSmsMessage(string mobile, VerifyType verifyType, string code)
 {
     ExceptionHelper.ThrowIfNullOrEmpty(mobile, "mobile");
     ExceptionHelper.ThrowIfNullOrEmpty(code, "code");
     using (var scope = new System.Transactions.TransactionScope())
     {
         var history = new Data.SmsHistory
         {
             content = String.Format("发送手机验证码:{0}", code),
             created = DateTime.Now,
             mobile  = mobile.Trim(),
         };
         _SmsHistoryRepository.Add(history);
         _SmsHistoryRepository.SaveChanges();
         //TODO:发送信息
         scope.Complete();
     }
 }
예제 #31
0
        public ActionResult DeleteExport2Provider(int id)
        {
            if (id < 0)
            {
                return(RedirectToAction("WaitingExport2Provider", new { @message = "Không tồn tại phiếu xuất kho này. Vui lòng kiểm tra lại" }));
            }
            var ctx   = new SmsContext();
            var infor = ctx.XUAT_KHO.Find(id);

            if (infor == null || infor.ACTIVE != "A")
            {
                ctx.Dispose();
                return(RedirectToAction("WaitingExport2Provider", new { @message = "Không tồn tại phiếu xuất kho này. Vui lòng kiểm tra lại" }));
            }
            using (var transaction = new System.Transactions.TransactionScope())
            {
                try
                {
                    infor.ACTIVE    = "I";
                    infor.UPDATE_AT = DateTime.Now;
                    infor.UPDATE_BY = Convert.ToInt32(Session["UserId"]);
                    ctx.SaveChanges();
                    var details = ctx.CHI_TIET_XUAT_KHO.Where(u => u.ACTIVE == "A" && u.MA_XUAT_KHO == id).ToList <CHI_TIET_XUAT_KHO>();
                    foreach (var detail in details)
                    {
                        detail.ACTIVE    = "I";
                        detail.UPDATE_AT = DateTime.Now;
                        detail.UPDATE_BY = Convert.ToInt32(Session["UserId"]);
                        ctx.SaveChanges();
                    }
                    transaction.Complete();
                    ctx.Dispose();
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                    Transaction.Current.Rollback();
                    ctx.Dispose();
                    return(RedirectToAction("WaitingExport2Provider", new { @message = "Hủy phiếu trả thất bại, vui lòng liên hệ admin." }));
                }
            }
            ctx.Dispose();
            return(RedirectToAction("WaitingExport2Provider", new { @messageInfor = "Xóa phiếu xuất kho thành công." }));
        }
예제 #32
0
파일: Form1.cs 프로젝트: hplewa/Coursemo
        private void showCoursesButton_Click(object sender, EventArgs e)
        {
            this.coursesLB.Items.Clear();
            using (var db = new CoursemoDataContext())
            {
                var TxOptions = new System.Transactions.TransactionOptions();
                TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable;

                using (var Tx = new System.Transactions.TransactionScope(
                           System.Transactions.TransactionScopeOption.Required, TxOptions))
                {
                    try
                    {
                        if (courses == null)
                        {
                            courses = new List <Course>();
                            if (delay_flag)
                            {
                                Delay();
                            }
                            var query = (from c in db.Courses
                                         orderby c.Department, c.CourseNum, c.CRN
                                         select c).ToList();
                            foreach (var c in query)
                            {
                                courses.Add(new Course(c.Department, c.CourseNum, c.Semester, c.Year, c.CRN, c.Time, c.Day, c.Time, c.Capacity));
                            }
                        }
                        foreach (var c in courses)
                        {
                            this.coursesLB.Items.Add(c);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        Tx.Complete();
                    }
                }
            }
        }
예제 #33
0
파일: Form1.cs 프로젝트: hplewa/Coursemo
        //Get students from DB
        //Display students in students listbox
        private void showStudentsButton_Click(object sender, EventArgs e)
        {
            this.studentsLB.Items.Clear();
            using (var db = new CoursemoDataContext())
            {
                var TxOptions = new System.Transactions.TransactionOptions();
                TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable;

                using (var Tx = new System.Transactions.TransactionScope(
                           System.Transactions.TransactionScopeOption.Required, TxOptions))
                {
                    try
                    {
                        if (students == null)
                        {
                            if (delay_flag)
                            {
                                Delay();
                            }
                            students = new List <Student>();
                            var query = (from s in db.Students
                                         orderby s.Netid
                                         select s).ToList();
                            foreach (var s in query)
                            {
                                students.Add(new Student(s.LastName, s.FirstName, s.Netid));
                            }
                        }
                        foreach (var s in students)
                        {
                            this.studentsLB.Items.Add(s);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        Tx.Complete();
                    }
                }
            }
        }
예제 #34
0
        public void MovePackageToWaiting(Package iPackage)
        {
            if (iPackage == null)
            {
                throw new Exception("Le package est null");
            }

            var originalPackage = GetPackageById(iPackage.PackageId, GranularityEnum.Full);

            if (originalPackage == null)
            {
                throw new Exception("Le package est null");
            }

            if (iPackage.Status != originalPackage.Status)
            {
                throw new Exception("La fonction n'est pas supportée pour le changement de statut");
            }

            if (iPackage.Status != PackageStatusEnum.Developpement)
            {
                throw new Exception("Le statut du package ne permet pas son retour en attente");
            }

            if (originalPackage.MainTasks.Exists(x => x.SubTasks.Exists(y => y.Progression != 0)))
            {
                throw new Exception("Le package doit avoir une progression égale à 0, pour revnir en attente");
            }

            using (var ts = new System.Transactions.TransactionScope())
            {
                //Changement sur le package
                UpdatePackageStatus(originalPackage, PackageStatusEnum.Waiting);

                //Ouverture des tâches associées
                foreach (var mainTaskItem in originalPackage.MainTasks.Enum())
                {
                    UpdateMainTaskStatus(mainTaskItem, MainTaskStatusEnum.Waiting);
                }

                ts.Complete();
            }
        }
예제 #35
0
파일: Form1.cs 프로젝트: hplewa/Coursemo
        //Delete all rows in Registrations, Transactions, and Waitlist tables
        private void resetButton_Click(object sender, EventArgs e)
        {
            using (var db = new CoursemoDataContext())
            {
                var TxOptions = new System.Transactions.TransactionOptions();
                TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable;

                using (var Tx = new System.Transactions.TransactionScope(
                           System.Transactions.TransactionScopeOption.Required, TxOptions))
                {
                    try
                    {
                        if (delay_flag)
                        {
                            Delay();
                        }
                        db.Registrations.DeleteAllOnSubmit(from r in db.Registrations select r);

                        if (delay_flag)
                        {
                            Delay();
                        }
                        db.Waitlists.DeleteAllOnSubmit(from w in db.Waitlists select w);

                        if (delay_flag)
                        {
                            Delay();
                        }
                        db.Transactions.DeleteAllOnSubmit(from t in db.Transactions select t);
                        db.SubmitChanges();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        Tx.Complete();
                    }
                }
                MessageBox.Show("Database reset.");
            }
        }
                public async Task Handle(InitiatingMessage message, IMessageHandlerContext context)
                {
                    //HINT: this scope is never completed
                    using (new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                    {
                        using (var connection = new SqlConnection(ConnectionString))
                        {
                            connection.Open();

                            var sendOptions = new SendOptions();
                            sendOptions.UseCustomSqlConnection(connection);
                            sendOptions.RouteToThisEndpoint();
                            await context.Send(new FollowUpRolledbackCommand(), sendOptions);

                            var publishOptions = new PublishOptions();
                            publishOptions.UseCustomSqlConnection(connection);
                            await context.Publish(new FollowUpRolledbackEvent(), publishOptions);
                        }
                    }

                    using (var scope = new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                    {
                        using (var connection = new SqlConnection(ConnectionString))
                        {
                            connection.Open();

                            var sendOptions = new SendOptions();
                            sendOptions.UseCustomSqlConnection(connection);
                            sendOptions.RouteToThisEndpoint();
                            await context.Send(new FollowUpCompletedCommand(), sendOptions);

                            var publishOptions = new PublishOptions();
                            publishOptions.UseCustomSqlConnection(connection);
                            await context.Publish(new FollowUpCompletedEvent(), publishOptions);

                            scenarioContext.InHandlerTransactionEscalatedToDTC = Transaction.Current.TransactionInformation.DistributedIdentifier != Guid.Empty;
                        }

                        scope.Complete();
                    }

                    throw new Exception("This should NOT prevent the InitiatingMessage from failing.");
                }
예제 #37
0
        /// <summary>
        /// 删除单个设备分类
        /// </summary>
        /// <param name="strCode">设备分类编码</param>
        /// <returns>返回处理结果</returns>
        public CommonResult <bool> DelDeviceClassByCode(string strCode)
        {
            var result = new CommonResult <bool>();

            try
            {
                var dbSession  = new DBService <DeviceClass>().DbSession;
                var dbSession1 = new DBService <Device>().DbSession;
                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                {
                    var model = dbSession.GetQueryable(t => t.DevCCode == strCode).FirstOrDefault();
                    if (model == null)
                    {
                        result.IsSuccess = false;
                        result.Message   = "该设备分类信息已经不存在";
                    }
                    else if (dbSession.GetQueryable(t => t.SupCCode == strCode).Count() > 0)
                    {
                        result.IsSuccess = false;
                        result.Message   = "不能直接删除上级分类";
                    }
                    else if (dbSession1.GetQueryable(t => t.DevCCode == strCode).Count() > 0)
                    {
                        result.IsSuccess = false;
                        result.Message   = "分类已经与设备档案关联,不能删除";
                    }

                    if (result.IsSuccess)
                    {
                        dbSession.Delete(model);
                        ts.Complete();
                        result.Data = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.Logger.Error(ex.Message);
                throw ex;
            }
            return(result);
        }
                public async Task Handle(InitiatingMessage message, IMessageHandlerContext context)
                {
                    using (var scope = new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                    {
                        using (var connection = new SqlConnection(ConnectionString))
                        {
                            connection.Open();

                            using (var rollbackedTransaction = connection.BeginTransaction())
                            {
                                var sendOptions = new SendOptions();
                                sendOptions.UseCustomSqlTransaction(rollbackedTransaction);
                                sendOptions.RouteToThisEndpoint();
                                await context.Send(new FollowUpRolledbackCommand(), sendOptions);

                                var publishOptions = new PublishOptions();
                                publishOptions.UseCustomSqlTransaction(rollbackedTransaction);
                                await context.Publish(new FollowUpRolledbackEvent(), publishOptions);

                                rollbackedTransaction.Rollback();
                            }

                            using (var transaction = connection.BeginTransaction())
                            {
                                var sendOptions = new SendOptions();
                                sendOptions.UseCustomSqlTransaction(transaction);
                                sendOptions.RouteToThisEndpoint();
                                await context.Send(new FollowUpCommittedCommand(), sendOptions);

                                var publishOptions = new PublishOptions();
                                publishOptions.UseCustomSqlTransaction(transaction);
                                await context.Publish(new FollowUpCommittedEvent(), publishOptions);

                                transaction.Commit();
                            }
                        }
                        scope.Complete();
                    }

                    throw new Exception("This should NOT prevent follow-up messages from being sent.");
                }
예제 #39
0
        public void ImplicitScope()
        {
            Console.WriteLine("TEST STARTING");
            //Console.WriteLine("1 tx: {0}", System.Transactions.Transaction.Current););
            using (var ts = new TransactionScope())
            {
                using (var c = GetConnection())
                    using (var cmd = c.CreateCommand())
                    {
                        //Console.WriteLine("2 tx: {0}", System.Transactions.Transaction.Current);
                        cmd.CommandText = "SELECT TOP 1 Val FROM Thing";
                        cmd.ExecuteScalar();
                    }

                Console.WriteLine("COMPLETING");
                ts.Complete();
                //Console.WriteLine("3 tx: {0}", System.Transactions.Transaction.Current); // throws InvalidOperationException, "we've going to complete..."
                Console.WriteLine("DISPOSING");
            }
            //Console.WriteLine("4 tx: {0}", System.Transactions.Transaction.Current);
        }
예제 #40
0
        public void Update(Entities.User obj)
        {
            // transaction scope
            using (var trans = new System.Transactions.TransactionScope())
            {
                {
                    // Users
                    obj.Email   = obj.Email.ToLower();
                    obj.Modifed = DateTime.Now;
                    repository.Update(obj);

                    // UsersPassword
                }

                {
                    // UsersRole
                    Rent.Business.Interfaces.IUserRole userRole = new UserRole();
                    var role = userRole.Select(obj.Uid);
                    role.RoleId = obj.RoleId;
                    userRole.Update(role);
                }



                {
                    // if (obj.UsersNotification != null)
                    {
                        // UsersNotification
                        Rent.Business.Interfaces.IUserNotification _iUsersNotificationRepository = new UserNotification();
                        var userNotification = _iUsersNotificationRepository.SelectByUid(obj.Uid);
                        userNotification.Phone = obj.PhoneNotification;
                        userNotification.Email = obj.EmailNotification;
                        _iUsersNotificationRepository.Update(userNotification);
                    }
                }

                // commit transaction
                trans.Complete();
            }
        }
        private void ThreadWTSA()
        {
            // Implicit Transaction
            Boolean again = true;

            while (again)
            {
                using (var scope = new System.Transactions.TransactionScope())
                {
                    if (ThreadA() == 0)
                    {
                        again = false;
                        scope.Complete();
                    }
                    else
                    {
                        Console.WriteLine("ThreadWTSA fails and reties");
                        scope.Dispose();
                    }
                }
            }
        }
예제 #42
0
        public void LeaveRulesUpdate(LeaveRulesDTOs Record)
        {
            try
            {
                using (var scope = new System.Transactions.TransactionScope())
                {
                    _unitOfWork.LeaveRuleRepository.Update(LeaveRulesMapper.LeaveRuleDtoToLeaveRules(Record));
                    int count = Record.LeaveRuleDetailsColection.Count();
                    for (int i = 0; i < count; i++)
                    {
                        LeaverulesDetailsDtos data = new LeaverulesDetailsDtos();
                        data.LeaveRuleId = Record.LeaveRuleId;
                        data.LeaveTypeId = Record.LeaveRuleDetailsColection[i].LeaveTypeId;
                        data.DetailId    = Record.LeaveRuleDetailsColection[i].DetailId;
                        if (Record.LeaveRuleDetailsColection[i].LeaveDays == null)
                        {
                            data.LeaveDays = 0;
                        }
                        else
                        {
                            data.LeaveDays = Record.LeaveRuleDetailsColection[i].LeaveDays;
                        }

                        LeaveRuleDetail insertdata = LeaveRuleDetailsMapper.LeaveRulesdetailDtoToLeaveRuleDetails(data);

                        _unitOfWork.LeaveRuleDetailRepository.Update(insertdata);
                    }
                    scope.Complete();
                }
            }
            catch (TransactionAbortedException ex)
            {
                throw new Exception(ex.Message);
            }
            catch (ApplicationException ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #43
0
        static void Main()
        {
            Console.WriteLine("Sample begins.");
            using (System.Transactions.TransactionScope txScope = new System.Transactions.TransactionScope())
            {
                Console.WriteLine("TransactionScope constructed.");

                //The local ID of the current transaction
                Console.WriteLine("Tx local ID: " + Transaction.Current.TransactionInformation.LocalIdentifier.ToString());

                Console.WriteLine("\nLaunching WF using WorkflowInvoker.");

                //Launch my workflow. WorkflowInvoker is the only way to implicitly flow a current transaction into a new workflow
                new WorkflowInvoker(BuildWF()).BeginInvoke(null, null);

                txScope.Complete();
                txScope.Dispose();
            };

            Console.WriteLine("\nSample complete. Press ENTER to exit");
            Console.ReadLine();
        }
예제 #44
0
        public static async Task Change(this Subscription_Product subscriptionProduct, ApplicationDbContext db)
        {
            var oldSubscriptionProduct = await db.Subscriptions_Products.FirstOrDefaultAsync(
                sp => sp.ProductID.Equals(subscriptionProduct.OldProductID) &&
                sp.SubscriptionID.Equals(subscriptionProduct.OldSubscriptionID));

            var newSubscriptionProduct = await db.Subscriptions_Products.FirstOrDefaultAsync(
                sp => sp.ProductID.Equals(subscriptionProduct.ProductID) &&
                sp.SubscriptionID.Equals(subscriptionProduct.SubscriptionID));

            if (oldSubscriptionProduct != null && newSubscriptionProduct == null)
            {
                newSubscriptionProduct = new Subscription_Product
                {
                    SubscriptionID = subscriptionProduct.SubscriptionID,
                    ProductID      = subscriptionProduct.ProductID
                };

                using (var transaction = new TransactionScope(
                           TransactionScopeAsyncFlowOption.Enabled))
                {
                    //try
                    //{

                    using (var context = new EntityContext())
                    {
                        context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
                        db.Subscriptions_Products.Remove(oldSubscriptionProduct);
                        db.Subscriptions_Products.Add(newSubscriptionProduct);
                        await db.SaveChangesAsync();
                    }


                    transaction.Complete();
                    //}
                    //catch { transaction.Dispose(); }
                }
            }
        }
예제 #45
0
        public ActionResult Eliminar(int txtIdGrupo)
        {
            using (var bd = new BDDemoLoginEntities())
            {
                using (var transaccion = new System.Transactions.TransactionScope())
                {
                    Grupo oGrupo = bd.Grupo.Where(p => p.IDGRUPO == txtIdGrupo).First();
                    oGrupo.HABILITADO = 0;

                    // borra permisos existentes
                    int cantPermisos = bd.GrupoPermiso.Where(p => p.IDGRUPO == txtIdGrupo).Count();

                    for (int i = 0; i < cantPermisos; i++)
                    {
                        GrupoPermiso oGrupoPermiso = bd.GrupoPermiso.Where(p => p.IDGRUPO == txtIdGrupo).First();
                        oGrupoPermiso.HABILITADO = 0;
                    }
                    bd.SaveChanges();
                    transaccion.Complete();
                }
            }
            return(RedirectToAction("Index"));
        }
예제 #46
0
        public void MovePackageToProduction(Package iPackage)
        {
            if (iPackage == null)
            {
                throw new Exception("Le package est null");
            }

            var thePackage = GetPackageById(iPackage.PackageId, GranularityEnum.Full);

            using (var ts = new System.Transactions.TransactionScope())
            {
                //UpdatePackageStatus
                UpdatePackageStatus(thePackage, PackageStatusEnum.Production);

                //Passage en production des tâches
                foreach (var mainTaskItem in thePackage.MainTasks)
                {
                    MoveMainTaskToProduction(mainTaskItem.MainTaskId);
                }

                //Nettoyage des priorités de projets tâches
                FillGapTaskPriority();

                //Création de la trace de déploiement
                var newDeployement = new EquinoxeExtend.Shared.Object.Release.Deployement();
                newDeployement.DeployementDate        = DateTime.Now;
                newDeployement.DeployementId          = -1;
                newDeployement.EnvironmentDestination = EnvironmentEnum.Production;
                newDeployement.PackageId = thePackage.PackageId;
                AddDeployement(newDeployement);

                //Nettoyage priorités des packages
                FillGapPackagePriority();

                ts.Complete();
            }
        }
예제 #47
0
        /// <summary>
        /// 删除单个设备档案
        /// </summary>
        /// <param name="strCode">设备编码</param>
        /// <returns>返回处理结果</returns>
        public CommonResult <bool> DelDeviceByCode(string strCode)
        {
            var result = new CommonResult <bool>();

            try
            {
                var dbSession  = new DBService <Device>().DbSession;
                var dbSession1 = new DBService <DeviceWorkingCondition>(dbSession.Context).DbSession;
                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
                {
                    var model = dbSession.GetQueryable(t => t.DevCode == strCode).FirstOrDefault();
                    if (model == null)
                    {
                        result.Message = "该设备信息已经不存在";
                    }

                    if (result.IsSuccess)
                    {
                        dbSession.Delete(model);
                        var dwcModel = dbSession1.GetQueryable(t => t.DevCode == model.DevCode).FirstOrDefault();
                        if (dwcModel != null)
                        {
                            dbSession1.Delete(dwcModel);
                        }
                        ts.Complete();
                        result.Data = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.Logger.Error(ex.Message);
                throw ex;
            }
            return(result);
        }
예제 #48
0
        public bool Disassociate(string provider, string providerUserId)
        {
            bool   success      = false;
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);

            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == CurrentUser.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (var scope = new System.Transactions.TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                    IsolationLevel = IsolationLevel.Serializable
                }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(CurrentUser.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(CurrentUser.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        success = true;
                    }
                }
            }
            return(success);
        }
예제 #49
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        var proxyHello  = new TransactionSvc.Hello.HelloClient();
        var proxyHi     = new TransactionSvc.Hi.HiClient();
        var proxyResult = new TransactionSvc.Result.ResultClient();

        System.Transactions.TransactionOptions to = new System.Transactions.TransactionOptions();
        // 设置事务的超时时间
        to.Timeout = new TimeSpan(0, 0, 30);
        // 设置事务的隔离级别
        to.IsolationLevel = System.Transactions.IsolationLevel.Serializable;

        using (var ts = new System.Transactions.TransactionScope())
        {
            try
            {
                proxyHello.WriteHello("webabcd");
                proxyHello.Close();

                proxyHi.WriteHi("webabcd");
                proxyHi.Close();

                ts.Complete();

                lblErr.Text = "OK";
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.ToString();
            }
        }

        GridView1.DataSource = proxyResult.GetResult();
        GridView1.DataBind();
        proxyHello.Close();
    }
예제 #50
0
 public void Add(IEnumerable <TEntity> entities, out OperationResult rState)
 {
     using (var transaction = new System.Transactions.TransactionScope())
     {
         try
         {
             foreach (var entity in entities)
             {
                 this.InsertOnSaveChanges(entity, out rState);
             }
             this.SaveChanges(out rState);
             if (!rState.Succeed)
             {
                 throw rState.Exception;
             }
             transaction.Complete();
             rState = new OperationResult(null);
         }
         catch (Exception ex)
         {
             rState = new OperationResult(ex);
         }
     }
 }
예제 #51
0
        public void Insert(teresa.information.LogTrackInfo e)
        {
            try
            {
                //不使用Transaction , 以正確的記錄發生那些Track事件
                using (System.Transactions.TransactionScope Ts = new System.Transactions.TransactionScope(TransactionScopeOption.Suppress))
                {
                    //設定連結字串
                    Database db = base.GetDatabase();

                    StringBuilder sbCommand = new StringBuilder();

                    sbCommand.Append("INSERT INTO Track_Log ");
                    sbCommand.Append("  (ModifyFromIP, ModifyUser, ModifyMode, ModifyTable, ModifyKeyValue ,ModifyBefore , ModifyAfter) ");
                    sbCommand.Append("VALUES ");
                    sbCommand.Append("  (@ModifyFromIP, @ModifyUser, @ModifyMode,  @ModifyTable, @ModifyKeyValue,  @ModifyBefore, @ModifyAfter) ");

                    DbCommand dbCommand = db.GetSqlStringCommand(sbCommand.ToString());

                    db.AddInParameter(dbCommand, "@ModifyFromIP", DbType.String, e.ModifyFromIP);
                    db.AddInParameter(dbCommand, "@ModifyUser", DbType.String, e.ModifyUser);
                    db.AddInParameter(dbCommand, "@ModifyMode", DbType.String, e.ModifyMode);
                    db.AddInParameter(dbCommand, "@ModifyTable", DbType.String, e.ModifyTable);
                    db.AddInParameter(dbCommand, "@ModifyKeyValue", DbType.String, e.ModifyKeyValue);
                    db.AddInParameter(dbCommand, "@ModifyKeyValue", DbType.String, e.ModifyBefore);
                    db.AddInParameter(dbCommand, "@ModifyKeyValue", DbType.String, e.ModifyAfter);

                    db.ExecuteNonQuery(dbCommand);
                    Ts.Complete();
                }
            }
            catch
            {
                throw;
            }
        }
예제 #52
0
        public ActionResult Agregar(GrupoCLS oGrupoCLS, FormCollection form)
        {
            string[] permisosSeleccionados = null;
            if (form["permisos"] != null)
            {
                permisosSeleccionados = form["permisos"].Split(',');
            }

            int numPermisosSeleccionados = 0;

            if (permisosSeleccionados != null)
            {
                numPermisosSeleccionados = permisosSeleccionados.Count();
            }

            //try
            //{
            int numRegistrosEncontrados = 0;

            using (var bd = new BDDemoLoginEntities())
            {
                numRegistrosEncontrados = bd.Grupo.Where(p => p.NOMBREGRUPO == oGrupoCLS.nombreGrupo).Count();
            }
            if (!ModelState.IsValid || numRegistrosEncontrados >= 1 || numPermisosSeleccionados < 1)
            {
                if (numRegistrosEncontrados >= 1)
                {
                    oGrupoCLS.mensajeErrorNombre = "El nombre de grupo ya existe ";
                }
                if (numPermisosSeleccionados < 1)
                {
                    oGrupoCLS.mensajeErrorPermiso = "Debe Seleccionar por lo menos un permiso";
                }
                listarPermiso();
                return(View(oGrupoCLS));
            }
            else
            {
                using (var bd = new BDDemoLoginEntities())
                {
                    using (var transaccion = new System.Transactions.TransactionScope()) {
                        Grupo oGrupo = new Grupo();
                        oGrupo.NOMBREGRUPO = oGrupoCLS.nombreGrupo;
                        oGrupo.HABILITADO  = 1;
                        bd.Grupo.Add(oGrupo);

                        for (int i = 0; i < numPermisosSeleccionados; i++)
                        {
                            GrupoPermiso oGrupoPermiso = new GrupoPermiso();
                            oGrupoPermiso.IDGRUPO    = oGrupoCLS.idGrupo;
                            oGrupoPermiso.IDPERMISO  = int.Parse(permisosSeleccionados[i]);
                            oGrupoPermiso.HABILITADO = 1;
                            bd.GrupoPermiso.Add(oGrupoPermiso);
                        }
                        bd.SaveChanges();
                        transaccion.Complete();
                    }
                }
            }
            //}
            //catch(Exception ex)
            //{

            //}
            return(RedirectToAction("Index"));
        }
예제 #53
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        int RoleID = 0;

        int.TryParse(hfR.Value, out RoleID);

        if (RoleID == 0)
        {
            string SC = "<script>alert('資料取得失敗');location.href = '/System/PowerM/RolePowerSetting.aspx';</script><style>body{display:none;}</style>";
            Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "alert", SC, false);
            return;
        }

        string script = "<script>alert('儲存失敗');</script>";

        if (hfV != null)
        {
            string jsonString = hfV.Value;

            List <RolePowerSettingPowerVM> list = new List <RolePowerSettingPowerVM>();
            list = JsonConvert.DeserializeObject <List <RolePowerSettingPowerVM> >(jsonString);


            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("RoleID");
            dt.Columns.Add("ModuleID");
            dt.Columns.Add("PowerString");


            foreach (var item in list.Where(item => item.PowerStringOut > 1))
            {
                dt.Rows.Add(0, RoleID, item.mId, item.PowerStringOut);
            }

            System.Transactions.TransactionOptions option = new System.Transactions.TransactionOptions();
            option.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            option.Timeout        = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(TransactionScopeOption.Required, option))
            {
                using (SqlConnection sc = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnUser"].ToString()))
                {
                    sc.Open();
                    using (SqlCommand cmd = new SqlCommand("dbo.usp_PowerM_xDeleteRoleModuleByRoleID", sc))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@RoleID", RoleID);
                        cmd.ExecuteNonQuery();

                        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sc))
                        {
                            bulkCopy.BulkCopyTimeout      = 60;
                            bulkCopy.DestinationTableName = "dbo.R_RoleModule";
                            bulkCopy.WriteToServer(dt);
                        }

                        ts.Complete();
                    }
                }
            }

            script = "<script>alert('儲存成功');location.href='/System/PowerM/RolePowerSetting.aspx';</script><style>body{display:none;}</style>";
            Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "alert", script, false);
        }


        Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "alert", script, false);
    }
예제 #54
0
        public object removeDevice(Dictionary <string, object> dicParas)
        {
            try
            {
                string errMsg      = string.Empty;
                string mobileToken = dicParas.ContainsKey("mobileToken") ? dicParas["mobileToken"].ToString() : string.Empty;
                string deviceToken = dicParas.ContainsKey("deviceToken") ? dicParas["deviceToken"].ToString() : string.Empty;

                Base_MerchInfo merch = MerchBusiness.GetMerchModel(mobileToken);
                if (merch.IsNull())
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "用户令牌无效"));
                }

                Base_DeviceInfo device = DeviceBusiness.GetDeviceModel(deviceToken);
                if (device.IsNull())
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "设备令牌无效"));
                }

                //设备所属商户不是当前商户
                if (device.MerchID != merch.ID)
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "该设备已被其他商户绑定,没有权限操作该设备"));
                }

                //开始解除绑定
                device.MerchID = 0;
                device.Status  = (int)DeviceStatusEnum.未激活;

                DeviceTypeEnum currDeviceType = (DeviceTypeEnum)device.DeviceType;
                bool           ret            = false;

                switch (currDeviceType)
                {
                case DeviceTypeEnum.Router:
                {
                    string sql = string.Format("exec RemoveMerchRouter {0}", device.ID);
                    XCCloudRS232BLL.ExecuteSql(sql);

                    //ret = DeviceBusiness.UpdateDevice(device);
                }
                break;

                case DeviceTypeEnum.SlotMachines:
                case DeviceTypeEnum.DepositMachine:
                {
                    //获取外设绑定关系实体
                    Data_MerchDevice md = MerchDeviceBusiness.GetMerchDeviceModel(device.ID);

                    using (var transactionScope = new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew))
                    {
                        DeviceBusiness.UpdateDevice(device);
                        ret = MerchDeviceBusiness.DeleteMerchDevice(md);

                        transactionScope.Complete();
                    }
                }
                break;

                case DeviceTypeEnum.Clerk:
                case DeviceTypeEnum.Terminal:
                {
                    //获取终端绑定关系实体
                    Data_MerchSegment ms = MerchSegmentBusiness.GetMerchSegmentModel(device.ID);

                    using (var transactionScope = new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew))
                    {
                        DeviceBusiness.UpdateDevice(device);
                        ret = MerchSegmentBusiness.DeleteMerchSegment(ms);

                        transactionScope.Complete();
                    }
                }
                break;
                }

                if (ret)
                {
                    DeviceStatusBusiness.SetDeviceState(device.Token, DeviceStatusEnum.未激活.ToDescription());
                }

                return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.T, ""));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #55
0
파일: Form1.cs 프로젝트: hplewa/Coursemo
        private void swapButton_Click(object sender, EventArgs e)
        {
            string netidA = this.netidATextBox.Text;

            if (netidA == null)
            {
                MessageBox.Show("Enter student A's netid.");
                return;
            }
            int crnA = Convert.ToInt32(this.crnATextBox.Text);

            if (this.crnATextBox.Text == null)
            {
                MessageBox.Show("Enter student A's CRN.");
                return;
            }
            string netidB = this.netidBTextBox.Text;

            if (netidB == null)
            {
                MessageBox.Show("Enter student B's netid.");
                return;
            }
            int crnB = Convert.ToInt32(this.crnBTextBox.Text);

            if (this.crnBTextBox.Text == null)
            {
                MessageBox.Show("Enter student B's CRN.");
                return;
            }
            string msg = null;

            using (var db = new CoursemoDataContext())
            {
                var TxOptions = new System.Transactions.TransactionOptions();
                TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable;

                using (var Tx = new System.Transactions.TransactionScope(
                           System.Transactions.TransactionScopeOption.Required, TxOptions))
                {
                    try
                    {
                        //Check if student A exists
                        if (delay_flag)
                        {
                            Delay();
                        }
                        var aExists = from s in db.Students
                                      where s.Netid == netidA
                                      select s.Netid;
                        if (!aExists.Any())
                        {
                            msg = netidA + " does not exist.";
                            throw new System.InvalidOperationException(msg);
                        }
                        //Check if student A is enrolled in crnA
                        var aEnrolled = from r in db.Registrations
                                        where r.Netid == netidA
                                        where r.CRN == crnA
                                        select r;
                        if (!aEnrolled.Any())
                        {
                            msg = netidA + " is not enrolled in " + crnA.ToString() + ".";
                            throw new System.InvalidOperationException(msg);
                        }

                        if (delay_flag)
                        {
                            Delay();
                        }
                        //Check if student B exists
                        var bExists = from s in db.Students
                                      where s.Netid == netidB
                                      select s.Netid;
                        if (!bExists.Any())
                        {
                            msg = netidB + " does not exist.";
                            throw new System.InvalidOperationException(msg);
                        }

                        if (delay_flag)
                        {
                            Delay();
                        }
                        //Check if student B is enrolled in crnB
                        var bEnrolled = from r in db.Registrations
                                        where r.Netid == netidB
                                        where r.CRN == crnB
                                        select r;
                        if (!bEnrolled.Any())
                        {
                            msg = netidB + " is not enrolled in " + crnB.ToString() + ".";
                            throw new System.InvalidOperationException(msg);
                        }

                        if (delay_flag)
                        {
                            Delay();
                        }
                        //Clear out student a's waitlist entry for b's class
                        var aWaiting = from w in db.Waitlists
                                       where w.Netid == netidA
                                       where w.CRN == crnB
                                       select w;
                        db.Waitlists.DeleteAllOnSubmit(aWaiting);

                        if (delay_flag)
                        {
                            Delay();
                        }
                        //Clear out student b's waitlist entry for a's class
                        var bWaiting = from w in db.Waitlists
                                       where w.Netid == netidB
                                       where w.CRN == crnA
                                       select w;
                        db.Waitlists.DeleteAllOnSubmit(bWaiting);

                        //Swap registrations
                        if (delay_flag)
                        {
                            Delay();
                        }
                        aEnrolled.First().CRN = crnB;

                        if (delay_flag)
                        {
                            Delay();
                        }
                        bEnrolled.First().CRN = crnA;
                        //MessageBox.Show(netidA + " swapped course " + crnA.ToString() + " for " + crnB.ToString() + " with " + netidB);
                        msg = netidA + " swapped course " + crnA.ToString() + " for " + crnB.ToString() + " with " + netidB;
                        db.SubmitChanges();
                        Tx.Complete();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            MessageBox.Show(msg);
        }
예제 #56
0
        public void IncluirPersonagem(Personagem personagem)
        {
            string connectionString =
                ConfigurationManager.ConnectionStrings["StreetFighter"]
                .ConnectionString;

            Personagem result = new Personagem();

            if (RegraDeNegocio(personagem))
            {
                using (var transaction = new System.Transactions.TransactionScope(TransactionScopeOption.Required))
                    using (var connection = new SqlConnection(connectionString))
                    {
                        try
                        {
                            connection.Open();
                            string sql        = "";
                            var    parameters = new List <SqlParameter>();

                            if (personagem.Id > 0)
                            {
                                sql = $"UPDATE Personagem SET Nome=@param_nome, DataNascimento=@param_data, Altura=@param_altura, Peso=@param_peso, Origen=@param_origem, GolpesEspeciais=@param_golpes, PesonagemOculto=@param_personagemOculto, Imagem=@param_imagem  WHERE Id = @param_id";
                                parameters.Add(new SqlParameter("param_id", personagem.Id));
                                parameters.Add(new SqlParameter("param_nome", personagem.Nome));
                                parameters.Add(new SqlParameter("param_data", personagem.DataNascimento));
                                parameters.Add(new SqlParameter("param_altura", personagem.Altura));
                                parameters.Add(new SqlParameter("param_peso", personagem.Peso));
                                parameters.Add(new SqlParameter("param_origem", personagem.Origem));
                                parameters.Add(new SqlParameter("param_golpes", personagem.GolpesEspeciais));
                                parameters.Add(new SqlParameter("param_personagemOculto", personagem.PersonagemOculto));
                                parameters.Add(new SqlParameter("param_imagem", personagem.Imagem));
                                // Aplicar o resto dos parâmetros
                            }
                            else
                            {
                                sql = $"INSERT INTO Personagem(Nome, DataNascimento, Altura, Peso, Origen, GolpesEspeciais, PersonagemOculto, Imagem) VALUES(@param_nome, @param_data, @param_altura, @param_peso, @param_origem, @param_golpes, @param_personagemOculto, @param_imagem); ";

                                parameters.Add(new SqlParameter("param_nome", personagem.Nome));
                                parameters.Add(new SqlParameter("param_data", personagem.DataNascimento));
                                parameters.Add(new SqlParameter("param_altura", personagem.Altura));
                                parameters.Add(new SqlParameter("param_peso", personagem.Peso));
                                parameters.Add(new SqlParameter("param_origem", personagem.Origem));
                                parameters.Add(new SqlParameter("param_golpes", personagem.GolpesEspeciais));
                                parameters.Add(new SqlParameter("param_personagemOculto", personagem.PersonagemOculto));
                                parameters.Add(new SqlParameter("param_imagem", personagem.Imagem));
                            }
                            var command = new SqlCommand(sql, connection);
                            foreach (SqlParameter param in parameters)
                            {
                                command.Parameters.Add(param);
                            }
                            command.ExecuteNonQuery();
                            transaction.Complete();
                        }
                        catch
                        {
                            Console.Write("Deu ruim. Erro ao cadastrar!"); // Melhorar isso
                        }
                        finally
                        {
                            connection.Close();
                        }
                    }
            }
        }
예제 #57
0
    protected void btnUploadFile_Click(object sender, EventArgs e)
    {
        string path = Server.MapPath("~/TemporaryFile/");

        try
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path += uploadFile.FileName;
            uploadFile.SaveAs(path);
            DataTable dtLOI = loiControllerr.initiateLOITable();
            //dtLOI.Columns.Add("ErrorRemarks");
            int successuploadedcount = 0;
            if (readLOIExcelFile(dtLOI, path))
            {
                if (dtLOI.Rows.Count > 0)
                {
                    using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope())
                    {
                        try
                        {
                            int errorcount    = 0;
                            int Subcon_Id     = loiControllerr.Validate_SubconName(dtLOI.Rows[0]["Subcone_Name"].ToString());
                            int scope_type_id = loiControllerr.Validate_sowdetail(dtLOI.Rows[0]["ScopeOfWork"].ToString());
                            int RequestId     = int.Parse(Request.QueryString["RequestId"]);
                            if (loiControllerr.LOI_UploadRejected_by_FM(RequestId))
                            {
                                foreach (DataRow dr in dtLOI.Rows)
                                {
                                    int       RegionId = 0;
                                    int       ARA_ID   = 0;
                                    DataTable dtRegion = loiControllerr.Validate_Region(dr["Region"].ToString());
                                    if (dtRegion.Rows.Count > 0)
                                    {
                                        RegionId = Convert.ToInt32(dtRegion.Rows[0]["RGN_ID"]);
                                        ARA_ID   = Convert.ToInt32(dtRegion.Rows[0]["ARA_ID"]);
                                    }
                                    string ErrorRemarks = ValidateLOIData(dr, RequestId, Subcon_Id, RegionId, scope_type_id);
                                    if (string.IsNullOrEmpty(ErrorRemarks))
                                    {
                                        if (!loiControllerr.LOI_Detail_Upload_by_FM(dr, RequestId, RegionId, ARA_ID))
                                        {
                                            errorcount   += 1;
                                            dr["Remarks"] = "Failed when upload data to db";
                                        }
                                    }
                                    else
                                    {
                                        errorcount   += 1;
                                        dr["Remarks"] = ErrorRemarks;
                                    }
                                }
                            }
                            else
                            {
                                errorcount += 1;
                            }

                            lblErrorUpload.Visible = false;
                            Session["dtLOIError"]  = null;
                            if (errorcount == 0)
                            {
                                if (loiControllerr.update_loi_price_fromTemp(RequestId))
                                {
                                    try
                                    {
                                        SendEmail(RequestId);
                                    }
                                    catch (Exception ex)
                                    {
                                    }
                                    finally
                                    {
                                        scope.Complete();
                                        ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('File completely uploaded');location.href = '../dashboard/frmDashboardFM.aspx';", true);
                                    }
                                }
                                else
                                {
                                    scope.Dispose();
                                    Session["dtLOIError"]  = dtLOI;
                                    lblErrorUpload.Text    = "Total Failed: " + errorcount.ToString();
                                    lblErrorUpload.Visible = true;
                                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('upload data failed');", true);
                                }
                            }
                            else
                            {
                                scope.Dispose();
                                Session["dtLOIError"]  = dtLOI;
                                lblErrorUpload.Text    = "Total Failed: " + errorcount.ToString();
                                lblErrorUpload.Visible = true;
                                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('upload data failed');", true);
                            }
                        }
                        catch
                        {
                            scope.Dispose();
                            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('upload data failed');", true);
                        }
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('There is no data to be uploaded');", true);
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Failed to read excel file');", true);
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Failed to upload data');", true);
        }
        finally
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }
    }
예제 #58
0
        public object bindDevice(Dictionary <string, object> dicParas)
        {
            try
            {
                string errMsg      = string.Empty;
                string mobileToken = dicParas.ContainsKey("mobileToken") ? dicParas["mobileToken"].ToString() : string.Empty;
                string deviceToken = dicParas.ContainsKey("deviceToken") ? dicParas["deviceToken"].ToString() : string.Empty;
                string deviceName  = dicParas.ContainsKey("deviceName") ? dicParas["deviceName"].ToString() : string.Empty;
                string level       = dicParas.ContainsKey("level") ? dicParas["level"].ToString() : string.Empty;
                string routerToken = dicParas.ContainsKey("routerToken") ? dicParas["routerToken"].ToString() : string.Empty;
                string groupId     = dicParas.ContainsKey("groupId") ? dicParas["groupId"].ToString() : string.Empty;

                Base_MerchInfo merch = MerchBusiness.GetMerchModel(mobileToken);
                if (merch.IsNull())
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "用户令牌无效"));
                }

                if (merch.State == 0)
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "当前用户已被禁用"));
                }

                Base_DeviceInfo device = DeviceBusiness.GetDeviceModel(deviceToken);
                if (device.IsNull())
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "设备令牌无效"));
                }

                //设备已被绑定
                if (!device.MerchID.IsNull() && device.MerchID != 0 && device.MerchID != merch.ID)
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "该设备已被其他商户绑定"));
                }

                //设备未绑定,开始绑定
                device.MerchID    = merch.ID;
                device.DeviceName = deviceName;
                device.Status     = (int)DeviceStatusEnum.启用;

                if (string.IsNullOrWhiteSpace(level))
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "参数错误"));
                }

                DeviceTypeEnum currDeviceType = (DeviceTypeEnum)device.DeviceType;

                switch (level)
                {
                case "1":
                {
                    if (currDeviceType == DeviceTypeEnum.Router)
                    {
                        DeviceBusiness.UpdateDevice(device);
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.T, ""));
                    }
                    else if (currDeviceType == DeviceTypeEnum.SlotMachines || currDeviceType == DeviceTypeEnum.DepositMachine)
                    {
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "请选定控制器后绑定该设备"));
                    }
                    else
                    {
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "请在分组中绑定该设备"));
                    }
                }

                case "2":
                {
                    if (currDeviceType == DeviceTypeEnum.Router)
                    {
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "请在返回上级绑定"));
                    }
                    else if (currDeviceType == DeviceTypeEnum.SlotMachines || currDeviceType == DeviceTypeEnum.DepositMachine)
                    {
                        if (string.IsNullOrWhiteSpace(routerToken))
                        {
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取控制器参数错误"));
                        }
                        //获取控制器实体
                        Base_DeviceInfo router = DeviceBusiness.GetDeviceModel(routerToken);
                        if (router.IsNull())
                        {
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取控制器参数错误"));
                        }

                        //获取当前控制器中的外设列表
                        var list = MerchDeviceBusiness.GetListByParentId(router.ID).OrderBy(m => m.HeadAddress).ToList();

                        if (list.Count >= 11)
                        {
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "超出最大绑定数量"));
                        }

                        Data_MerchDevice md = list.FirstOrDefault(m => m.DeviceID == device.ID);
                        if (md.IsNull())
                        {
                            md          = new Data_MerchDevice();
                            md.ParentID = router.ID;
                            md.DeviceID = device.ID;

                            int index = 0;
                            foreach (var item in list)
                            {
                                string currAddress = string.Format("A{0}", index);
                                //int currIndex = int.Parse(item.HeadAddress, System.Globalization.NumberStyles.AllowHexSpecifier);
                                if (currAddress != item.HeadAddress)
                                {
                                    break;
                                }
                                index++;
                                continue;
                            }
                            //md.HeadAddress = Convert.ToString(index, 16).PadLeft(2, '0').ToUpper();
                            md.HeadAddress = string.Format("A{0}", index);
                        }

                        using (var transactionScope = new System.Transactions.TransactionScope(
                                   TransactionScopeOption.RequiresNew))
                        {
                            DeviceBusiness.UpdateDevice(device);
                            MerchDeviceBusiness.AddMerchDevice(md);

                            transactionScope.Complete();
                        }

                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.T, ""));
                    }
                    else
                    {
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "请在分组中绑定该设备"));
                    }
                }

                case "3":
                {
                    if (currDeviceType != DeviceTypeEnum.Clerk && currDeviceType != DeviceTypeEnum.Terminal)
                    {
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "请在分组中绑定该设备"));
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(groupId))
                        {
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取分组参数错误"));
                        }

                        //获取分组实体
                        Data_GameInfo group = GameBusiness.GetGameInfoModel(Convert.ToInt32(groupId));
                        if (group.IsNull())
                        {
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取分组参数错误"));
                        }

                        //根据分组获取当前分组的控制器
                        Base_DeviceInfo router = DeviceBusiness.GetDeviceModelById((int)group.DeviceID);
                        if (router.IsNull())
                        {
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取控制器参数错误"));
                        }

                        //判断当前分组是否属于当前商户
                        if (router.MerchID != merch.ID)
                        {
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "分组信息与当前商户不匹配"));
                        }

                        //获取当前分组中的终端列表
                        var list = MerchSegmentBusiness.GetListByGroupId(group.GroupID).OrderBy(m => m.HeadAddress).ToList();

                        if (list.Count >= 99)
                        {
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "超出最大绑定数量"));
                        }

                        Data_MerchSegment ms = list.FirstOrDefault(m => m.ParentID == group.DeviceID && m.DeviceID == device.ID);
                        if (ms.IsNull())
                        {
                            ms          = new Data_MerchSegment();
                            ms.ParentID = group.DeviceID;
                            ms.GroupID  = group.GroupID;
                            ms.DeviceID = device.ID;

                            int index = 1;
                            foreach (var item in list)
                            {
                                int currIndex = int.Parse(item.HeadAddress, System.Globalization.NumberStyles.AllowHexSpecifier);
                                if (currIndex != index)
                                {
                                    break;
                                }
                                index++;
                                continue;
                            }
                            ms.HeadAddress = Convert.ToString(index, 16).PadLeft(2, '0').ToUpper();
                        }

                        using (var transactionScope = new System.Transactions.TransactionScope(
                                   TransactionScopeOption.RequiresNew))
                        {
                            DeviceBusiness.UpdateDevice(device);
                            MerchSegmentBusiness.AddMerchSegment(ms);

                            transactionScope.Complete();
                        }

                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.T, ""));
                    }
                }
                }

                DeviceStatusBusiness.SetDeviceState(device.Token, DeviceStatusEnum.离线.ToDescription());

                return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.T, ""));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
 public override void Complete()
 {
     _inner.Complete();
 }
예제 #60
-1
파일: FlowRule.cs 프로젝트: zjchenxk/SYLS
        /// <summary>
        /// 删除指定流程步骤数据
        /// </summary>
        /// <param name="nId">步骤编码</param>
        /// <param name="nOpStaffId">操作员工编码</param>
        /// <param name="strOpStaffName">操作员工姓名</param>
        /// <param name="strErrText">出错信息</param>
        /// <returns></returns>
        public bool DeleteApproveFlowStep(long nId, long nOpStaffId, string strOpStaffName, out string strErrText)
        {
            try
            {
                using (TransactionScope transScope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(2, 0, 0)))
                {
                    using (FlowDAO dao = new FlowDAO())
                    {
                        //删除步骤数据
                        if (!dao.DeleteApproveFlowStep(nId, nOpStaffId, strOpStaffName, out strErrText))
                        {
                            return false;
                        }

                        //删除原条件数据
                        if (!dao.DeleteApproveFlowStepConditions(nId, nOpStaffId, strOpStaffName, out strErrText))
                        {
                            return false;
                        }
                    }
                    transScope.Complete();
                }
                return true;
            }
            catch (Exception e)
            {
                strErrText = e.Message;
                return false;
            }
        }