예제 #1
0
        protected override void InitData()
        {
            base.InitData();

            if (Meta.Count > 0)
            {
                return;
            }

            if (XTrace.Debug)
            {
                XTrace.WriteLine("开始初始化{0}菜单数据……", typeof(TEntity).Name);
            }

            using (var trans = new EntityTransaction <TEntity>())
            {
                // 准备增加Admin目录下的所有页面
                ScanAndAdd();

                trans.Commit();
                if (XTrace.Debug)
                {
                    XTrace.WriteLine("完成初始化{0}菜单数据!", typeof(TEntity).Name);
                }
            }
        }
예제 #2
0
        public async Task <IHttpActionResult> PostReprocess([FromBody] EntityTransaction transaction)
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(TheSettingService);

            handler.Start(LOG_TAG, "PostReprocess", GetServiceProperties());

            try
            {
                ServiceLocationService locator = new ServiceLocationService();
                UriBuilderService      builder = new UriBuilderService(Constants.ApplicationInstance, Constants.EnqueuerServiceName);
                var partitionKey = (long)transaction.EntityType;
                IEnqueuerService enqueuerService = locator.Create <IEnqueuerService>(partitionKey, builder.ToUri());
                bool             isEnqueued      = await enqueuerService.EnqueueProcess(transaction);

                if (isEnqueued)
                {
                    return(Ok());
                }
                else
                {
                    throw new Exception("Enqueuing failed!!!");
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(BadRequest(ex.Message));
            }
            finally
            {
                handler.Stop(error);
            }
        }
        private DbCommand PrepareEntityCommandBeforeExecution(EntityCommand entityCommand)
        {
            if (1 != this._mappedCommandDefinitions.Count)
            {
                throw new NotSupportedException("MARS");
            }
            EntityTransaction      entityTransaction      = entityCommand.ValidateAndGetEntityTransaction();
            InterceptableDbCommand interceptableDbCommand = new InterceptableDbCommand(this._mappedCommandDefinitions[0].CreateCommand(), entityCommand.InterceptionContext, (DbDispatchers)null);

            CommandHelper.SetStoreProviderCommandState(entityCommand, entityTransaction, (DbCommand)interceptableDbCommand);
            bool flag = false;

            if (interceptableDbCommand.Parameters != null)
            {
                foreach (DbParameter parameter in interceptableDbCommand.Parameters)
                {
                    int index = entityCommand.Parameters.IndexOf(parameter.ParameterName);
                    if (-1 != index)
                    {
                        EntityCommandDefinition.SyncParameterProperties(entityCommand.Parameters[index], parameter, this._storeProviderServices);
                        if (parameter.Direction != ParameterDirection.Input)
                        {
                            flag = true;
                        }
                    }
                }
            }
            if (flag)
            {
                entityCommand.SetStoreProviderCommand((DbCommand)interceptableDbCommand);
            }
            return((DbCommand)interceptableDbCommand);
        }
예제 #4
0
 // <summary>
 // Constructs the DbContextTransaction object with the associated transaction object
 // </summary>
 // <param name="transaction">The EntityTransaction object to use</param>
 internal DbContextTransaction(EntityTransaction transaction)
 {
     DebugCheck.NotNull(transaction);
     _connection = transaction.Connection;
     EnsureOpenConnection();
     _entityTransaction = transaction;
 }
 /// <summary>
 /// Begins a transaction on the underlying store connection
 /// </summary>
 /// <returns>
 /// a <see cref="T:System.Data.Entity.DbContextTransaction" /> object wrapping access to the underlying store's transaction object
 /// </returns>
 public DbContextTransaction BeginTransaction()
 {
   EntityConnection connection = (EntityConnection) this._internalContext.ObjectContext.Connection;
   this._dbContextTransaction = new DbContextTransaction(connection);
   this._entityTransaction = connection.CurrentTransaction;
   return this._dbContextTransaction;
 }
