public StandardTransaction(TransactionDelegate onTransactionCommitted, TransactionDelegate onTransactionRolledback,
			TransactionMode transactionMode, IsolationMode isolationMode, bool distributedTransaction) : 
			this(transactionMode, isolationMode, distributedTransaction)
		{
			this.onTransactionCommitted = onTransactionCommitted;
			this.onTransactionRolledback = onTransactionRolledback;
		}
        /// <summary>
        ///     Processes the Authorize and AuthorizeAndCapture transactions
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice" /> to be paid</param>
        /// <param name="payment">The <see cref="IPayment" /> record</param>
        /// <param name="transactionMode">Authorize or AuthorizeAndCapture</param>
        /// <param name="amount">The money amount to be processed</param>
        /// <returns>The <see cref="IPaymentResult" /></returns>
        public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, TransactionMode transactionMode, decimal amount)
        {
            if (!IsValidCurrencyCode(invoice.CurrencyCode()))
            return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Invalid currency. Invoice Currency: '{0}'", invoice.CurrencyCode()))), invoice, false);

              if (transactionMode == TransactionMode.Authorize) {

            //var paymentId = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.QuickpayPaymentId);
            var currency = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.PaymentCurrency);
            var amountAuthorizedMinorString = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.PaymentAmount);
            var amountAuthorized = decimal.Parse(amountAuthorizedMinorString) / (IsZeroDecimalCurrency(currency) ? 100 : 1);

            if (invoice.CurrencyCode() != currency) {
              return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Currency mismatch. Invoice Currency: {0}, Payment Currency: {1}", invoice.CurrencyCode(), currency))), invoice, false);
            }

            if (invoice.Total > amountAuthorized) {
              return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Amount mismatch. Invoice Amount: {0}, Payment Amount: {1}", invoice.Total.ToString("F2"), amountAuthorized.ToString("F2")))), invoice, false);
            }

            payment.Authorized = true;

            return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, invoice.ShippingLineItems().Any());
              }

              return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("{0}", "QuickPay Payment AuthorizeAndCapture Not Implemented Yet"))), invoice, false);
        }
        private IPaymentResult ProcessPayment(IInvoice invoice, TransactionMode transactionMode, decimal amount, ProcessorArgumentCollection args)
        {
            var po = args.AsPurchaseOrderFormData();

            var payment = GatewayProviderService.CreatePayment(PaymentMethodType.PurchaseOrder, invoice.Total, PaymentMethod.Key);
            payment.CustomerKey = invoice.CustomerKey;
            payment.Authorized = false;
            payment.Collected = false;
            payment.PaymentMethodName = "Purchase Order";

            
            var result = _processor.ProcessPayment(invoice, payment, amount, po);

            GatewayProviderService.Save(payment);

            if (!result.Payment.Success)
            {
                GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Denied, result.Payment.Exception.Message, 0);
            }
            else
            {
                MerchelloContext.Current.Services.InvoiceService.Save(invoice, false);
                GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Debit,
                    payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.AuthorizationTransactionResult) +
                    (transactionMode == TransactionMode.AuthorizeAndCapture ? string.Empty : " to show record of Authorization"),
                    transactionMode == TransactionMode.AuthorizeAndCapture ? invoice.Total : 0);
            }

            return result;
        }
Ejemplo n.º 4
0
        private IPaymentResult ProcessPayment(IInvoice invoice, TransactionMode transactionMode, decimal amount, ProcessorArgumentCollection args)
        {
            var cc = args.AsCreditCardFormData();

            var payment = GatewayProviderService.CreatePayment(PaymentMethodType.CreditCard, invoice.Total, PaymentMethod.Key);
            payment.CustomerKey = invoice.CustomerKey;
            payment.Authorized = false;
            payment.Collected = false;
            payment.PaymentMethodName = string.Format("{0} Stripe Credit Card", cc.CreditCardType);
            payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.CcLastFour, cc.CardNumber.Substring(cc.CardNumber.Length - 4, 4).EncryptWithMachineKey());

            
            var result = _processor.ProcessPayment(invoice, payment, transactionMode, amount, cc);

            GatewayProviderService.Save(payment);

            if (!result.Payment.Success)
            {
                GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Denied, result.Payment.Exception.Message, 0);
            }
            else
            {
                GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Debit,
                    //payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.AuthorizationTransactionResult) +
                    (transactionMode == TransactionMode.AuthorizeAndCapture ? string.Empty : " to show record of Authorization"),
                    transactionMode == TransactionMode.AuthorizeAndCapture ? invoice.Total : 0);
            }

            return result;
        }
