protected override void DoSetUp()
 {
     this.transactionManagerMock = Mockery.Create<ITransactionManager>();
     this.transactionAttribute = new TransactionAttribute
     {
         TransactionManager = this.transactionManagerMock.Object
     };
     this.filterContext = Mockery.Create<ActionExecutingContext>();
 }
Exemplo n.º 2
0
 protected virtual bool Attribute_GetUsage(ExecutionEngine engine)
 {
     if (engine.EvaluationStack.Pop() is InteropInterface _interface)
     {
         TransactionAttribute attr = _interface.GetInterface <TransactionAttribute>();
         if (attr == null)
         {
             return(false);
         }
         engine.EvaluationStack.Push((int)attr.Usage);
         return(true);
     }
     return(false);
 }
Exemplo n.º 3
0
        public void FeeIsSignatureContract_TestScope_NoScopeFAULT()
        {
            var wallet   = TestUtils.GenerateTestWallet();
            var snapshot = Blockchain.Singleton.GetSnapshot();

            // no password on this wallet
            using (var unlock = wallet.Unlock(""))
            {
                var acc = wallet.CreateAccount();

                // Fake balance

                var key = NativeContract.GAS.CreateStorageKey(20, acc.ScriptHash);

                var entry = snapshot.Storages.GetAndChange(key, () => new StorageItem(new AccountState()));

                entry.GetInteroperable <AccountState>().Balance = 10000 * NativeContract.GAS.Factor;

                // Make transaction
                // Manually creating script

                byte[] script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    // self-transfer of 1e-8 GAS
                    BigInteger value = (new BigDecimal(1, 8)).Value;
                    sb.EmitAppCall(NativeContract.GAS.Hash, "transfer", acc.ScriptHash, acc.ScriptHash, value);
                    sb.Emit(OpCode.ASSERT);
                    script = sb.ToArray();
                }

                // trying with no scope
                var attributes = new TransactionAttribute[] { };

                var signers = new Signer[] { new Signer
                                             {
                                                 Account          = acc.ScriptHash,
                                                 Scopes           = (WitnessScope)0xFF,
                                                 AllowedContracts = new[] { NativeContract.NEO.Hash, NativeContract.GAS.Hash }
                                             } };

                // using this...

                // expects FAULT on execution of 'transfer' Application script
                // due to lack of a valid witness validation
                Transaction tx = null;
                Assert.ThrowsException <InvalidOperationException>(() => tx = wallet.MakeTransaction(script, acc.ScriptHash, signers, attributes));
                Assert.IsNull(tx);
            }
        }
Exemplo n.º 4
0
 private bool Attribute_GetData(ExecutionEngine engine)
 {
     if (engine.CurrentContext.EvaluationStack.Pop() is InteropInterface _interface)
     {
         TransactionAttribute attr = _interface.GetInterface <TransactionAttribute>();
         if (attr == null)
         {
             return(false);
         }
         engine.CurrentContext.EvaluationStack.Push(attr.Data);
         return(true);
     }
     return(false);
 }
Exemplo n.º 5
0
        public virtual object Invoke(InterceptorContext context)
        {
            TransactionAttribute transAttr = (context.TargetMethodInfo.GetCustomAttributes(typeof(TransactionAttribute), true) as TransactionAttribute[])[0];

            TransactionOptions options = new TransactionOptions();

            options.IsolationLevel = transAttr.IsolationLevel;
            options.Timeout        = transAttr.TimeOut;
            using (TransactionScope tran = new TransactionScope(transAttr.ScopeOption, options, transAttr.EnterpriseServicesInteropOption))
            {
                object returnValue = context.Invoke();
                tran.Complete();
                return(returnValue);
            }
        }
        /// <summary>
        /// Get TransactionAttribute array from TransactionAttributes array
        /// </summary>
        /// <param name="attrs">TransactionAttributes to convert</param>
        /// <returns>TransactionAttribute array</returns>
        public TransactionAttribute[] GetTransactionAttributes(TransactionAttributes[] attrs)
        {
            var attrList = new List <TransactionAttribute>();

            for (int i = 0; i < attrs.Length; i++)
            {
                var txnAttr = new TransactionAttribute
                {
                    Data  = attrs[i].data.HexToBytes(),
                    Usage = (TransactionAttributeUsage)attrs[i].usage
                };

                attrList.Add(txnAttr);
            }

            return(attrList.ToArray());
        }
Exemplo n.º 7
0
        public void TestSign()
        {
            txManager = new TransactionManager(rpcClientMock.Object, sender);

            TransactionAttribute[] attributes = new TransactionAttribute[1]
            {
                new TransactionAttribute
                {
                    Usage = TransactionAttributeUsage.Url,
                    Data  = "53616d706c6555726c".HexToBytes() // "SampleUrl"
                }
            };

            Cosigner[] cosigners = new Cosigner[1] {
                new Cosigner {
                    Account = sender,
                    Scopes  = WitnessScope.Global
                }
            };

            byte[] script = new byte[1];
            txManager.MakeTransaction(script, attributes, cosigners)
            .AddSignature(keyPair1)
            .Sign();

            // get signature from Witnesses
            var tx = txManager.Tx;

            byte[] signature = tx.Witnesses[0].InvocationScript.Skip(2).ToArray();

            Assert.IsTrue(Crypto.VerifySignature(tx.GetHashData(), signature, keyPair1.PublicKey.EncodePoint(false).Skip(1).ToArray()));
            // verify network fee
            long networkFee = tx.Size * (long)1000 + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + InteropService.GetPrice(InteropService.Crypto.ECDsaVerify, null, null);

            Assert.AreEqual(networkFee, tx.NetworkFee);

            // duplicate sign should not add new witness
            txManager.AddSignature(keyPair1).Sign();
            Assert.AreEqual(1, txManager.Tx.Witnesses.Length);

            // throw exception when the KeyPair is wrong
            Assert.ThrowsException <Exception>(() => txManager.AddSignature(keyPair2).Sign());
        }