예제 #6
0
파일: source.cs 프로젝트: winxxp/samples
        static public void Transactions()
        {
            //<snippetTransactionsWithEntityClient>
            using (EntityConnection con = new EntityConnection("name=AdventureWorksEntities"))
            {
                con.Open();
                EntityTransaction transaction = con.BeginTransaction();
                DbCommand         cmd         = con.CreateCommand();
                cmd.Transaction = transaction;
                cmd.CommandText = @"SELECT VALUE Contact FROM AdventureWorksEntities.Contacts 
                    AS Contact WHERE Contact.LastName = @ln";
                EntityParameter param = new EntityParameter();
                param.ParameterName = "ln";
                param.Value         = "Adams";
                cmd.Parameters.Add(param);

                using (DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
                {
                    // Iterate through the collection of Contact items.
                    while (rdr.Read())
                    {
                        Console.Write("First Name: " + rdr["FirstName"]);
                        Console.WriteLine("\tLast Name: " + rdr["LastName"]);
                    }
                }
                transaction.Commit();
            }
            //</snippetTransactionsWithEntityClient>
        }
        public void UpdateDocumentVariable(string RoleName,
                                           string ModuleName, string VariableName,
                                           string DocumentName, List <string> ListDocKey)
        {
            RoleModuleDocument rmd = new RoleModuleDocument();

            rmd.Dp           = _LoginObj.Dp;
            rmd.ProductName  = BaseFramework.ProductName;
            rmd.RoleName     = RoleName;
            rmd.ModuleName   = ModuleName;
            rmd.VariableName = VariableName;
            rmd.DocumentName = DocumentName;

            using (EntityTransaction tr = new EntityTransaction(rmd.Dp))
            {
                _LoginObj.Dp.ExecuteNonQuery(@"DELETE FROM 
                    _System_RoleModuleDocument WHERE RoleName=@0 AND ModuleName=@1 AND 
                    VariableName=@2 AND ProductName=@3",
                                             new FieldParam("0", RoleName),
                                             new FieldParam("1", ModuleName),
                                             new FieldParam("2", VariableName),
                                             new FieldParam("3", BaseFramework.ProductName));
                foreach (string DocumentKey in ListDocKey)
                {
                    rmd.DocumentKey = DocumentKey;
                    rmd.SaveNew();
                }
                tr.CommitTransaction();
            }
        }
예제 #8
0
        /// <summary>
        /// Executes a SQL command against the SQL connection.
        /// </summary>
        /// <param name="objectContext">The object context.</param>
        /// <param name="transaction">The transaction to use, if any.</param>
        /// <param name="command">The command to execute.</param>
        /// <returns>The result of executing the command.</returns>
        public static int ExecuteCommand(this ObjectContext objectContext, EntityTransaction transaction, string command)
        {
            if (objectContext == null)
            {
                throw new ArgumentNullException("objectContext");
            }
            if (string.IsNullOrEmpty(command))
            {
                throw new ArgumentNullException("command");
            }

            DbConnection connection = (EntityConnection)objectContext.Connection;
            bool         opening    = connection.State == ConnectionState.Closed;

            if (opening)
            {
                connection.Open();
            }

            DbCommand cmd = connection.CreateCommand();

            cmd.Transaction = transaction;
            cmd.CommandText = command;
            cmd.CommandType = CommandType.StoredProcedure;
            try {
                return(cmd.ExecuteNonQuery());
            } finally {
                if (opening && connection.State == ConnectionState.Open)
                {
                    connection.Close();
                }
            }
        }
예제 #9
0
        private void RecordTransaction(IProcessedArgs <TEntity> args)
        {
            EntityTransaction transaction = this.RecordTransactionEntry(args);

            this.RecordDestinationSystemEntity(transaction, args);
            this.RecordValueChanges(transaction, args);
        }
예제 #10
0
 // <summary>
 // Constructs the DbContextTransaction object with the associated connection object
 // and with the given isolation level
 // </summary>
 // <param name="connection">The EntityConnection object owning this transaction </param>
 // <param name="isolationLevel">The database isolation level with which the underlying store transaction will be created</param>
 internal DbContextTransaction(EntityConnection connection, IsolationLevel isolationLevel)
 {
     DebugCheck.NotNull(connection);
     _connection = connection;
     EnsureOpenConnection();
     _entityTransaction = _connection.BeginTransaction(isolationLevel);
 }
        public bool TransferData()
        {
            TableVersion tv = new TableVersion();

            using (EntityTransaction Tr = 
                new EntityTransaction(DpDestination)) 
            {
                foreach (TableTransfer tbl in ListTable) 
                {
                    tv.TableName= tbl.TableName;
                    DpSource.LoadEntity(tv, false);

                    TransferTable(new TableDef(tbl.TableName, tv.CreateStr),
                        tbl.Condition);
                }
                foreach (TypeTransfer typ in ListObjectType)
                {
                    TableDef td = MetaData.GetTableDef(typ.ObjectType);
                    TransferTable(td, typ.Condition);
                    foreach (EntityCollDef ecd in td.ChildEntities)
                        TransferTable(MetaData.GetTableDef(ecd.ChildType), 
                            typ.Condition);
                }
                Tr.CommitTransaction();
            }
            return true;
        }
예제 #12
0
        // Enqueuer Interface Implementation
        public async Task <bool> EnqueueProcess(EntityTransaction transaction)
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(SettingService);

            handler.Start(LOG_TAG, "EnqueueProcess", GetServiceProperties());
            bool blReturn = false;

            try
            {
                handler.Info("Processing business key: " + transaction.BusinessKey + " - entity type: " + transaction.EntityType);

                // Gets (or creates) a replicated dictionary called "ProcessQueue" in this partition.
                var requests = await this.StateManager.GetOrAddAsync <IReliableQueue <EntityTransaction> >(ProcessQueueName);

                using (var tx = this.StateManager.CreateTransaction())
                {
                    await requests.EnqueueAsync(tx, transaction);

                    await tx.CommitAsync();
                }

                blReturn = true;
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            finally
            {
                handler.Stop(error);
            }

            return(blReturn);
        }
예제 #13
0
        public async Task Process(EntityTransaction transaction)
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(SettingService);

            handler.Start(LOG_TAG, "Process", GetActorProperties());

            try
            {
                if (transaction == null)
                {
                    handler.Info("Process transactions is null");
                    return;
                }

                // Scheduler a reminder to reprocess myself and my parent
                // TODO: I think the actor does not evict from memory
                // as long as there are reminders. To garbage collect, reminders
                // have to be removed
                await this.RegisterReminderAsync(
                    ReprocessReminder,
                    ObjectToByteArray(transaction),
                    TimeSpan.FromSeconds(0),  // Remind immediately
                    TimeSpan.FromDays(1));    // Remind again in 1 day - useless of course!!
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            finally
            {
                handler.Stop(error);
            }
        }
예제 #14
0
        public static void PostIssue(int issueId)
        {
            // Open a connection manualy since EF has issues with MSDTC transactions
            var connection = new EntityConnection(ConfigurationManager.ConnectionStrings[INVENTORY_CONNECTION].ConnectionString);

            connection.Open();

            var context   = new InventoryEntities(connection);
            var issue     = context.Issues.Single(i => i.IssueId == issueId);
            var warehouse = issue.WarehouseId;

            try
            {
                using (EntityTransaction scope = connection.BeginTransaction())
                {
                    foreach (var item in issue.IssueItems)
                    {
                        // 1. Check the availablity of stock (ItemId and WarehouseId)
                        var stock = context.StockStatus.Single(s => s.ItemId == item.ItemId && s.WarehouseId == warehouse);

                        // 2. If availalbe < requested then throw an error
                        if (stock.Quantity < item.Quantity)
                        {
                            var msg = "Error posting current record. The requested and available quantity do not match.\n";
                            msg += string.Format("Item: {0} \nAvailable Quantity: {1}\nRequested Quantity:{2}", item.ItemDetail.ItemNo, stock.Quantity, item.Quantity);
                            throw new ApplicationException(msg);
                        }

                        // 3. If available > requested then update balance and set status of issue to posted.
                        var status = context.StockStatus.Single(s => s.ItemId == item.ItemId && s.WarehouseId == warehouse);
                        status.Quantity -= item.Quantity;

                        // 4. Add transaction log to stock_transaction
                        var transaction = new StockTransaction();
                        transaction.TransactionTypeId = OWNER_ISSUE;
                        transaction.OwnerId           = issue.IssueId;
                        transaction.ItemId            = item.ItemId;
                        transaction.Quantity          = item.Quantity;
                        transaction.WarehouseId       = warehouse;
                        transaction.TransactionDate   = DateTime.Now;
                        AddTransactionRecord(transaction);

                        issue.StatusId   = STATUS_POSTED;
                        issue.PostedDate = DateTime.Now;  //TODO: Consider getting the date from the server instead of the client.
                        var user = SecurityHelper.GetUserDetail(Thread.CurrentPrincipal.Identity.Name);
                        issue.PostedBy = string.Format("{0} ({1})", user.FullName, user.UserName);

                        // SEND ALL CHANGES TO THE DATABASE - MIGHTY SAVE!!!!!!
                        context.SaveChanges();

                        scope.Commit();
                    }
                }
            }
            catch (Exception exception)
            {
                throw new ApplicationException("Error occured while posting the current issue.", exception);
            }
        }
예제 #15
0
        /// <summary>
        /// Begins a transaction on the underlying store connection using the specified isolation level
        /// </summary>
        /// <param name="isolationLevel">The database isolation level with which the underlying store transaction will be created</param>
        /// <returns>
        /// a <see cref="DbContextTransaction" /> object wrapping access to the underlying store's transaction object
        /// </returns>
        public DbContextTransaction BeginTransaction(IsolationLevel isolationLevel)
        {
            var entityConnection = (EntityConnection)_internalContext.ObjectContext.Connection;

            _dbContextTransaction = new DbContextTransaction(entityConnection, isolationLevel);
            _entityTransaction    = entityConnection.CurrentTransaction;

            return(_dbContextTransaction);
        }
 internal static void SetStoreProviderCommandState(
     EntityCommand entityCommand,
     EntityTransaction entityTransaction,
     DbCommand storeProviderCommand)
 {
     storeProviderCommand.CommandTimeout   = entityCommand.CommandTimeout;
     storeProviderCommand.Connection       = entityCommand.Connection.StoreConnection;
     storeProviderCommand.Transaction      = entityTransaction?.StoreTransaction;
     storeProviderCommand.UpdatedRowSource = entityCommand.UpdatedRowSource;
 }
        public override bool AnyModelTableExistsInDatabase(
            ObjectContext context,
            DbConnection connection,
            IEnumerable <EntitySet> modelTables,
            string edmMetadataContextTableName)
        {
            StringBuilder stringBuilder = new StringBuilder();

            foreach (EntitySet modelTable in modelTables)
            {
                stringBuilder.Append("'");
                stringBuilder.Append((string)modelTable.MetadataProperties["Schema"].Value);
                stringBuilder.Append(".");
                stringBuilder.Append(this.GetTableName(modelTable));
                stringBuilder.Append("',");
            }
            stringBuilder.Remove(stringBuilder.Length - 1, 1);
            using (DbCommand command = connection.CreateCommand())
            {
                command.CommandText = "\r\nSELECT Count(*)\r\nFROM INFORMATION_SCHEMA.TABLES AS t\r\nWHERE t.TABLE_SCHEMA + '.' + t.TABLE_NAME IN (" + (object)stringBuilder + ")\r\n    OR t.TABLE_NAME = '" + edmMetadataContextTableName + "'";
                bool flag = true;
                if (DbInterception.Dispatch.Connection.GetState(connection, context.InterceptionContext) == ConnectionState.Open)
                {
                    flag = false;
                    EntityTransaction currentTransaction = ((EntityConnection)context.Connection).CurrentTransaction;
                    if (currentTransaction != null)
                    {
                        command.Transaction = currentTransaction.StoreTransaction;
                    }
                }
                IDbExecutionStrategy executionStrategy = DbProviderServices.GetExecutionStrategy(connection);
                try
                {
                    return(executionStrategy.Execute <bool>((Func <bool>)(() =>
                    {
                        if (DbInterception.Dispatch.Connection.GetState(connection, context.InterceptionContext) == ConnectionState.Broken)
                        {
                            DbInterception.Dispatch.Connection.Close(connection, context.InterceptionContext);
                        }
                        if (DbInterception.Dispatch.Connection.GetState(connection, context.InterceptionContext) == ConnectionState.Closed)
                        {
                            DbInterception.Dispatch.Connection.Open(connection, context.InterceptionContext);
                        }
                        return (int)DbInterception.Dispatch.Command.Scalar(command, new DbCommandInterceptionContext(context.InterceptionContext)) > 0;
                    })));
                }
                finally
                {
                    if (flag && DbInterception.Dispatch.Connection.GetState(connection, context.InterceptionContext) != ConnectionState.Closed)
                    {
                        DbInterception.Dispatch.Connection.Close(connection, context.InterceptionContext);
                    }
                }
            }
        }
예제 #18
0
        // <summary>
        // Given an entity command and entity transaction, passes through relevant state to store provider
        // command.
        // </summary>
        // <param name="entityCommand"> Entity command. Must not be null. </param>
        // <param name="entityTransaction"> Entity transaction. Must not be null. </param>
        // <param name="storeProviderCommand"> Store provider command that is being setup. Must not be null. </param>
        internal static void SetStoreProviderCommandState(
            EntityCommand entityCommand, EntityTransaction entityTransaction, DbCommand storeProviderCommand)
        {
            DebugCheck.NotNull(entityCommand);
            DebugCheck.NotNull(storeProviderCommand);

            storeProviderCommand.CommandTimeout   = entityCommand.CommandTimeout;
            storeProviderCommand.Connection       = (entityCommand.Connection).StoreConnection;
            storeProviderCommand.Transaction      = (null != entityTransaction) ? entityTransaction.StoreTransaction : null;
            storeProviderCommand.UpdatedRowSource = entityCommand.UpdatedRowSource;
        }
예제 #19
0
        /// <summary>
        /// Begins a transaction on the underlying store connection
        /// </summary>
        /// <returns>
        /// a <see cref="DbContextTransaction" /> object wrapping access to the underlying store's transaction object
        /// </returns>
        public DbContextTransaction BeginTransaction()
        {
            var entityConnection = (EntityConnection)_internalContext.ObjectContext.Connection;

            _dbContextTransaction = _internalContext.DefaultIsolationLevel == null
                ? new DbContextTransaction(entityConnection)
                : new DbContextTransaction(entityConnection, _internalContext.DefaultIsolationLevel.Value);
            _entityTransaction = entityConnection.CurrentTransaction;

            return(_dbContextTransaction);
        }
예제 #20
0
        public virtual EntityConnectionProxy CreateNew(DbConnection storeConnection)
        {
            EntityConnection  entityConnection   = new EntityConnection(this._entityConnection.GetMetadataWorkspace(), storeConnection);
            EntityTransaction currentTransaction = this._entityConnection.CurrentTransaction;

            if (currentTransaction != null && DbInterception.Dispatch.Transaction.GetConnection(currentTransaction.StoreTransaction, this._entityConnection.InterceptionContext) == storeConnection)
            {
                entityConnection.UseStoreTransaction(currentTransaction.StoreTransaction);
            }
            return(new EntityConnectionProxy(entityConnection));
        }
예제 #21
0
        // Override BeginTransaction so we can keep the current transaction in a property
        protected override IDbTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel)
        {
            var conn = GetDbConnection();

            if (conn == null)
            {
                return(null);
            }
            EntityTransaction = (EntityTransaction)conn.BeginTransaction(isolationLevel);
            return(EntityTransaction);
        }