Ejemplo n.º 5
0
        public int Hurl(string storedProcedureName, System.Collections.Generic.List<dynamic> objects, TransactionMode transMode)
        {
            // This has slightly different logic because we need to scope the transaction differently.
            int numberOfRecordsAffected = 0;
            SqlTransaction transaction = null;

            using (SqlConnection dbConn = new SqlConnection(this.ConnectionString))
            {
                using (SqlCommand dbComm = new SqlCommand(storedProcedureName, dbConn) { CommandType = System.Data.CommandType.StoredProcedure })
                {
                    if (transMode == TransactionMode.On)
                    {
                        transaction = dbConn.BeginTransaction();
                    }

                    foreach (dynamic obj in objects)
                    {
                        dbComm.Parameters.Clear();
                        string jsonString = JsonConvert.SerializeObject(obj);
                        dbComm.Parameters.AddRange(jsonString.DeserializeJsonIntoSqlParameters());

                        if (dbConn.State != System.Data.ConnectionState.Open) { dbConn.Open(); }
                        numberOfRecordsAffected += dbComm.ExecuteNonQuery();
                    }

                    if (transaction != null) { transaction.Commit(); }
                }
            }

            return numberOfRecordsAffected;
        }
 private void OnNewTransaction(ITransaction transaction, TransactionMode transactionMode, IsolationMode isolationMode, bool distributedTransaction)
 {
     if (!transaction.DistributedTransaction)
     {
         transaction.Enlist(new RhinoTransactionResourceAdapter(transactionMode));
     }
 }
Ejemplo n.º 7
0
		protected TransactionBase(string name, TransactionMode mode, IsolationMode isolationMode)
		{
			theName = name ?? string.Empty;
			_TransactionMode = mode;
			_IsolationMode = isolationMode;
			Status = TransactionStatus.NoTransaction;
			Context = new Hashtable();
		}
		public ITransaction CreateTransaction(TransactionMode transactionMode, IsolationMode isolationMode,
		                                      bool distributedTransaction)
		{
			_current = new MockTransaction();

			_transactions++;

			return _current;
		}
Ejemplo n.º 9
0
        public ITransaction BeginTransaction(IsolationLevel isolationLevel, TransactionMode mode)
        {
            Guard.Against<InvalidOperationException>(Transaction != null, "There is a active transcation, cannot begin a new transaction.");

            var scope = TransactionScopeHelper.CreateScope(isolationLevel, mode);

            var transaction = new UnitOfWorkTransaction(this, scope);

            return transaction;
        }
 ///<summary>
 /// Create a new <typeparamref name="TransactionScope"/> using the supplied parameters.
 ///</summary>
 ///<param name="isolationLevel"></param>
 ///<param name="txMode"></param>
 ///<returns></returns>
 ///<exception cref="NotImplementedException"></exception>
 public static TransactionScope CreateScope(IsolationLevel isolationLevel, TransactionMode txMode) {
     if (txMode == TransactionMode.New) {
         Logger.Debug(x => x("Creating a new TransactionScope with TransactionScopeOption.RequiresNew"));
         return new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { IsolationLevel = isolationLevel });
     }
     if (txMode == TransactionMode.Supress) {
         Logger.Debug(x => x("Creating a new TransactionScope with TransactionScopeOption.Supress"));
         return new TransactionScope(TransactionScopeOption.Suppress);
     }
     Logger.Debug(x => x("Creating a new TransactionScope with TransactionScopeOption.Required"));
     return new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = isolationLevel });
 }
        public ITransaction CreateTransaction(TransactionMode txMode, IsolationMode iMode, bool isAmbient, bool isReadOnly)
		{
			txMode = ObtainDefaultTransactionMode(txMode);

			AssertModeSupported(txMode);

			if (CurrentTransaction == null &&
			    (txMode == TransactionMode.Supported ||
			     txMode == TransactionMode.NotSupported))
			{
				return null;
			}

			TransactionBase transaction = null;

			if (CurrentTransaction != null)
			{
				if (txMode == TransactionMode.Requires || txMode == TransactionMode.Supported)
				{
					transaction = ((TransactionBase)CurrentTransaction).CreateChildTransaction();

					logger.DebugFormat("Child transaction \"{0}\" created with mode '{1}'.", transaction.Name, txMode);
				}
			}

			if (transaction == null)
			{
				transaction = InstantiateTransaction(txMode, iMode, isAmbient, isReadOnly);

				if (isAmbient)
				{
#if MONO
					throw new NotSupportedException("Distributed transactions are not supported on Mono");
#else
					transaction.CreateAmbientTransaction();
#endif
				}

				logger.DebugFormat("Transaction \"{0}\" created. ", transaction.Name);
			}

			activityManager.CurrentActivity.Push(transaction);

			if (transaction.IsChildTransaction)
				ChildTransactionCreated.Fire(this, new TransactionEventArgs(transaction));
			else
				TransactionCreated.Fire(this, new TransactionEventArgs(transaction));

			return transaction;
		}