Exemplo n.º 8
0
        public void Init()
        {
            _context = Isolate.Fake.Instance <ActionExecutingContext>();
            _result  = Isolate.Fake.Instance <ActionExecutedContext>();

            _session     = Isolate.Fake.Instance <ISession>();
            _transaction = Isolate.Fake.Instance <ITransaction>();
            Isolate.WhenCalled(() => _session.Transaction).WillReturn(_transaction);
            Isolate.WhenCalled(() => _transaction.IsActive).WillReturn(true);

            _mock = MockManager.Mock <TransactionAttribute>();
            _mock.CallBase.ExpectCall("OnActionExecuted");

            _attr = new TransactionAttribute();
            Isolate.NonPublic.Property.WhenGetCalled(_attr, "Session").WillReturn(_session);

            _loginController = ObjectFactory.GetInstance <LoginController>();
            _homeController  = ObjectFactory.GetInstance <HomeController>();
        }
Exemplo n.º 9
0
 internal static void CheckProxy(Assembly addIn)
 {
     foreach (var type in addIn.GetTypes())
     {
         if (typeof(DoverFormBase).IsAssignableFrom(type))
         {
             CheckFormType(type);
         }
         var interceptors = type.GetCustomAttributes(true);
         foreach (var obj in interceptors)
         {
             TransactionAttribute interceptor = obj as TransactionAttribute;
             if (interceptor != null)
             {
                 CheckTransactionType(type);
             }
         }
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// 执行事务
        /// </summary>
        /// <param name="action">动作回调</param>
        /// <param name="accessMode">访问模式</param>
        /// <param name="transAttr">事务特性</param>
        /// <param name="connectionId">连接ID</param>
        protected void ExecTransaction(Action <string> action, AccessMode accessMode = AccessMode.MASTER, TransactionAttribute transAttr = null, string connectionId = null)
        {
            if (string.IsNullOrWhiteSpace(connectionId) || GetDbTransaction(connectionId, accessMode) == null)
            {
                IDbTransaction dbTransaction = null;
                try
                {
                    if (string.IsNullOrWhiteSpace(connectionId))
                    {
                        connectionId = NewConnectionId(accessMode);
                    }
                    if (transAttr == null)
                    {
                        transAttr = new TransactionAttribute()
                        {
                            Level = IsolationLevel.ReadCommitted
                        };
                    }
                    dbTransaction = BeginTransaction(connectionId, transAttr);

                    action(connectionId);

                    dbTransaction.Commit();
                }
                catch (Exception ex)
                {
                    if (dbTransaction != null)
                    {
                        dbTransaction.Rollback();
                    }
                    throw new Exception(ex.Message, ex);
                }
                finally
                {
                    Release(connectionId);
                }
            }
            else
            {
                action(connectionId);
            }
        }
Exemplo n.º 11
0
        public void TestMakeTransaction()
        {
            txManager = new TransactionManager(rpcClientMock.Object, sender);

            var attributes = new TransactionAttribute[1]
            {
                new Cosigner
                {
                    Account = sender,
                    Scopes  = WitnessScope.Global
                }
            };

            byte[] script = new byte[1];
            txManager.MakeTransaction(script, attributes);

            var tx = txManager.Tx;

            Assert.AreEqual(WitnessScope.Global, (tx.Attributes[0] as Cosigner).Scopes);
        }
Exemplo n.º 12
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            MethodInfo methodInfo = input.Target.GetType().GetMethods().ToList()
                                    .FirstOrDefault(m => m.Name == input.MethodBase.Name);
            TransactionAttribute transactionAttribute =
                methodInfo != null?methodInfo.GetCustomAttribute <TransactionAttribute>() : null;


            if (transactionAttribute == null)
            {
                return(run(input, getNext));
            }
            else
            {
                using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required))
                {
                    return(run(input, getNext, transaction));
                }
            }
        }
Exemplo n.º 13
0
        public void TestMakeTransaction()
        {
            txManager = new TransactionManager(rpcClientMock.Object, sender);

            TransactionAttribute[] attributes = new TransactionAttribute[1]
            {
                new TransactionAttribute
                {
                    Usage = TransactionAttributeUsage.Url,
                    Data  = "53616d706c6555726c".HexToBytes() // "SampleUrl"
                }
            };

            byte[] script = new byte[1];
            txManager.MakeTransaction(script, attributes, null);

            var tx = txManager.Tx;

            Assert.AreEqual("53616d706c6555726c", tx.Attributes[0].Data.ToHexString());
        }