예제 #22
0
        public static int ExecuteCommand(this ObjectContext objectContext, string command)
        {
            // Try to automatically add the appropriate transaction if one is known.
            EntityTransaction transaction = null;

            if (Database.IsDataContextInitialized && Database.DataContext == objectContext)
            {
                transaction = Database.DataContextTransaction;
            }
            return(ExecuteCommand(objectContext, transaction, command));
        }
    public void example()
    {
        using (TransactionScope mainScope = new TransactionScope())
        {
            // ADO.NET
            using (SqlConnection firstConnection = new SqlConnection("First"))
            {
                firstConnection.Open();
                using (SqlCommand firstCommand = new SqlCommand("FirstQueryText", firstConnection))
                {
                    Int32 recordsAffected = firstCommand.ExecuteNonQuery();
                }

                using (SqlConnection secondConnection = new SqlConnection("Second"))
                {
                    secondConnection.Open();
                    using (SqlCommand secondCommand = new SqlCommand("SecondQueryText", secondConnection))
                    {
                        Int32 secondAffected = secondCommand.ExecuteNonQuery();
                    }
                }
            }
            mainScope.Complete();
        }

        //Entity Connection
        using (TestEntities database = new TestEntities())
        {
            Customer cust = new Customer();
            cust.FirstName = "Ronald";
            cust.LastName  = "McDonald";
            cust.AccountId = 3;
            database.Customers.Add(cust);
            database.SaveChanges();
        }

        using (EntityConnection connection = new EntityConnection("TestEntities"))
        {
            using (EntityTransaction trans = connection.BeginTransaction(System.Data.IsolationLevel.Serializable))
            {
                EntityCommand CurrentCommand = new EntityCommand("SOME UPDATE STATEMENT", connection, trans);
                connection.Open();
                Int32 RecordsAffected = CurrentCommand.ExecuteNonQuery();
                trans.Commit();
            }
        }

        SqlConnection myConnection = new SqlConnection("Connection String");
    }