Ejemplo n.º 12
0
 internal static string BeginTransactionWithMode(TransactionMode mode)
 {
     switch (mode)
     {
         case TransactionMode.Deferred:
             return "BEGIN DEFERRED TRANSACTION";
         case TransactionMode.Exclusive:
             return "BEGIN EXCLUSIVE TRANSACTION";
         case TransactionMode.Immediate:
             return "BEGIN IMMEDIATE TRANSACTION";
         default:
             throw new ArgumentException("Not a valid TransactionMode");
     }
 }
Ejemplo n.º 13
0
 public override void BeginThreadTransaction(TransactionMode mode)
 {
     if (mode != TransactionMode.ReplicationSlave)
     {
         throw new ArgumentException("Illegal transaction mode");
     }
     lck.SharedLock();
     Page pg = pool.getPage(0);
     header.unpack(pg.data);
     pool.unfix(pg);
     currIndex = 1 - header.curr;
     currIndexSize = header.root[1 - currIndex].indexUsed;
     committedIndexSize = currIndexSize;
     usedSize = header.root[currIndex].size;
 }
Ejemplo n.º 14
0
		public AbstractTransaction(TransactionMode transactionMode, IsolationMode isolationMode, bool distributedTransaction,
		                           string name) : this()
		{
			this.transactionMode = transactionMode;
			this.isolationMode = isolationMode;
			this.distributedTransaction = distributedTransaction;

			if (String.IsNullOrEmpty(name))
			{
				this.name = ObtainName();
			}
			else
			{
				this.name = name;
			}
		}