Exemplo n.º 14
0
    public void IsolationExample()
    {
        // Get the TransactionAttribute applied to the class.
        TransactionAttribute attribute =
            (TransactionAttribute)Attribute.GetCustomAttribute(
                this.GetType(),
                typeof(TransactionAttribute),
                false);

        // Display the current value of the attribute's Isolation property.
        Console.WriteLine("TransactionAttribute.Isolation: {0}",
                          attribute.Isolation);

        // Set the Isolation property value of the attribute.
        attribute.Isolation = TransactionIsolationLevel.RepeatableRead;

        // Display the new value of the attribute's Isolation property.
        Console.WriteLine("TransactionAttribute.Isolation: {0}",
                          attribute.Isolation);
    }
Exemplo n.º 15
0
        protected override void DoSetUp()
        {
            this.transactionManagerMock = Mockery.Create <ITransactionManager>();
            this.transactionAttribute   = new TransactionAttribute
            {
                TransactionManager = this.transactionManagerMock.Object
            };

            this.fakeController = new FakeController
            {
                ViewData = new ViewDataDictionary(new Model {
                    Required = "y"
                })
            };

            this.filterContext = Mockery.Create <ActionExecutedContext>();
            this.filterContext.SetupGet(c => c.Controller).Returns(this.fakeController);
            // most tests require top-level action
            this.filterContext.SetupGet(c => c.IsChildAction).Returns(false);
        }
    public void TimeoutExample()
    {
        // Get the TransactionAttribute applied to the class.
        TransactionAttribute attribute =
            (TransactionAttribute)Attribute.GetCustomAttribute(
                this.GetType(),
                typeof(TransactionAttribute),
                false);

        // Display the current value of the attribute's Timeout property.
        Console.WriteLine("TransactionAttribute.Timeout: {0}",
                          attribute.Timeout);

        // Set the Timeout property value of the attribute to sixty
        // seconds.
        attribute.Timeout = 60;

        // Display the new value of the attribute's Timeout property.
        Console.WriteLine("TransactionAttribute.Timeout: {0}",
                          attribute.Timeout);
    }
Exemplo n.º 17
0
        public void TestMakeTransaction()
        {
            txManager = new TransactionManager(rpcClientMock.Object, sender);

            TransactionAttribute[] attributes = new TransactionAttribute[1]
            {
                new TransactionAttribute
                {
                    Usage = TransactionAttributeUsage.Url,
                    Data  = "53616d706c6555726c".HexToBytes() // "SampleUrl"
                }
            };

            byte[] script = new byte[1];
            txManager.MakeTransaction(script, attributes, null, 60000);

            var tx = txManager.Tx;

            Assert.AreEqual("53616d706c6555726c", tx.Attributes[0].Data.ToHexString());
            Assert.AreEqual(0, tx.SystemFee % (long)NativeContract.GAS.Factor);
            Assert.AreEqual(60000, tx.NetworkFee);
        }
Exemplo n.º 18
0
        public void TestTransactionRollback()
        {
            var transactionManagerMock = new Mock <ITransactionManager>();
            var aspectContextMock      = new Mock <AspectContext>();
            var mockDelegateMock       = new Mock <AspectDelegate>();
            var dbProviderMock         = new Mock <IDbProvider>();
            var factoryMock            = new Mock <ITransactionFactory>();
            var dbOptionMock           = new Mock <DbOption>();
            var transactionMock        = new Mock <ITransaction>();
            var dbTransactionMock      = new Mock <IDbTransaction>();
            var manager  = new TransactionManager();
            var services = Mock.Of <IServiceProvider>(sp =>
                                                      sp.GetService(typeof(ITransactionManager)) == manager &&
                                                      sp.GetService(typeof(DbOption)) == dbOptionMock.Object &&
                                                      sp.GetService(typeof(ITransactionFactory)) == factoryMock.Object
                                                      );

            factoryMock.SetupSequence(t => t.GetTransaction())
            .Returns(transactionMock.Object)
            .Returns(transactionMock.Object)
            .Returns(transactionMock.Object);
            aspectContextMock.Setup(t => t.ServiceProvider).Returns(services);
            var tt = new TransactionAttribute
            {
                IsDisable = false
            };

            tt.Invoke(aspectContextMock.Object, mockDelegateMock.Object);
            var tt1 = new TransactionAttribute
            {
                IsDisable = false
            };

            Assert.ThrowsExceptionAsync <Exception>(() =>
            {
                return(tt1.Invoke(aspectContextMock.Object, t => { throw new Exception(); }));
            });
            transactionMock.Verify(t => t.RollbackAsync());
        }
Exemplo n.º 19
0
        /// <summary>
        /// Checks for and starts automatic transaction
        /// </summary>
        /// <param name="type"></param>
        /// <param name="doc"></param>
        /// <returns></returns>
        private Transaction StartAutomaticTransaction(Type type, Document doc)
        {
            //check for transactionmode attribute, if automatic, start one
            Attribute[] attrs = Attribute.GetCustomAttributes(type);

            Transaction transaction = null;

            //start transaction
            foreach (Attribute attr in attrs)
            {
                if (attr is TransactionAttribute)
                {
                    TransactionAttribute transAt = (TransactionAttribute)attr;
                    if (transAt.Mode == TransactionMode.Automatic)
                    {
                        //needs automatic transaction mode.
                        transaction = new Transaction(doc);
                        transaction.Start("Remote Runner");
                    }
                }
            }
            return(transaction);
        }