예제 #24
0
        /// <summary>删除用户</summary>
        /// <param name="uid"></param>
        /// <param name="delposts"></param>
        /// <param name="delpms"></param>
        /// <returns></returns>
        public Boolean Delete(Boolean delposts, Boolean delpms)
        {
            var user = this;

            using (var tran = new EntityTransaction <User>())
            {
                user.Delete();

                var tps = Topic.FindAllByPosterID(user.ID);
                var lps = Topic.FindAllByLastPostID(user.ID);
                if (delposts)
                {
                    tps.Delete();
                    lps.Delete();

                    var ps = Post.FindAllByPosterID(user.ID);
                    ps.Delete();
                }
                else
                {
                    tps.SetItem(Topic._.Poster, "该用户已被删除");
                    lps.SetItem(Topic._.LastPoster, "该用户已被删除");

                    tps.Save();
                    lps.Save();
                }

                var pms1 = ShortMessage.FindAllByMsgtoID(user.ID);
                var pms2 = ShortMessage.FindAllByMsgfromID(user.ID);
                if (delpms)
                {
                    pms1.Delete();
                    pms2.Delete();
                }
                else
                {
                    pms1.SetItem(ShortMessage._.Msgto, "该用户已被删除");
                    pms2.SetItem(ShortMessage._.Msgfrom, "该用户已被删除");

                    pms1.Save();
                    pms2.Save();
                }

                tran.Commit();
            }

            return(true);
        }