Ejemplo n.º 15
0
        public FileBasedPersistentSource(string basePath, string prefix, TransactionMode transactionMode)
        {
            SyncLock = new object();
            this.basePath = basePath;
            this.prefix = prefix;
            this.transactionMode = transactionMode;
            dataPath = Path.Combine(basePath, prefix + ".data");
            logPath = Path.Combine(basePath, prefix + ".log");


            RecoverFromFailedRename(dataPath);
            RecoverFromFailedRename(logPath);

            CreatedNew = File.Exists(logPath) == false;

            OpenFiles();
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Creates a context with an optionally open database and SMTP connection.
        /// </summary>
        /// <param name="openConnection">True if a database connection should be opened.</param>
        /// <param name="beginTransaction">True if a transaction is required.</param>
        /// <param name="openSmtp">True if an SMTP connection should be opened.</param>
        /// <returns>A valid connection.</returns>
        public Context CreateContext(ConnectionMode connectionMode, TransactionMode transactionMode)
        {
            var context = new Context()
            {
                ConnectionString = connectionString,
                ConnectionMode = connectionMode,
                TransactionMode = transactionMode,

                UserGuid = userGuid,
                UserName = userName,
            };

            context.ClusterProperty.Name = clusterName;
            context.DomainProperty.Name = domainName;
            context.FederationProperty.Name = federationName;

            return context;
        }
        /// <summary>
        ///     Processes the Authorize and AuthorizeAndCapture transactions
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice" /> to be paid</param>
        /// <param name="payment">The <see cref="IPayment" /> record</param>
        /// <param name="transactionMode">Authorize or AuthorizeAndCapture</param>
        /// <param name="amount">The money amount to be processed</param>
        /// <param name="creditCard">The <see cref="CreditCardFormData" /></param>
        /// <returns>The <see cref="IPaymentResult" /></returns>
        public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, TransactionMode transactionMode,
            decimal amount, CreditCardFormData creditCard)
        {
            if (!IsValidCurrencyCode(invoice.CurrencyCode()))
                return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception("Invalid currency")), invoice,
                    false);

            // The minimum amount is $0.50 (or equivalent in charge currency).
            // Test that the payment meets the minimum amount (for USD only).
            if (invoice.CurrencyCode() == "USD")
            {
                if (amount < 0.5m)
                    return
                        new PaymentResult(
                            Attempt<IPayment>.Fail(payment, new Exception("Invalid amount (less than 0.50 USD)")),
                            invoice, false);
            }
            else
            {
                if (amount < 1)
                    return
                        new PaymentResult(
                            Attempt<IPayment>.Fail(payment,
                                new Exception("Invalid amount (less than 1 " + invoice.CurrencyCode() + ")")),
                            invoice, false);
            }

            var requestParams = StripeHelper.PreparePostDataForProcessPayment(invoice.GetBillingAddress(), transactionMode,
                ConvertAmount(invoice, amount), invoice.CurrencyCode(), creditCard, invoice.PrefixedInvoiceNumber(),
                string.Format("Full invoice #{0}", invoice.PrefixedInvoiceNumber()));

            // https://stripe.com/docs/api#create_charge
            try
            {
                var response = StripeHelper.MakeStripeApiRequest("https://api.stripe.com/v1/charges", "POST", requestParams, _settings);
                return GetProcessPaymentResult(invoice, payment, response);
            }
            catch (WebException ex)
            {
                return GetProcessPaymentResult(invoice, payment, (HttpWebResponse) ex.Response);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Enlists a <see cref="UnitOfWorkScope"/> instance with the transaction manager,
        /// with the specified transaction mode.
        /// </summary>
        /// <param name="scope">The <see cref="IUnitOfWorkScope"/> to register.</param>
        /// <param name="mode">A <see cref="TransactionMode"/> enum specifying the transaciton
        /// mode of the unit of work.</param>
        public void EnlistScope(IUnitOfWorkScope scope, TransactionMode mode)
        {
            _logger.Info(string.Format("Enlisting scope {0} with transaction manager {1} with transaction mode {2}",
                                scope.ScopeId,
                                _transactionManagerId,
                                mode));

            var uowFactory = ServiceLocator.Current.GetInstance<IUnitOfWorkFactory>();
            if (_transactions.Count == 0 ||
                mode == TransactionMode.New ||
                mode == TransactionMode.Supress)
            {
                _logger.Debug(string.Format("Enlisting scope {0} with mode {1} requires a new TransactionScope to be created.", scope.ScopeId, mode));
                var txScope = TransactionScopeHelper.CreateScope(UnitOfWorkSettings.DefaultIsolation, mode);
                var unitOfWork = uowFactory.Create();
                var transaction = new UnitOfWorkTransaction(unitOfWork, txScope);
                transaction.TransactionDisposing += OnTransactionDisposing;
                transaction.EnlistScope(scope);
                _transactions.AddFirst(transaction);
                return;
            }
            CurrentTransaction.EnlistScope(scope);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TransactionScope"/> class.
        /// </summary>
        public TransactionScope(
            TransactionMode mode = TransactionMode.New,
            IsolationLevel isolation = IsolationLevel.Unspecified,
            OnDispose ondispose = OnDispose.Commit,
            ISessionScope parent = null,
            ISessionFactoryHolder holder = null,
            IThreadScopeInfo scopeinfo = null
            )
            : base(FlushAction.Config, isolation, ondispose, parent, holder, scopeinfo)
        {
            this.mode = mode;

            parentTransactionScope = ParentScope as TransactionScope;

            if (mode == TransactionMode.New) {
                if (parentTransactionScope != null) {
                    parentTransactionScope = null;
                    ParentScope = null;
                } else {
                    parentTransactionScope = null;
                }
            }
        }
Ejemplo n.º 20
0
        public int Hurl(string storedProcedureName, string jsonData, TransactionMode transMode)
        {
            int numberOfRecordsAffected = 0;
            SqlTransaction transaction = null;

            using (SqlConnection dbConn = new SqlConnection(this.ConnectionString))
            {
                using (SqlCommand dbComm = new SqlCommand(storedProcedureName, dbConn) { CommandType = System.Data.CommandType.StoredProcedure })
                {
                    if (transMode == TransactionMode.On)
                    {
                        transaction = dbConn.BeginTransaction();
                    }

                    dbComm.Parameters.AddRange(jsonData.DeserializeJsonIntoSqlParameters());

                    dbConn.Open();
                    numberOfRecordsAffected = dbComm.ExecuteNonQuery();
                    if (transaction != null) { transaction.Commit(); }
                }
            }

            return numberOfRecordsAffected;
        }
Ejemplo n.º 21
0
        public async Task <int> HurlAsync(string storedProcedureName, string jsonData, TransactionMode transMode)
        {
            int            numberOfRecordsAffected = 0;
            SqlTransaction transaction             = null;

            using (SqlConnection dbConn = new SqlConnection(this.ConnectionString))
            {
                using (SqlCommand dbComm = new SqlCommand(storedProcedureName, dbConn)
                {
                    CommandType = System.Data.CommandType.StoredProcedure
                })
                {
                    if (transMode == TransactionMode.On)
                    {
                        transaction = dbConn.BeginTransaction();
                    }

                    dbComm.Parameters.AddRange(jsonData.DeserializeJsonIntoSqlParameters());

                    dbConn.Open();
                    numberOfRecordsAffected = await dbComm.ExecuteNonQueryAsync();

                    if (transaction != null)
                    {
                        transaction.Commit();
                    }
                }
            }

            return(numberOfRecordsAffected);
        }
Ejemplo n.º 22
0
        public async Task <int> HurlAsync(string storedProcedureName, System.Collections.Generic.List <dynamic> objects, TransactionMode transMode)
        {
            // This has slightly different logic because we need to scope the transaction differently.
            int            numberOfRecordsAffected = 0;
            SqlTransaction transaction             = null;

            using (SqlConnection dbConn = new SqlConnection(this.ConnectionString))
            {
                using (SqlCommand dbComm = new SqlCommand(storedProcedureName, dbConn)
                {
                    CommandType = System.Data.CommandType.StoredProcedure
                })
                {
                    if (transMode == TransactionMode.On)
                    {
                        transaction = dbConn.BeginTransaction();
                    }

                    foreach (dynamic obj in objects)
                    {
                        dbComm.Parameters.Clear();
                        string jsonString = JsonConvert.SerializeObject(obj);
                        dbComm.Parameters.AddRange(jsonString.DeserializeJsonIntoSqlParameters());

                        if (dbConn.State != System.Data.ConnectionState.Open)
                        {
                            dbConn.Open();
                        }
                        numberOfRecordsAffected += await dbComm.ExecuteNonQueryAsync();
                    }

                    if (transaction != null)
                    {
                        transaction.Commit();
                    }
                }
            }

            return(numberOfRecordsAffected);
        }
 private void btnCancel_Click(object sender, EventArgs e)
 {
     //if transaction is cancelled, transaction mode should return to view mode
     Mode = TransactionMode.View;
 }
Ejemplo n.º 24
0
 public int Hurl(string storedProcedureName, dynamic obj, TransactionMode transMode)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 25
0
 public async Task <int> HurlAsync(string storedProcedureName, dynamic obj, TransactionMode transMode)
 {
     return(await HurlAsync(storedProcedureName, JsonConvert.SerializeObject(obj), transMode));
 }
Ejemplo n.º 26
0
 public TalkactiveTransaction(TransactionMode transactionMode, IsolationMode isolationMode, bool isAmbient, bool isReadOnly) :
     base(null, transactionMode, isolationMode)
 {
     _IsAmbient  = isAmbient;
     _IsReadOnly = isReadOnly;
 }
        /// <summary>
        /// Insert the specified data.
        /// </summary>
        /// <param name="data">Data.</param>
        public virtual TData Insert(TData data, TransactionMode mode, IPrincipal principal)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            DataPersistingEventArgs <TData> preArgs = new DataPersistingEventArgs <TData>(data, mode, principal);

            this.Inserting?.Invoke(this, preArgs);
            if (preArgs.Cancel)
            {
                this.m_tracer.TraceWarning("Pre-Event handler indicates abort insert for {0}", data);
                return(data);
            }

#if PERFMON
            Stopwatch sw = new Stopwatch();
            sw.Start();
#endif

            // Persist objectel
            using (var context = this.CreateConnection(principal))
                try
                {
                    using (context.LockConnection())
                    {
                        try
                        {
                            // Does this object already exist?
                            if (data.Key.HasValue && this.Get(context, data.Key.Value) != null)
                            {
                                throw new DuplicateKeyException($"Object {typeof(TData).Name} with key {data.Key} already exists");
                            }

                            this.m_tracer.TraceVerbose("INSERT {0}", data);

                            context.Connection.BeginTransaction();
                            data = this.Insert(context, data);

                            if (mode == TransactionMode.Commit)
                            {
                                context.Connection.Commit();
                            }
                            else
                            {
                                context.Connection.Rollback();
                            }
                            // Remove from the cache
                            foreach (var itm in context.CacheOnCommit.AsParallel())
                            {
                                ApplicationContext.Current.GetService <IDataCachingService>().Add(itm);
                            }
                        }
                        catch (Exception e)
                        {
                            this.m_tracer.TraceError("Error : {0}", e);
                            context.Connection.Rollback();
                            throw new LocalPersistenceException(SynchronizationOperationType.Insert, data, e);
                        }
                    }
                    this.Inserted?.Invoke(this, new DataPersistedEventArgs <TData>(data, mode, principal));
                    return(data);
                }
                catch (SQLiteException e)
                {
                    this.m_tracer.TraceError("Error inserting data {1} : {0}", e, context.Connection);
                    throw new DataPersistenceException($"Database error inserting {data}", e);
                }
            catch (Exception e)
            {
                throw new DataPersistenceException($"Error inserting {data}", e);
            }

#if PERFMON
            finally
            {
                sw.Stop();
                ApplicationContext.Current.PerformanceLog(typeof(TData).Name, nameof(Insert), "Complete", sw.Elapsed);
            }
#endif
        }
 /// <summary>
 /// Create a resource
 /// </summary>
 public Resource Create(Resource target, TransactionMode mode)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Delete a resource
 /// </summary>
 public Resource Delete(string id, TransactionMode mode)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Constructs a new container instance using the given string as the name
 /// or connection string for the database to which a connection will be made.
 /// </summary>
 /// <param name="nameOrConnectionString">
 /// Either the database name or a connection string.
 /// </param>
 /// <param name="transactionMode">The transaction behavior.</param>
 public EFUsersDomainContainer(string nameOrConnectionString, TransactionMode transactionMode)
     : base(nameOrConnectionString, transactionMode)
 {
 }
 /// <summary>
 /// Constructs a new container instance using a given connection.
 /// </summary>
 /// <param name="connection">The connection to use.</param>
 /// <param name="ownTheConnection">If true, hand over connection ownership to the container.</param>
 /// <param name="transactionMode">The transaction behavior.</param>
 public EFUsersDomainContainer(System.Data.Common.DbConnection connection, bool ownTheConnection, TransactionMode transactionMode)
     : base(connection, ownTheConnection, transactionMode)
 {
 }
 /// <summary>
 /// Constructs a new container instance using conventions to
 /// create the name of the database to which a connection will be made.
 /// The by-convention name is the full name (namespace + class name)
 /// of the derived container class.
 /// </summary>
 /// <param name="transactionMode">The transaction behavior.</param>
 public EFUsersDomainContainer(TransactionMode transactionMode)
     : base(transactionMode)
 {
 }
 private void btnEdit_Click(object sender, EventArgs e)
 {
     //same with others
     Mode = TransactionMode.Edit;
 }
 private void btnNew_Click(object sender, EventArgs e)
 {
     //upon clicking new the mode is in new hehe
     Mode = TransactionMode.New;
 }
        /// <summary>
        /// Obsolete the specified identified data
        /// </summary>
        /// <param name="data">Data.</param>
        public virtual TData Obsolete(TData data, TransactionMode mode, IPrincipal principal)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            else if (!data.Key.HasValue || data.Key == Guid.Empty)
            {
                throw new InvalidOperationException("Data missing key");
            }
#if PERFMON
            Stopwatch sw = new Stopwatch();
            sw.Start();
#endif
            DataPersistingEventArgs <TData> preArgs = new DataPersistingEventArgs <TData>(data, mode, principal);
            this.Obsoleting?.Invoke(this, preArgs);
            if (preArgs.Cancel)
            {
                this.m_tracer.TraceWarning("Pre-Event handler indicates abort for {0}", data);
                return(data);
            }

            // Obsolete object
            using (var context = this.CreateConnection(principal))
                try
                {
                    using (context.LockConnection())
                    {
                        try
                        {
                            this.m_tracer.TraceVerbose("OBSOLETE {0}", data);
                            context.Connection.BeginTransaction();

                            data = this.Obsolete(context, data);

                            if (mode == TransactionMode.Commit)
                            {
                                context.Connection.Commit();
                            }
                            else
                            {
                                context.Connection.Rollback();
                            }

                            // Remove from the cache
                            foreach (var itm in context.CacheOnCommit.AsParallel())
                            {
                                ApplicationContext.Current.GetService <IDataCachingService>().Remove(itm.Key.Value);
                            }
                        }
                        catch (Exception e)
                        {
                            this.m_tracer.TraceError("Error : {0}", e);
                            context.Connection.Rollback();
                            throw new LocalPersistenceException(SynchronizationOperationType.Obsolete, data, e);
                        }
                    }
                    this.Obsoleted?.Invoke(this, new DataPersistedEventArgs <TData>(data, mode, principal));

                    return(data);
                }
                catch (SQLiteException e)
                {
                    this.m_tracer.TraceError("Error obsoleting data {1} : {0}", e, context.Connection);
                    throw new DataPersistenceException($"Database error obsoleting {data}", e);
                }
            catch (Exception e) { throw new DataPersistenceException($"Error obsoleting {data}", e); }
#if PERFMON
            finally
            {
                sw.Stop();
                ApplicationContext.Current.PerformanceLog(typeof(TData).Name, nameof(Obsolete), "Complete", sw.Elapsed);
            }
#endif
        }