Exemplo n.º 20
0
        public void TestTransactionCommit()
        {
            var transactionManagerMock = new Mock <ITransactionManager>();
            var aspectContextMock      = new Mock <AspectContext>();
            var mockDelegateMock       = new Mock <AspectDelegate>();
            var dbProviderMock         = new Mock <IDbProvider>();
            var factoryMock            = new Mock <ITransactionFactory>();
            var dbOptionMock           = new Mock <DbOption>();
            var transactionMock        = new Mock <ITransaction>();
            var dbTransactionMock      = new Mock <DbTransaction>();
            var manager  = new TransactionManager();
            var services = Mock.Of <IServiceProvider>(sp =>
                                                      sp.GetService(typeof(ITransactionManager)) == manager &&
                                                      sp.GetService(typeof(DbOption)) == dbOptionMock.Object &&
                                                      sp.GetService(typeof(ITransactionFactory)) == factoryMock.Object
                                                      );

            factoryMock.SetupSequence(t => t.GetTransaction())
            .Returns(transactionMock.Object)
            .Returns(transactionMock.Object)
            .Returns(transactionMock.Object);
            aspectContextMock.Setup(t => t.ServiceProvider).Returns(services);
            var tt = new TransactionAttribute
            {
                IsDisable = false
            };

            tt.Invoke(aspectContextMock.Object, mockDelegateMock.Object);
            transactionMock.Verify(t => t.CommitAsync());
            var tt1 = new TransactionAttribute
            {
                IsDisable = false
            };

            tt1.Invoke(aspectContextMock.Object, mockDelegateMock.Object);
            transactionMock.Verify(t => t.CommitAsync(), Times.AtLeast(2));
        }
Exemplo n.º 21
0
        public void TestSign()
        {
            txManager = new TransactionManager(rpcClientMock.Object, sender);

            var attributes = new TransactionAttribute[1]
            {
                new Cosigner
                {
                    Account = sender,
                    Scopes  = WitnessScope.Global
                }
            };

            byte[] script = new byte[1];
            txManager.MakeTransaction(script, attributes)
            .AddSignature(keyPair1)
            .Sign();

            // get signature from Witnesses
            var tx = txManager.Tx;

            byte[] signature = tx.Witnesses[0].InvocationScript.Skip(2).ToArray();

            Assert.IsTrue(Crypto.VerifySignature(tx.GetHashData(), signature, keyPair1.PublicKey));
            // verify network fee and system fee
            long networkFee = tx.Size * (long)1000 + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + ApplicationEngine.ECDsaVerifyPrice * 1;

            Assert.AreEqual(networkFee, tx.NetworkFee);
            Assert.AreEqual(100, tx.SystemFee);

            // duplicate sign should not add new witness
            txManager.AddSignature(keyPair1).Sign();
            Assert.AreEqual(1, txManager.Tx.Witnesses.Length);

            // throw exception when the KeyPair is wrong
            Assert.ThrowsException <Exception>(() => txManager.AddSignature(keyPair2).Sign());
        }
Exemplo n.º 22
0
        public async Task TestTransactionDisableFalse()
        {
            var transactionManagerMock = new Mock <ITransactionManager>();
            var aspectContextMock      = new Mock <AspectContext>();
            var mockDelegateMock       = new Mock <AspectDelegate>();
            var dbProviderMock         = new Mock <IDbProvider>();
            var factoryMock            = new Mock <ITransactionFactory>();
            var dbOptionMock           = new Mock <DbOption>();
            var transactionMock        = new Mock <ITransaction>();
            var connectFactoryMock     = new Mock <IConnectFactory>();
            var IdbConnectMock         = new Mock <DbConnection>();
            var IdbTransactionMock     = new Mock <DbTransaction>();
            var services = Mock.Of <IServiceProvider>(sp =>

                                                      sp.GetService(typeof(ITransactionManager)) == transactionManagerMock.Object &&
                                                      sp.GetService(typeof(DbOption)) == dbOptionMock.Object &&
                                                      sp.GetService(typeof(ITransactionFactory)) == factoryMock.Object
                                                      );

            connectFactoryMock.Setup(t => t.CreateAndOpenConnectionAsync()).ReturnsAsync(IdbConnectMock.Object);

            aspectContextMock.Setup(t => t.ServiceProvider).Returns(services);
            factoryMock.SetupSequence(t => t.GetTransaction())
            .Returns(new ORM.Database.Transaction(connectFactoryMock.Object))
            .Returns(new InnerTransaction())
            .Returns(new InnerTransaction());

            var tt = new TransactionAttribute
            {
                IsDisable = false
            };
            await tt.Invoke(aspectContextMock.Object, mockDelegateMock.Object);

            transactionManagerMock.Verify(t => t.AddTransaction(It.IsAny <ORM.Database.Transaction>()));
            transactionManagerMock.Verify(t => t.RemoveTransaction(It.IsAny <ITransaction>()));
        }
        protected override void DoSetUp()
        {
            this.transactionManagerMock = Mockery.Create<ITransactionManager>();
            this.transactionAttribute = new TransactionAttribute
            {
                TransactionManager = this.transactionManagerMock.Object
            };

            this.fakeController = new FakeController
            {
                ViewData = new ViewDataDictionary(new Model {Required = "y"})
            };

            this.filterContext = Mockery.Create<ActionExecutedContext>();
            this.filterContext.SetupGet(c => c.Controller).Returns(this.fakeController);
            // most tests require top-level action
            this.filterContext.SetupGet(c => c.IsChildAction).Returns(false);
        }