예제 #25
0
        /// <summary>
        /// Given an entity command, returns the associated entity transaction and performs validation
        /// to ensure the transaction is consistent.
        /// </summary>
        /// <param name="entityCommand">Entity command instance. Must not be null.</param>
        /// <returns>Entity transaction</returns>
        internal static EntityTransaction GetEntityTransaction(EntityCommand entityCommand)
        {
            Debug.Assert(null != entityCommand);
            EntityTransaction entityTransaction = (EntityTransaction)entityCommand.Transaction;

            // Check to make sure that either the command has no transaction associated with it, or it
            // matches the one used by the connection
            if (entityTransaction != null && entityTransaction != entityCommand.Connection.CurrentTransaction)
            {
                throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.EntityClient_InvalidTransactionForCommand);
            }
            // Now we have asserted that EntityCommand either has no transaction or has one that matches the
            // one used in the connection, we can simply use the connection's transaction object
            entityTransaction = entityCommand.Connection.CurrentTransaction;
            return(entityTransaction);
        }
 /* hack to set the current DbTransaction onto the DbCommand.  Transaction comes from EF private properties. */
 public void SetCurrentTransaction(System.Data.Common.DbCommand command)
 {
     if (EntityTransaction != null)
     {
         // get private member via reflection
         var bindingFlags  = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
         var etype         = EntityTransaction.GetType();
         var stProp        = etype.GetProperty("StoreTransaction", bindingFlags);
         var transaction   = stProp.GetValue(EntityTransaction, null);
         var dbTransaction = transaction as System.Data.Common.DbTransaction;
         if (dbTransaction != null)
         {
             command.Transaction = dbTransaction;
         }
     }
 }