Ejemplo n.º 36
0
		/// <summary>
		/// Declares both the transaction mode and isolation 
		/// desired for this method. The transaction manager should
		/// obey the declaration.
		/// </summary>
		/// <param name="transactionMode"></param>
		/// <param name="isolationMode"></param>
		public TransactionAttribute(TransactionMode transactionMode, IsolationMode isolationMode)
		{
			_transactionMode = transactionMode;
			_isolationMode = isolationMode;
		}
Ejemplo n.º 37
0
 public OrderMarketRequest(string token, OrderStateCommand requestCommand, List <int> itemList, TransactionMode transactionMode)
     : base(token, requestCommand, itemList, transactionMode)
 {
 }
		public RhinoTransactionResourceAdapter(TransactionMode transactionMode)
		{
			this.transactionMode = transactionMode;
		}
 public void RunInTransaction(Action <IDatabaseConnection> action, TransactionMode mode)
 {
     _db.RunInTransaction(action, mode);
 }
Ejemplo n.º 40
0
 public async Task <int> HurlAsync(string storedProcedureName, List <dynamic> objects, TransactionMode transMode)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Overloaded Constructor.
 /// Creates a new instance of the <see cref="UnitOfWorkScope"/> class.
 /// </summary>
 /// <param name="mode">A <see cref="TransactionMode"/> enum specifying the transation mode
 /// of the unit of work.</param>
 public UnitOfWorkScope(TransactionMode mode)
 {
     UnitOfWorkManager.CurrentTransactionManager.EnlistScope(this, mode);
 }