Exemplo n.º 24
0
 private string BuildCaption(string formato,TransactionAttribute ta, string defaultv)
 {
     return String.Format(formato, defaultv, ta.Attribute.ContextualTitleProperty, ta.Name);
 }
Exemplo n.º 25
0
 /// <summary>
 /// 创建
 /// </summary>
 /// <param name="connection">数据库连接</param>
 /// <param name="transAttr">事务特性</param>
 /// <returns>数据库事务</returns>
 public IDbTransaction Begin(IDbConnection connection, TransactionAttribute transAttr)
 {
     return(connection.BeginTransaction(transAttr.Level));
 }
Exemplo n.º 26
0
        private void button5_Click(object sender, EventArgs e)
        {
            byte[] script;
            try
            {
                script = textBox6.Text.Trim().HexToBytes();
            }
            catch (FormatException ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            if (tx == null)
            {
                tx = new InvocationTransaction();
            }
            tx.Version = 1;
            tx.Script  = script;
            // add an attribute to make each itx different
            TransactionAttribute attr = new TransactionAttribute()
            {
                Usage = TransactionAttributeUsage.Description,
                Data  = ((BigInteger)DateTime.Now.ToTimestamp()).ToByteArray()
            };
            // add an attribute for signature
            UInt160 defaultAddr        = Program.CurrentWallet.GetChangeAddress();
            TransactionAttribute attr2 = new TransactionAttribute()
            {
                Usage = TransactionAttributeUsage.Script,
                Data  = defaultAddr.ToArray()
            };

            if (tx.Attributes == null)
            {
                tx.Attributes = new TransactionAttribute[0];
            }
            var attrList = tx.Attributes.ToList();

            attrList.Add(attr);
            attrList.Add(attr2);
            tx.Attributes = attrList.ToArray();
            if (tx.Inputs == null)
            {
                tx.Inputs = new CoinReference[0];
            }
            if (tx.Outputs == null)
            {
                tx.Outputs = new TransactionOutput[0];
            }
            if (tx.Witnesses == null)
            {
                tx.Witnesses = new Witness[0];
            }
            ApplicationEngine engine = ApplicationEngine.Run(tx.Script, tx, testMode: true);
            StringBuilder     sb     = new StringBuilder();

            sb.AppendLine($"VM State: {engine.State}");
            sb.AppendLine($"Gas Consumed: {engine.GasConsumed}");
            sb.AppendLine($"Evaluation Stack: {new JArray(engine.ResultStack.Select(p => p.ToParameter().ToJson()))}");
            textBox7.Text = sb.ToString();
            if (!engine.State.HasFlag(VMState.FAULT))
            {
                tx.Gas = engine.GasConsumed - Fixed8.FromDecimal(10);
                if (tx.Gas < Fixed8.Zero)
                {
                    tx.Gas = Fixed8.Zero;
                }
                tx.Gas = tx.Gas.Ceiling();
                //tx.Gas += Fixed8.Satoshi;
                Fixed8 fee = tx.Gas;
                label7.Text     = fee + " gas";
                button3.Enabled = true;
            }
            else
            {
                MessageBox.Show(Strings.ExecutionFailed);
            }
        }
Exemplo n.º 27
0
        private string BuildIsValid(Transaction trn,TransactionAttribute ta)
        {
            // Temos atributos para Carregar
            bool carrega = TemAttributoInferido(trn, ta);

            StringBuilder saida = new StringBuilder();
            if (carrega) {

                saida.AppendLine("for each");

                // filtros
                foreach (AttributeRelation ar in ta.ForeignKeyTo.KeyAttributes)
                {
                    saida.AppendLine("   where " + ar.Related.Name + " = &" + trn.Name + "SDT." + ar.Base.Name);
                }

                // Preenche atributos inferidos
                foreach (TransactionAttribute a in trn.Structure.Root.Attributes)
                {
                    if (a.IsInferred)
                    {
                        foreach (AttributeRelation ar in ta.ForeignKeyTo.InferredAttributes)
                        {
                            if (a.Attribute == ar.Base)
                            {
                                saida.AppendLine("      &" + trn.Name + "SDT." + ar.Base.Name + " = " + ar.Related.Name);
                            }
                        }
                    }
                }

                // Se não encontrar
                saida.AppendLine("   when none");

                // Limpa os atributos inferidos
                foreach (TransactionAttribute a in trn.Structure.Root.Attributes)
                {
                    if (a.IsInferred)
                    {
                        if (ta.ForeignKeyTo.ContainsInferredAttribute(a.Attribute))
                        {
                            saida.AppendLine("      &" + trn.Name + "SDT." + a.Name + " = nullvalue(&" + trn.Name + "SDT." + a.Name + ")");
                        }
                    }
                }

                // Volta o foco para o campo chamador
                saida.AppendLine("      ctl" + ta.Name + ".SetFocus()");

                // Se tem mensagem mostra
                if (settings.Template.SuggestMessageNotFoundForeignKey != String.Empty)
                {
                    saida.AppendLine("      msg('" + String.Format(settings.Template.SuggestMessageNotFoundForeignKey, ta.ForeignKeyTo.RelatedTransaction.Description) + "')");
                }

                saida.Append("endfor");
            }

            return saida.ToString();
        }
Exemplo n.º 28
0
        public static SignedTransaction Unserialize(BinaryReader reader)
        {
            var tx = new SignedTransaction
            {
                Type    = (TransactionType)reader.ReadByte(),
                Version = reader.ReadByte()
            };


            switch (tx.Type)
            {
            case TransactionType.InvocationTransaction:
            {
                //todo
                break;
            }

            case TransactionType.MinerTransaction:
            {
                //todo
                break;
            }

            case TransactionType.ClaimTransaction:
            {
                var len = (int)reader.ReadVarInt(0x10000000);
                tx.References = new SignedTransaction.Input[len];
                for (var i = 0; i < len; i++)
                {
                    tx.References[i] = UnserializeTransactionInput(reader);
                }

                break;
            }

            case TransactionType.ContractTransaction:
            {
                break;
            }

            case TransactionType.PublishTransaction:
            {
                //todo
                break;
            }

            case TransactionType.EnrollmentTransaction:
            {
                //todo
                break;
            }

            case TransactionType.RegisterTransaction:
            {
                //todo
                break;
            }

            case TransactionType.IssueTransaction:
            {
                break;
            }

            case TransactionType.StateTransaction:
                break;

            default:
            {
                throw new NotImplementedException();
            }
            }

            var attrCount = (int)reader.ReadVarInt(16);

            if (attrCount != 0)
            {
                tx.Attributes = new TransactionAttribute[attrCount];
                for (var i = 0; i < attrCount; i++)
                {
                    tx.Attributes[i] = TransactionAttribute.Unserialize(reader);
                }
            }

            var inputCount = (int)reader.ReadVarInt();

            tx.Inputs = new SignedTransaction.Input[inputCount];
            for (var i = 0; i < inputCount; i++)
            {
                tx.Inputs[i] = UnserializeTransactionInput(reader);
            }

            var outputCount = (int)reader.ReadVarInt();

            tx.Outputs = new SignedTransaction.Output[outputCount];
            for (var i = 0; i < outputCount; i++)
            {
                tx.Outputs[i] = UnserializeTransactionOutput(reader);
            }

            var witnessCount = (int)reader.ReadVarInt();

            tx.Witnesses = new Witness[witnessCount];
            for (var i = 0; i < witnessCount; i++)
            {
                tx.Witnesses[i] = Witness.Unserialize(reader);
            }

            return(tx);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Intercepts the specified invocation and creates a transaction
        /// if necessary.
        /// </summary>
        /// <param name="invocation">The invocation.</param>
        /// <returns></returns>
        public void Intercept(IInvocation invocation)
        {
            MethodInfo methodInfo;

            if (invocation.Method.DeclaringType.IsInterface)
            {
                methodInfo = invocation.MethodInvocationTarget;
            }
            else
            {
                methodInfo = invocation.Method;
            }

            if (metaInfo == null || !metaInfo.Contains(methodInfo))
            {
                invocation.Proceed();
                return;
            }
            else
            {
                TransactionAttribute transactionAtt = metaInfo.GetTransactionAttributeFor(methodInfo);

                ITransactionManager manager = kernel.Resolve <ITransactionManager>();

                ITransaction transaction = manager.CreateTransaction(
                    transactionAtt.TransactionMode, transactionAtt.IsolationMode, transactionAtt.Distributed);

                if (transaction == null)
                {
                    invocation.Proceed();
                    return;
                }

                transaction.Begin();

                bool rolledback = false;

                try
                {
                    if (metaInfo.ShouldInject(methodInfo))
                    {
                        var parameters = methodInfo.GetParameters();

                        for (int i = 0; i < parameters.Length; i++)
                        {
                            if (parameters[i].ParameterType == typeof(ITransaction))
                            {
                                invocation.SetArgumentValue(i, transaction);
                            }
                        }
                    }
                    invocation.Proceed();

                    if (transaction.IsRollbackOnlySet)
                    {
                        logger.DebugFormat("Rolling back transaction {0}", transaction.GetHashCode());

                        rolledback = true;
                        transaction.Rollback();
                    }
                    else
                    {
                        logger.DebugFormat("Committing transaction {0}", transaction.GetHashCode());

                        transaction.Commit();
                    }
                }
                catch (TransactionException ex)
                {
                    // Whoops. Special case, let's throw without
                    // attempt to rollback anything

                    if (logger.IsFatalEnabled)
                    {
                        logger.Fatal("Fatal error during transaction processing", ex);
                    }

                    throw;
                }
                catch (Exception)
                {
                    if (!rolledback)
                    {
                        if (logger.IsDebugEnabled)
                        {
                            logger.DebugFormat("Rolling back transaction {0} due to exception on method {2}.{1}", transaction.GetHashCode(), methodInfo.Name, methodInfo.DeclaringType.Name);
                        }

                        transaction.Rollback();
                    }

                    throw;
                }
                finally
                {
                    manager.Dispose(transaction);
                }
            }
        }
Exemplo n.º 30
0
 private void AddTransactionAttribute(AttributesElement attributesElement, TransactionAttribute att, string description, bool visible, bool forbidAutolink)
 {
     AttributeElement attElement = attributesElement.AddAttribute(att.Attribute);
     attElement.Description = description;
     attElement.Visible = visible;
     attElement.Autolink = (!forbidAutolink);
 }
Exemplo n.º 31
0
 private void Act()
 {
     TransactionAttribute.OnActionExecuted(this.filterContext);
 }
Exemplo n.º 32
0
 private bool TemAttributoInferido(Transaction trn, TransactionAttribute ta)
 {
     foreach (TransactionAttribute a in trn.Structure.Root.Attributes)
     {
         if (a.IsInferred)
         {
             if (ta.ForeignKeyTo.ContainsRelatedAttribute(a.Attribute))
             {
                 return true;
             }
             else
             {
                 if (a.Attribute.SuperType != null)
                 {
                     if (ta.ForeignKeyTo.ContainsRelatedAttribute(a.Attribute.SuperType))
                     {
                         return true;
                     }
                 }
             }
         }
     }
     return false;
 }
Exemplo n.º 33
0
 private void AddDescriptionAttribute(LevelElement levelElement, TransactionAttribute da)
 {
     if (da != null)
     {
         DescriptionAttributeElement daElement = new DescriptionAttributeElement();
         daElement.Attribute = da.Attribute;
         daElement.Description = da.Attribute.ContextualTitleProperty;
         levelElement.DescriptionAttribute = daElement;
     }
 }
Exemplo n.º 34
0
 private void AddOrderAttribute(OrderElement orderElement, TransactionAttribute att, string attDescription, bool ascending)
 {
     OrderAttributeElement orderAttElement = orderElement.AddOrderAttribute();
     orderAttElement.Attribute = att.Attribute;
     orderAttElement.Description = attDescription;
     orderAttElement.Ascending = ascending;
 }
Exemplo n.º 35
0
 private static void AddBasedOnVariable(Transaction transaction, string name, TransactionAttribute baseAttribute)
 {
     Variable var = AddVariable(transaction, name);
     if (var != null)
         var.AttributeBasedOn = baseAttribute;
 }
Exemplo n.º 36
0
 private string BuildCaption(TransactionAttribute ta,string defaultv)
 {
     return BuildCaption(settings.Labels.AttributeCaption, ta,defaultv);
 }
Exemplo n.º 37
0
        public TransactionAttribute Unwrap()
        {
            MemoryReader reader = new(Data);

            return(TransactionAttribute.DeserializeFrom(ref reader));
        }
Exemplo n.º 38
0
 public void TestSetup()
 {
     uut = new TransactionAttribute();
 }
Exemplo n.º 39
0
        private static string OneAttribute(TransactionAttribute att, Dictionary<string, int> Counters, System.Boolean getButton, IDictionary<TransactionAttribute, Artech.Genexus.Common.Objects.Attribute> descAttNames)
        {
            StringBuilder ret = new StringBuilder();
            Artech.Genexus.Common.Objects.Attribute attName;
            if (!descAttNames.TryGetValue(att, out attName))
                attName = att.Attribute;

            string captionProperty = "Title";
            if (att.IsLocal)
                captionProperty = "ContextualTitle";

            //System.Collections.Generic.Dictionary<String,Object> cp = new System.Collections.Generic.Dictionary<String,Object>();

            // Don't show the get button.
            getButton = false;
            ret.AppendLine("<tr>");
                ret.AppendLine("<td class=\"td5\" valign=\"top\" nowrap=\"nowrap\">");
                    ret.AppendLine(WebForm.TextBlock("TextBlock" + att.Name, null, String.Format("={0}.{1}", attName.Name, captionProperty)));
                ret.AppendLine("</td>");
                ret.AppendLine("<td nowrap=\"nowrap\">");

                if (getButton)
                {

                    ret.AppendLine(WebForm.BeginTable("Table"+att.Name,null));
                        ret.AppendLine("<tr>");
                            ret.AppendLine("<td>");

                }

                                ret.AppendLine(WebForm.Attribute(att.Name));

                if (getButton)
                {
                            ret.AppendLine("</td>");
                            ret.AppendLine("<td>");
                                ret.AppendLine(Button("btn_get","GX_BtnGet","BtnGet","Get",""));
                            ret.AppendLine("</td>");
                        ret.AppendLine("</tr>");
                    ret.AppendLine(WebForm.EndTable());

                }
                ret.AppendLine("</td>");
            ret.AppendLine("</tr>");
            return ret.ToString();
        }
		///<summary>
		/// Adds a method info and the corresponding transaction attribute.
		///</summary>
		public void Add(MethodInfo method, TransactionAttribute attribute)
		{
			method2Att[method] = attribute;
		}
Exemplo n.º 41
0
        private void BuildPrompt(HPatternInstance instance, AttributeElement ae,TransactionAttribute ta,Transaction trn)
        {
            List<string> listapk = new List<string>();
            foreach (AttributeRelation ar in ta.ForeignKeyTo.KeyAttributes)
            {
                listapk.Add(ar.Related.Name);
            }

            IEnumerable<WebPanel> listaw = WebPanel.GetAll(instance.Model);
            bool geralink = false;
            foreach (WebPanel wobj in listaw)
            {
                // Se este objeto foi gerado pelo Pattern
                if (String.IsNullOrEmpty(settings.Template.PromptSuggestNameContains) || wobj.Name.ToLower().IndexOf(settings.Template.PromptSuggestNameContains.ToLower()) >= 0)
                {
                    // Aqui vamos retirar a o loop infinito, então nunca ira sugerir um prompt dele mesmo
                    bool gera = true;
                    if (wobj.Parent is PatternInstance)
                    {
                        if (((PatternInstance)wobj.Parent).KBObjectKey.Equals(pinstance.KBObjectKey))
                            gera = false;
                    }
                    if (gera)
                    {
                        foreach (Signature sig in wobj.GetSignatures())
                        {
                            if (sig.ParametersCount > 0)
                            {
                                foreach (AttributeRelation ar in ta.ForeignKeyTo.KeyAttributes)
                                {
                                    geralink = false;
                                    foreach (Parameter par in sig.Parameters)
                                    {
                                        if (par.Object.Name.ToLower().IndexOf(ar.Related.Name.ToLower()) >= 0)
                                        {
                                            geralink = true;
                                        }
                                    }
                                    if (!geralink)
                                        break;
                                }
                                if (geralink)
                                {
                                    LinkElement link = new LinkElement();
                                    ae.Links.Add(link);
                                    link = new LinkElement();
                                    link.WebpanelObject = wobj;
                                    link.Tooltip = wobj.Description;

                                    foreach (AttributeRelation ar in ta.ForeignKeyTo.KeyAttributes)
                                    {
                                        link.Parameters.Add(new ParameterElement(ar.Base.Name));
                                    }
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
                if (geralink)
                {
                    break;
                }
            }
        }
Exemplo n.º 42
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // those you need to set up------------------------------------------------------------

            rpcClient = new RpcClient("http://localhost:20002");                              // your node url, such as "http://47.89.240.111:12332"
            nep2Key   = "6PYLjXkQzADs7r36XQjByJXoggm3beRh6UzxuN59NZiBxFBnm1HPvv3ytM";         // you can find this in your wallet, the "key" field
            string password = "******";                                                            // your password

            UInt160 from       = "AQzRMe3zyGS8W177xLJfewRRQZY2kddMun".ToScriptHash();         // your account address, such as "APPmjituYcgfNxjuQDy9vP73R2PmhFsYJR"
            UInt160 scriptHash = UInt160.Parse("0x6b4f6926c28523519c758ec2015a60ddfe8b37dc"); // your contract script hash, such as "0x5be5fc0641e44b0003262b3fda775ea60133cb05"
            //byte[] param = new byte[] { }; // your contract parameter
            BigInteger param = 2;

            //-------------------------------------------------------------------------------------------

            ScriptBuilder sb = new ScriptBuilder().EmitAppCall(scriptHash, "getProxyHash", new ContractParameter[] { new ContractParameter()
                                                                                                                     {
                                                                                                                         Type = ContractParameterType.Integer, Value = param
                                                                                                                     } });
            var script = sb.ToArray();

            InvocationTransaction itx = new InvocationTransaction();

            itx.Inputs     = new CoinReference[] { };
            itx.Outputs    = new TransactionOutput[] { };
            itx.Attributes = new TransactionAttribute[] { };
            itx.Witnesses  = new Witness[] { };
            itx.Version    = 1;
            itx.Script     = script;
            itx.Gas        = GetGasConsumed(script);

            Fixed8 fee = itx.Gas;

            if (itx.Size > 1024)
            {
                fee += Fixed8.FromDecimal(0.001m);
                fee += Fixed8.FromDecimal(itx.Size * 0.00001m);
            }

            var(inputs, sum) = GetTransactionInputs(from, Blockchain.UtilityToken.Hash, fee);
            if (sum > fee)
            {
                itx.Outputs = itx.Outputs.Concat(new[] { new TransactionOutput()
                                                         {
                                                             AssetId = Blockchain.UtilityToken.Hash, Value = sum - fee, ScriptHash = from
                                                         } }).ToArray();
            }
            itx.Inputs = itx.Inputs.Concat(inputs).ToArray();

            // sign the itx
            Random random = new Random();
            var    nonce  = new byte[32];

            random.NextBytes(nonce);
            TransactionAttribute[] attributes = new TransactionAttribute[]
            {
                new TransactionAttribute()
                {
                    Usage = TransactionAttributeUsage.Script, Data = from.ToArray()
                },
                new TransactionAttribute()
                {
                    Usage = TransactionAttributeUsage.Remark1, Data = nonce
                }                                                                                      // if a transaction has no inputs and outputs, need to add nonce for duplication
            };
            itx.Attributes = itx.Attributes.Concat(attributes).ToArray();

            KeyPair keyPair = WalletHelper.KeyPairFromNep2(nep2Key, password);
            Witness witness = WalletHelper.CreateTransactionWitness(itx, keyPair);

            itx.Witnesses = itx.Witnesses.Concat(new[] { witness }).ToArray();

            var raw  = itx.ToArray();
            var txid = rpcClient.SendRawTransaction(raw);

            Console.WriteLine(txid.ToString());
        }
 ///<summary>
 /// Adds a method info and the corresponding transaction attribute.
 ///</summary>
 public void Add(MethodInfo method, TransactionAttribute attribute)
 {
     method2Att[method] = attribute;
 }