예제 #27
0
파일: Node.Cache.cs 프로젝트: neshlabs/nesh
        private async Task <Entity> GetCacheEntity(Nuid entity_id)
        {
            try
            {
                IRedisDatabase db          = GetCache(entity_id);
                ITransaction   query_trans = db.Database.CreateTransaction();

                string type = await GetCacheType(entity_id);

                EntityTransaction trans = new EntityTransaction(entity_id, type);


                EntityPrefab entity_prefab = Prefabs.GetEntity(trans.Type);
                if (entity_prefab == null)
                {
                    throw new Exception($"Prefabs.GetEntity cant found {trans.Type}");
                }

                string field_key = CacheUtils.BuildFields(trans.Id);
                trans.Fields = query_trans.HashGetAllAsync(field_key);

                foreach (Table table in trans.Entity.GetTables())
                {
                    TablePrefab        table_prefab = entity_prefab.tables[table.GetName()];
                    string             table_key    = CacheUtils.BuildTable(trans.Id, table.GetName());
                    Task <HashEntry[]> key_values   = query_trans.HashGetAllAsync(table_key);
                    trans.AddTableTrans(table.GetName(), key_values);
                }

                bool redis_execute = await query_trans.ExecuteAsync();

                if (!redis_execute)
                {
                    throw new Exception("query_trans ExecuteAsync ERROR!!");
                }

                return(await BuildCacheEntity(trans));
            }
            catch (Exception ex)
            {
                _Logger.LogError(ex, "GetCacheEntities Failed");
            }

            return(null);
        }