Ejemplo n.º 42
0
		/// <summary>
		/// Factory method for creating a transaction.
		/// </summary>
		/// <param name="transactionMode">The transaction mode.</param>
		/// <param name="isolationMode">The isolation mode.</param>
		/// <param name="distributedTransaction">if set to <c>true</c>, the TM will create a distributed transaction.</param>
		/// <returns>A transaction</returns>
		protected virtual AbstractTransaction InstantiateTransaction(TransactionMode transactionMode, IsolationMode isolationMode, bool distributedTransaction)
		{
			return new StandardTransaction(
				new TransactionDelegate(RaiseTransactionCommitted),
				new TransactionDelegate(RaiseTransactionRolledback),
				new TransactionErrorDelegate(RaiseTransactionFailed), 
				transactionMode, isolationMode, distributedTransaction);
		}
Ejemplo n.º 43
0
 public int Hurl(string storedProcedureName, string jsonData, TransactionMode transMode)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 44
0
		protected virtual TransactionMode ObtainDefaultTransactionMode(TransactionMode transactionMode)
		{
			return TransactionMode.Requires;
		}
Ejemplo n.º 45
0
 public int Hurl(string storedProcedureName, dynamic obj, TransactionMode transMode)
 {
     return(Hurl(storedProcedureName, JsonConvert.SerializeObject(obj), transMode));
 }