예제 #28
0
        /// <summary>导入</summary>
        public virtual void Import()
        {
            using (var trans = new EntityTransaction <TEntity>())
            {
                //顶级节点根据名字合并
                if (ParentID == 0)
                {
                    var m = Find(__.Name, Name);
                    if (m != null)
                    {
                        this.ID       = m.ID;
                        this.Name     = m.Name;
                        this.ParentID = 0;
                        this.Url      = m.Url;
                        this.Remark   = m.Remark;

                        this.Update();
                    }
                    else
                    {
                        this.Insert();
                    }
                }
                else
                {
                    this.Insert();
                }

                //更新编号
                var list = Childs;
                if (list != null && list.Count > 0)
                {
                    foreach (TEntity item in list)
                    {
                        item.ParentID = ID;

                        item.Import();
                    }
                }

                trans.Commit();
            }
        }
예제 #29
0
 private void RecordValueChanges(
     EntityTransaction transaction, IProcessedArgs <TEntity> args)
 {
     if (this.loggingConfigurationProvider.MigrationConfiguration.ValueChanges)
     {
         foreach (ValueChange valueChange in args.ValueChanges)
         {
             this.safeRepository.CreateValueChange(
                 new PersistenceValueChange(
                     Guid.NewGuid(),
                     transaction.Id,
                     valueChange.ValueName,
                     args.Outcome != EntityTransactionOutcome.NewEntityCreated
                         ? valueChange.PreviousValue?.ToString()
                         : null,
                     valueChange.NewValue?.ToString()));
         }
     }
 }
예제 #30
0
        static void CurrentLogin_onLogon()
        {
            RingkasanAkun = new RingkasanAkun();

            using (EntityTransaction tr = new EntityTransaction(
                       BaseFramework.DefaultDp))
            {
                if (!BaseFramework.DefaultDp.Find
                    .IsExists <MataUang>(string.Empty))
                {
                    MataUang mu = new MataUang();
                    mu.KodeMataUang = "IDR";
                    mu.NamaMataUang = "Rupiah";
                    mu.Aktif        = true;
                    mu.SaveNew();
                }
                if (!BaseFramework.DefaultDp.Find
                    .IsExists <JenisDokSumberJurnal>("Otomatis=@0",
                                                     new FieldParam("0", false)))
                {
                    JenisDokSumberJurnal jds = new JenisDokSumberJurnal();
                    jds.JenisDokSumber = "Umum";
                    jds.Aktif          = true;
                    jds.SaveNew();
                }

                if (!BaseFramework.DefaultDp.Find
                    .IsExists <SetingPerusahaan>(string.Empty))
                {
                    SetingPerusahaan sp = new SetingPerusahaan();
                    sp.SetDefaultValue();
                    sp.TglMulaiSistemBaru = BaseFramework
                                            .TransDate.StartDate;
                    sp.SaveNew();
                }

                tr.CommitTransaction();
            }
            SetingPerusahaan.LoadEntity();
            RegisterAsPostedDocument("Penerimaan Kas Umum");
            RegisterAsPostedDocument("Pengeluaran Kas Umum");
            RegisterAsPostedDocument("Transfer Antar Kas");
        }