Ejemplo n.º 46
0
		/// <summary>
		/// Creates a transaction.
		/// </summary>
		/// <param name="transactionMode">The transaction mode.</param>
		/// <param name="isolationMode">The isolation mode.</param>
		/// <returns></returns>
		public virtual ITransaction CreateTransaction(TransactionMode transactionMode, IsolationMode isolationMode)
		{
			return CreateTransaction(transactionMode, isolationMode, false);
		}
 /// <summary>
 /// <see cref="ITransactionManager.CreateTransaction(Castle.Services.Transaction.TransactionMode,Castle.Services.Transaction.IsolationMode)"/>.
 /// </summary>
 public ITransaction CreateTransaction(TransactionMode txMode, IsolationMode isolationMode)
 {
     return CreateTransaction(txMode, isolationMode, false);
 }
Ejemplo n.º 48
0
 public async Task <int> HurlAsync(string storedProcedureName, string jsonData, TransactionMode transMode)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 49
0
 public SendOptions WithTransactionMode(TransactionMode transactionMode)
 {
     this.SetApplicationProperty(MessageBrokers.ApplicationProperties.TransactionMode, (byte)transactionMode);
     return(this);
 }
Ejemplo n.º 50
0
 /// <summary>
 /// Creates an object that contains contextual information about the message broker transaction
 /// </summary>
 /// <param name="transactionReceiver">The message broker receiver</param>
 /// <param name="transactionMode">The transaction mode</param>
 public TransactionContext(string transactionReceiver, TransactionMode transactionMode)
 {
     TransactionReceiver = transactionReceiver;
     TransactionMode     = transactionMode;
 }
Ejemplo n.º 51
0
		/// <summary>
		/// Creates a transaction.
		/// </summary>
		/// <param name="transactionMode">The transaction mode.</param>
		/// <param name="isolationMode">The isolation mode.</param>
		/// <param name="distributedTransaction">if set to <c>true</c>, the TM will create a distributed transaction.</param>
		/// <returns></returns>
		public virtual ITransaction CreateTransaction(TransactionMode transactionMode, IsolationMode isolationMode, bool distributedTransaction)
		{
			if (transactionMode == TransactionMode.Unspecified)
			{
				transactionMode = ObtainDefaultTransactionMode(transactionMode);
			}

			CheckNotSupportedTransaction(transactionMode);

			if (CurrentTransaction == null &&
			    (transactionMode == TransactionMode.Supported ||
			     transactionMode == TransactionMode.NotSupported))
			{
				return null;
			}

			AbstractTransaction transaction = null;

			if (CurrentTransaction != null)
			{
				if (transactionMode == TransactionMode.Requires || transactionMode == TransactionMode.Supported)
				{
					transaction = ((StandardTransaction) CurrentTransaction).CreateChildTransaction();

					RaiseChildTransactionCreated(transaction, transactionMode, isolationMode, distributedTransaction);

					logger.DebugFormat("Child Transaction {0} created", transaction.GetHashCode());
				}
			}

			if (transaction == null)
			{
				transaction = InstantiateTransaction(transactionMode, isolationMode, distributedTransaction);

				if (distributedTransaction)
				{
#if MONO
					throw new TransactionException("Distributed transactions are not supported on Mono");
#else
					transaction.Enlist(new TransactionScopeResourceAdapter(transactionMode, isolationMode));
#endif
				}

				RaiseTransactionCreated(transaction, transactionMode, isolationMode, distributedTransaction);

				logger.DebugFormat("Transaction {0} created", transaction.GetHashCode());
			}

			transaction.Logger = logger.CreateChildLogger(transaction.GetType().FullName);

			activityManager.CurrentActivity.Push(transaction);

			return transaction;
		}
Ejemplo n.º 52
0
 protected virtual TransactionMode ObtainDefaultTransactionMode(TransactionMode transactionMode)
 {
     return(TransactionMode.Requires);
 }
Ejemplo n.º 53
0
		protected void RaiseChildTransactionCreated(ITransaction transaction, TransactionMode transactionMode,
													IsolationMode isolationMode, bool distributedTransaction)
		{
			TransactionCreationInfoDelegate eventDelegate =
				(TransactionCreationInfoDelegate) events[ChildTransactionCreatedEvent];

			if (eventDelegate != null)
			{
				eventDelegate(transaction, transactionMode, isolationMode, distributedTransaction);
			}
		}
 /// <summary>
 /// Gets the default transaction mode, i.e. the mode which is the current mode when
 /// <see cref="TransactionMode.Unspecified"/> is passed to <see cref="CreateTransaction(Castle.Services.Transaction.TransactionMode,Castle.Services.Transaction.IsolationMode)"/>.
 /// </summary>
 /// <param name="mode">The mode which was passed.</param>
 /// <returns>
 /// Requires &lt;- mode = Unspecified
 /// mode &lt;- otherwise
 /// </returns>
 protected virtual TransactionMode ObtainDefaultTransactionMode(TransactionMode mode)
 {
     return(mode == TransactionMode.Unspecified ? TransactionMode.Requires : mode);
 }
Ejemplo n.º 55
0
		private void CheckNotSupportedTransaction(TransactionMode transactionMode)
		{
			if (transactionMode == TransactionMode.NotSupported &&
			    CurrentTransaction != null &&
			    CurrentTransaction.Status == TransactionStatus.Active)
			{
				String message = "There is a transaction active and the transaction mode " +
				                 "explicit says that no transaction is supported for this context";

				logger.Error(message);

				throw new TransactionException(message);
			}
		}
 /// <summary>
 /// <see cref="ITransactionManager.CreateTransaction(Castle.Services.Transaction.TransactionMode,Castle.Services.Transaction.IsolationMode)"/>.
 /// </summary>
 public ITransaction CreateTransaction(TransactionMode txMode, IsolationMode isolationMode)
 {
     return(CreateTransaction(txMode, isolationMode, false, false));
 }
 /// <summary>
 /// Update a resource
 /// </summary>
 public Resource Update(string id, Resource target, TransactionMode mode)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 58
0
 public TalkativeTransaction(TransactionMode transactionMode, IsolationMode isolationMode, bool isAmbient) :
     base(null, transactionMode, isolationMode)
 {
     _IsAmbient = isAmbient;
 }
Ejemplo n.º 59
0
		/// <summary>
		/// Declares the transaction mode, but omits the isolation, 
		/// which means that the transaction manager should use the
		/// default value for it.
		/// </summary>
		/// <param name="transactionMode"></param>
		public TransactionAttribute(TransactionMode transactionMode) : this(transactionMode, IsolationMode.Unspecified)
		{
		}
Ejemplo n.º 60
0
 /// <summary>
 /// 根据指定的TransactionMode,创建一个ConnectionScope对象
 /// <remarks>
 /// <list type="bullet">
 /// <item><description>事务行为由<see cref="TransactionMode"/>枚举决定;</description></item>
 /// </list>
 /// </remarks>
 /// </summary>
 /// <param name="mode">事务模式</param>
 public ConnectionScope(TransactionMode mode)
 {
     Init(mode, null, null);
 }