Exemplo n.º 1
0
        /// <summary>
        /// Finds addresses with balance and finds reminder and creates transaction items
        /// </summary>
        /// <param name="transferItem"></param>
        /// <param name="seed"></param>
        /// <param name="startFromIndex"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <TransactionItem[]> CreateTransactions(TransferItem transferItem, string seed, int startFromIndex, CancellationToken cancellationToken)
        {
            var withdrawalAmount = transferItem.Value;
            var addressItems     = await FindAddressesWithBalance(seed, startFromIndex, withdrawalAmount, cancellationToken);

            return(await CreateTransactions(transferItem, seed, addressItems, cancellationToken));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Ends a pending asynchronous read.
        /// </summary>
        /// <param name="asyncResult">Stores state information for this asynchronous operation as well as any user defined data.</param>
        /// <returns>The number of bytes received.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="asyncResult"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
        /// <exception cref="ArgumentException"><paramref name="asyncResult"/> was not returned by a call to the <see cref="BeginReceive"/> method.</exception>
        /// <exception cref="InvalidOperationException"><see cref="EndReceive"/> was previously called for the asynchronous read.</exception>
        /// <exception cref="SocketException">An operating system error occurs while accessing the socket.</exception>
        /// <exception cref="ObjectDisposedException">The <see cref="SecureSocket"/> has been closed.</exception>
        /// <exception cref="SecurityException">An error occurs while communicating with the remote host.</exception>
        public override int EndReceive(IAsyncResult asyncResult)
        {
            if (SecureProtocol == SecureProtocol.None)
            {
                return(base.EndReceive(asyncResult));
            }
            // Make sure everything is in order
            if (asyncResult == null)
            {
                throw new ArgumentNullException();
            }
            TransferItem ti = m_Controller.EndReceive(asyncResult);

            if (ti == null)
            {
                throw new ArgumentException();
            }
            // Process the (secure) EndReceive
            // block if the operation hasn't ended yet
            if (!ti.AsyncResult.IsCompleted)
            {
                ti.AsyncResult.AsyncWaitHandle.WaitOne();
            }
            if (ti.AsyncResult.AsyncException != null)
            {
                throw new SecurityException("An error occurs while communicating with the remote host.\r\n" + ti.AsyncResult.AsyncException.ToString(), ti.AsyncResult.AsyncException);
            }
            if (ti.Transferred == 0)
            {
                m_SentShutdownNotification = true;
            }
            return(ti.Transferred);
        }
Exemplo n.º 3
0
        public IEnumerable <TransferItem> ChildrenGetter(object p)
        {
            TransferItem directory = ((TransferItem)p);

            if (null == directory)
            {
                // Root
                if (!_cache.isValid(null))
                {
                    _cache.put(null, new AttributedList(Transfer.getRoots()));
                    Filter();
                }
            }
            else if (!_cache.isValid(directory))
            {
                _controller.Background(new TransferPromptListAction(this, _controller, _source, _destination, directory, Transfer,
                                                                    _cache));
            }
            // Return list with filtered files included
            AttributedList list = _cache.get(directory);

            for (int i = 0; i < list.size(); i++)
            {
                yield return((TransferItem)list.get(i));
            }
        }
        public void Transaction_WithPOW_ToTrytes_SerialisesCorrectly()
        {
            // Arrange
            var trunk    = "GFZIP9ZXJIJLUBYGTY9LGEDXVBLRCBEOEWYGZKHDLCCGXOVFPZM9MLQRMATDIICUFZRNXDNOBQIBA9999";
            var branch   = "NYXCW9DAGWKXQXUL9OUIIJYJFDOBLEB9LGTNWMCNADXPJVGECZ9SKVRTOXSNNXRHPP9QMCXSWRLU99999";
            var transfer = new TransferItem()
            {
                Address = "ASLIEIUJQHMVNHFQEXIDGGRRINZRHXZT9IWMZLRHWDYL9C9A9JSPBZUXJID9YERUQYRVALRVRLQZYSRXW", Message = "TESTMESSAGE", Tag = "MINEIOTADOTCOM", Value = 0
            };

            var trans = transfer.CreateTransactions();

            trans[0].SetAttachmentTime(new DateTime(2018, 01, 12, 0, 0, 0, DateTimeKind.Utc));
            trans[0].SetTimeStamp(new DateTime(2018, 01, 12, 0, 0, 0, DateTimeKind.Utc));
            var tranTrytes = trans.GetTrytes();

            // Act
            var trytesToSend = tranTrytes.DoPow(trunk, branch, 4, 1, CancellationToken.None).Result; // do the pow
            var tran         = new TransactionItem(trytesToSend[0]);

            // Assert
            Assert.AreEqual("ASLIEIUJQHMVNHFQEXIDGGRRINZRHXZT9IWMZLRHWDYL9C9A9JSPBZUXJID9YERUQYRVALRVRLQZYSRXW", tran.Address);
            Assert.AreEqual(0, tran.Value);

            Assert.AreEqual(151575840, tran.Timestamp, tran.Timestamp);
            Assert.AreEqual(1515758400000, tran.AttachmentTimestamp, tran.AttachmentTimestamp);
            Assert.AreEqual(0, tran.CurrentIndex);
            Assert.AreEqual(0, tran.LastIndex);
            Assert.AreEqual("GFZIP9ZXJIJLUBYGTY9LGEDXVBLRCBEOEWYGZKHDLCCGXOVFPZM9MLQRMATDIICUFZRNXDNOBQIBA9999", tran.TrunkTransaction);
            Assert.AreEqual("NYXCW9DAGWKXQXUL9OUIIJYJFDOBLEB9LGTNWMCNADXPJVGECZ9SKVRTOXSNNXRHPP9QMCXSWRLU99999", tran.BranchTransaction);
            Assert.AreEqual("MINEIOTADOTCOM9999999999999", tran.Tag);
        }
Exemplo n.º 5
0
 public bool prompt(TransferItem item, BackgroundException failure)
 {
     if (_supressed)
     {
         return(_option);
     }
     if (_controller.Visible)
     {
         AtomicBoolean c = new AtomicBoolean(true);
         _controller.Invoke(delegate
         {
             TaskDialogResult result = _controller.View.CommandBox(LocaleFactory.localizedString("Error"),
                                                                   failure.getMessage() ?? LocaleFactory.localizedString("Unknown"),
                                                                   failure.getDetail() ?? LocaleFactory.localizedString("Unknown"), null, null,
                                                                   LocaleFactory.localizedString("Always"),
                                                                   LocaleFactory.localizedString("Continue", "Credentials"), true, TaskDialogIcon.Warning,
                                                                   TaskDialogIcon.Information, delegate(int opt, bool verificationChecked)
             {
                 if (verificationChecked)
                 {
                     _supressed = true;
                     _option    = c.Value;
                 }
             });
             if (result.Result == TaskDialogSimpleResult.Cancel)
             {
                 c.SetValue(false);
             }
         }, true);
         return(c.Value);
     }
     // Abort
     return(false);
 }
        public void Transaction_CanSign_WithoutError()
        {
            // Arrange
            var seed     = "GFZIP9ZXJIJLUBYGTY9LGEDXVBLRCBEOEWYGZKHDLCCGXOVFPZM9MLQRMATDIICUFZRNXDNOBQIBA9999";
            var address1 = Utils.IotaUtils.GenerateAddress(seed, 0);
            var address2 = Utils.IotaUtils.GenerateAddress(seed, 1);
            var pKey     = Utils.Converter.ToTrytes(address1.PrivateKeyTrints);

            var signing       = new Utils.Signing(new Kerl());
            var key1          = signing.Key(Utils.Converter.ToTrits(seed), 0, 2);
            var address1again = Utils.IotaUtils.GenerateAddress(key1, false, CancellationToken.None);

            Assert.AreEqual(address1.Address, address1again);

            var trunk  = "GFZIP9ZXJIJLUBYGTY9LGEDXVBLRCBEOEWYGZKHDLCCGXOVFPZM9MLQRMATDIICUFZRNXDNOBQIBA9999";
            var branch = "NYXCW9DAGWKXQXUL9OUIIJYJFDOBLEB9LGTNWMCNADXPJVGECZ9SKVRTOXSNNXRHPP9QMCXSWRLU99999";

            var transfer = new TransferItem()
            {
                Address = address2.Address, Message = "TESTMESSAGE", Tag = "MINEIOTADOTCOM", Value = 1
            };

            // Act
            var trans = transfer.CreateTransactions(address1.Address, address1);

            // Assert Pass.
        }
Exemplo n.º 7
0
        public TransferItem[] GetTransferItems(string DocEntry)
        {
            Recordset recordset = null;

            TransferItem[] transferItems           = null;
            Dictionary <string, string> paramaters = new Dictionary <string, string>();

            try {
                paramaters.Add("DocEntry", DocEntry);
                string query = this.GetSQL("GetTransferItems").Inject(paramaters);
                recordset = (Recordset)DIApplication.Company.GetBusinessObject(BoObjectTypes.BoRecordset);
                recordset.DoQuery(query);

                if (recordset.RecordCount > 0)
                {
                    transferItems = new TransferItem[recordset.RecordCount];
                    for (int i = 0; i < recordset.RecordCount; i++)
                    {
                        var transferItem = new TransferItem();
                        Parallel.ForEach(recordset.Fields.OfType <Field>(), field => {
                            transferItem.GetType().GetProperty(field.Name).SetValue(transferItem, field.Value);
                        });
                        transferItems[i] = transferItem;
                        recordset.MoveNext();
                    }
                }
            }
            catch (Exception ex) {
                HandleException(ex, "GetTransferItems");
            }
            return(transferItems);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Sends transfer without renew balance
        /// </summary>
        /// <param name="transferItem">The transfer items to send</param>
        /// <param name="addressItems">The address items from which amount is send</param>
        /// <param name="remainderAddress">The remainder where remaind amount is send</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns></returns>
        public async Task <TransactionItem[]> AttachTransferWithoutRenewBalance(TransferItem transferItem, IEnumerable <AddressItem> addressItems, string remainderAddress, CancellationToken cancellationToken)
        {
            var transactionItems       = transferItem.CreateTransactions(remainderAddress, addressItems.ToArray());
            var resultTransactionItems = await AttachTransactions(transactionItems, cancellationToken);

            return(resultTransactionItems);
        }
        /// <summary>
        /// Begins an asynchronous write to a stream.
        /// </summary>
        /// <param name="buffer">The location in memory that holds the data to send.</param>
        /// <param name="offset">The location in buffer to begin sending the data.</param>
        /// <param name="size">The size of buffer.</param>
        /// <param name="callback">The delegate to call when the asynchronous call is complete.</param>
        /// <param name="state">An object containing additional information supplied by the client.</param>
        /// <returns>An <see cref="IAsyncResult"/> representing the asynchronous call.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
        /// <exception cref="ArgumentOutOfRangeException">The specified <paramref name="offset"/> or <paramref name="size"/> exceeds the size of <paramref name="buffer"/>.</exception>
        /// <exception cref="IOException">There is a failure while writing to the network.</exception>
        // Thanks go out to Martin Plante for notifying us about a bug in this method.
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException();
            }
            if (offset < 0 || offset > buffer.Length || size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException();
            }
            if (Socket == null)
            {
                throw new IOException();
            }
            if (WriteResult != null)
            {
                throw new IOException();
            }
            TransferItem localResult = new TransferItem(new byte[size], 0, size, new AsyncResult(callback, state, null), DataType.ApplicationData);

            WriteResult = localResult;
            Array.Copy(buffer, offset, localResult.Buffer, 0, size);
            try {
                Socket.BeginSend(localResult.Buffer, 0, size, SocketFlags.None, new AsyncCallback(OnBytesSent), (int)0);
                return(localResult.AsyncResult);
            } catch {
                throw new IOException();
            }
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Finding an IOTA node");
            INodeFinder nodeFinder  = new IotaDanceNodeFinder();
            var         nodes       = nodeFinder.FindNodes().Result;
            var         bestNodeUrl = nodes.ElementAt(1).Url;

            Console.WriteLine($"Creating transfer now. This may take a few seconds.");
            var transferItem = new TransferItem()
            {
                Address = "FAKEADDRESS9999999999999999999999999999999999999999999999999999999999999999999999", Message = "TESTMESSAGE"
            };
            var api = new IotaApi(bestNodeUrl);


            var apiResult = api.AttachTransfer(transferItem, CancellationToken.None).Result;

            if (apiResult.Successful)
            {
                var transactions = apiResult.Result;
                Console.WriteLine($"Your transaction hash is: {transactions[0].Hash}");
            }
            else
            {
                Console.WriteLine($"{apiResult.ErrorMessage} Exception: {apiResult.ExceptionInfo}");
            }

            Console.WriteLine($"Press any key to close");
            Console.ReadKey();
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Finding an IOTA node");
            INodeFinder nodeFinder = new IotaDanceNodeFinder();
            var         node       = nodeFinder.GetBestNode().Result;
            var         api        = new IotaApi(node);

            Console.WriteLine("Found node: " + node);

            Console.WriteLine($"Creating transfer now. This may take a few seconds.");
            var transferItem = new TransferItem()
            {
                Address = "FAKEADDRESS9999999999999999999999999999999999999999999999999999999999999999999999", Message = "PROMOTE9TEST"
            };
            var response = api.AttachTransfer(transferItem, CancellationToken.None).Result;

            if (response.Successful)
            {
                var transaction = response.Result;
                var hash        = transaction[0].Hash;
                Console.WriteLine($"Your transaction hash is: {hash}");

                Promote(api, hash);
            }
            else
            {
                Console.WriteLine($"Error Create Transaction: {response.ErrorMessage} Exception: {response.ExceptionInfo}");
            }

            Console.WriteLine($"All done.");
            Console.WriteLine($"Press any key to close");
            Console.ReadKey();
        }
        //table  details
        private void AddTransferItem(TransferItem det, Table atable)
        {
            Cell A = new Cell(new Phrase(det.EmpNo, tcFont));

            A.HorizontalAlignment = Cell.ALIGN_LEFT;
            atable.AddCell(A);

            Cell B = new Cell(new Phrase(det.EmpName, tcFont));

            B.HorizontalAlignment = Cell.ALIGN_LEFT;
            atable.AddCell(B);


            Cell D = new Cell(new Phrase(det.BranchName, tcFont));

            D.HorizontalAlignment = Cell.ALIGN_LEFT;
            atable.AddCell(D);

            Cell E = new Cell(new Phrase(det.AccountNo, tcFont));

            E.HorizontalAlignment = Cell.ALIGN_LEFT;
            atable.AddCell(E);

            Cell F = new Cell(new Phrase(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:N0}", det.Amount), tcFont));

            F.HorizontalAlignment = Cell.ALIGN_RIGHT;
            atable.AddCell(F);
        }
 public static bool IsEqualTo(this TransferItem i1, TransferItem i2)
 {
     return(i1.Id == i2.Id &&
            string.Compare(i1.Name, i2.Name) == 0 &&
            i1.Price == i2.Price &&
            i1.Discount == i2.Discount);
 }
Exemplo n.º 14
0
        /// <summary>
        /// Ends a pending asynchronous send.
        /// </summary>
        /// <param name="asyncResult">The result of the asynchronous operation.</param>
        /// <returns>If successful, the number of bytes sent to the SecureSocket.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="asyncResult"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
        /// <exception cref="ArgumentException"><paramref name="asyncResult"/> was not returned by a call to the <see cref="BeginSend"/> method.</exception>
        /// <exception cref="InvalidOperationException"><see cref="EndSend"/> was previously called for the asynchronous read.</exception>
        /// <exception cref="SocketException">An operating system error occurs while accessing the SecureSocket.</exception>
        /// <exception cref="ObjectDisposedException">The SecureSocket has been closed.</exception>
        /// <exception cref="SecurityException">An error occurs while communicating with the remote host.</exception>
        public override int EndSend(IAsyncResult asyncResult)
        {
            if (SecureProtocol == SecureProtocol.None)
            {
                return(base.EndSend(asyncResult));
            }
            if (asyncResult == null)
            {
                throw new ArgumentNullException();
            }
            TransferItem ti = m_Controller.EndSend(asyncResult);

            if (ti == null)
            {
                throw new ArgumentException();
            }
            if (!ti.AsyncResult.IsCompleted)
            {
                ti.AsyncResult.AsyncWaitHandle.WaitOne();
            }
            if (ti.AsyncResult.AsyncException != null)
            {
                throw new SecurityException("An error occurs while communicating with the remote host.", ti.AsyncResult.AsyncException);
            }
            return(ti.OriginalSize);
        }
        private void SetRootPaths()
        {
            List           items = _transfer.getRoots();
            IList <string> roots = new List <string>();

            for (int i = 0; i < items.size(); i++)
            {
                TransferItem item = (TransferItem)items.get(i);
                if (i == 0)
                {
                    if (items.size() > 1)
                    {
                        roots.Add(String.Format("{0} ({1} more)", item.remote.getName(), items.size() - 1));
                    }
                    else
                    {
                        roots.Add(item.remote.getName());
                    }
                }
                else
                {
                    roots.Add(item.remote.getName());
                }
            }
            View.PopulateRoots(roots);
        }
Exemplo n.º 16
0
 private bool View_ValidateOpenEvent()
 {
     return(ValidateToolbarItem(delegate(Transfer transfer)
     {
         if (transfer.getLocal() != null)
         {
             if (!transfer.isComplete())
             {
                 return false;
             }
             if (!transfer.isRunning())
             {
                 for (int i = 0; i < transfer.getRoots().size(); i++)
                 {
                     TransferItem item = (TransferItem)transfer.getRoots().get(i);
                     if (item.local.exists())
                     {
                         return true;
                     }
                 }
             }
         }
         return false;
     }));
 }
        public void Transaction_ToTrytes_SerialisesCorrectly()
        {
            // Arrange
            var expectedtrytes = "MTWLHBKJJLIRJVEWDPOWHPACMACNTIBTNPLKKTRJHKAA9UAKFH9XCZTDPHIPCXNZ9KQIZCMJXEFUACJXWOZVZHOFYWJMSOSHJYHEBXUIG9TBDMVKSYAUDQAXSDDFPKNHOSETSRNCSSMMMLHGYDQLQWRQWBBOJSWMVXXYIOMI9EXTPJYIQ9GXCLZMKG9UNFKLKRGGJMIMMVGZGBDGRKWBHXCZOMCIRVLBMGXQKXEQKZNMVYHODWXJYYPVUQLLBGCILOYKHBFRUJKIKMKH9RITQOQGLESBZGDDQLCYOUTCRFHJ9ARQYPQLRLOHDEAXEYTM9CCCRWGCJWRGAWYHSHBFXOPNKCVSHDCWPMTSZOUMNOTDWFEDLMSLLMWQBAVAPMPBGZ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IIJYJFDOBLEB9LGTNWMCNADXPJVGECZ9SKVRTOXSNNXRHPP9QMCXSWRLU99999MINEIOTADOTCOM9999999999999DBNIZZXJE999999999L99999999XPBFUCTLEMOYKHMTZOKTNLTTHJY";

            // Act
            var transfer = new TransferItem()
            {
                Address = "ASLIEIUJQHMVNHFQEXIDGGRRINZRHXZT9IWMZLRHWDYL9C9A9JSPBZUXJID9YERUQYRVALRVRLQZYSRXW", Message = "TESTMESSAGE", Tag = "MINEIOTADOTCOM", Value = 0
            };
            var tran = transfer.CreateTransactions()[0];

            tran.TrunkTransaction  = "GFZIP9ZXJIJLUBYGTY9LGEDXVBLRCBEOEWYGZKHDLCCGXOVFPZM9MLQRMATDIICUFZRNXDNOBQIBA9999";
            tran.BranchTransaction = "NYXCW9DAGWKXQXUL9OUIIJYJFDOBLEB9LGTNWMCNADXPJVGECZ9SKVRTOXSNNXRHPP9QMCXSWRLU99999";
            tran.Bundle            = "9BHGQLNJGFONXXJLSNEZXACIP9UQGV9HIWKP9X9COQLHBRSWEBSBJECCLLADKBUW9HAKSQZBNJZVIQAHZ";
            tran.SetTimeStamp(new DateTime(2018, 01, 12, 0, 0, 0, DateTimeKind.Utc));

            var trytesOutput = tran.ToTransactionTrytes();

            // Assert
            Assert.AreEqual("ASLIEIUJQHMVNHFQEXIDGGRRINZRHXZT9IWMZLRHWDYL9C9A9JSPBZUXJID9YERUQYRVALRVRLQZYSRXW", tran.Address);
            Assert.AreEqual(0, tran.Value);
            Assert.AreEqual("MINEIOTADOTCOM9999999999999", tran.Tag);


            Assert.AreEqual("9BHGQLNJGFONXXJLSNEZXACIP9UQGV9HIWKP9X9COQLHBRSWEBSBJECCLLADKBUW9HAKSQZBNJZVIQAHZ", tran.Bundle);
            Assert.AreEqual("GFZIP9ZXJIJLUBYGTY9LGEDXVBLRCBEOEWYGZKHDLCCGXOVFPZM9MLQRMATDIICUFZRNXDNOBQIBA9999", tran.TrunkTransaction);
            Assert.AreEqual("NYXCW9DAGWKXQXUL9OUIIJYJFDOBLEB9LGTNWMCNADXPJVGECZ9SKVRTOXSNNXRHPP9QMCXSWRLU99999", tran.BranchTransaction);

            Assert.AreEqual(0, tran.LastIndex);
            Assert.AreEqual(0, tran.CurrentIndex);
            Assert.AreEqual(151575840, tran.Timestamp, tran.Timestamp);
            Assert.AreEqual("999999999999999999999999999", tran.Nonce); // Why is this 81 not 27?
        }
 private void View_ChangedSelectionEvent()
 {
     if (View.SelectedItem != null)
     {
         TransferItem selected = View.SelectedItem;
         if (null != selected)
         {
             if (null != selected.local)
             {
                 View.LocalFileUrl = selected.local.getAbsolute();
                 if (selected.local.attributes().getSize() == -1)
                 {
                     View.LocalFileSize = UnknownString;
                 }
                 else
                 {
                     View.LocalFileSize = SizeFormatterFactory.get().format(selected.local.attributes().getSize());
                 }
                 if (selected.local.attributes().getModificationDate() == -1)
                 {
                     View.LocalFileModificationDate = UnknownString;
                 }
                 else
                 {
                     View.LocalFileModificationDate =
                         UserDateFormatterFactory.get().getLongFormat(selected.local.attributes().getModificationDate());
                 }
             }
             View.RemoteFileUrl =
                 new DefaultUrlProvider(Transfer.getSource()).toUrl(selected.remote)
                 .find(DescriptiveUrl.Type.provider)
                 .getUrl();
             TransferStatus status = TransferPromptModel.GetStatus(selected);
             if (status.getRemote().getSize() == -1)
             {
                 View.RemoteFileSize = UnknownString;
             }
             else
             {
                 View.RemoteFileSize = SizeFormatterFactory.get().format(status.getRemote().getSize());
             }
             if (status.getRemote().getModificationDate() == -1)
             {
                 View.RemoteFileModificationDate = UnknownString;
             }
             else
             {
                 View.RemoteFileModificationDate =
                     UserDateFormatterFactory.get().getLongFormat(status.getRemote().getModificationDate());
             }
         }
         else
         {
             View.LocalFileUrl              = String.Empty;
             View.LocalFileSize             = String.Empty;
             View.LocalFileModificationDate = String.Empty;
         }
     }
 }
Exemplo n.º 19
0
 public InnerTransferPromptListWorker(TransferPromptModel model, TransferPromptController controller,
                                      Transfer transfer, TransferItem directory, TransferItemCache cache)
     : base(transfer, directory.remote, directory.local, controller)
 {
     _model     = model;
     _directory = directory;
     _cache     = cache;
 }
Exemplo n.º 20
0
        /// <summary>
        /// Sends transfer with money.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="transferItem">Transfer item to send</param>
        /// <param name="seed">Seed from which you want to send money.</param>
        /// <param name="startFromIndex">Index to start search for address</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns></returns>
        public static async Task <TransactionItem[]> SendTransfer(this IotaApi api, TransferItem transferItem, string seed, int startFromIndex, CancellationToken cancellationToken)
        {
            var transactionItemsToSend = await api.CreateTransactions(transferItem, seed, startFromIndex, cancellationToken);

            var transactionItems = await api.AttachTransactions(transactionItemsToSend, cancellationToken);

            return(transactionItems);
        }
Exemplo n.º 21
0
 public bool IsSelected(TransferItem item)
 {
     if (_selected.ContainsKey(item))
     {
         return(_selected[item] == CheckState.Checked);
     }
     return(true);
 }
Exemplo n.º 22
0
 public override object GetCreateImage(TransferItem item)
 {
     if (!GetStatus(item).isExists())
     {
         return((Image)Images.Plus);
     }
     return(null);
 }
Exemplo n.º 23
0
 public virtual object GetCreateImage(TransferItem item)
 {
     if (!GetStatus(item).isExists())
     {
         return(IconCache.IconForName("plus"));
     }
     return(null);
 }
Exemplo n.º 24
0
        public async Task <string> ApproveTransaction(string transactionHash, ApproveTransactionType approveType)
        {
            var api = CreateIotaClient();
            //var address = await api.GetAddress(TestSeed2, 8);

            var emptyAddress = IotaUtils.GenerateRandomTrytes(81); // "".Pad(81);

            var transfer = new TransferItem()
            {
                Address = emptyAddress,
                Value   = 0,
                Message = "",
                Tag     = ""
            };

            while (true)
            {
                try
                {
                    CancellationTokenSource cts = new CancellationTokenSource();

                    var transactions    = transfer.CreateTransactions();
                    var trytesToPow     = transactions.GetTrytes().Single();
                    var toApproveResult = await api.IriApi.GetTransactionsToApprove(9);

                    var toApprove = toApproveResult.Result;

                    var diver = new PowDiver();
                    cts.CancelAfter(20000);
                    var trunk  = toApprove.TrunkTransaction;
                    var branch = toApprove.BranchTransaction;

                    if (approveType == ApproveTransactionType.Trunk)
                    {
                        trunk = transactionHash;
                    }
                    else
                    {
                        branch = transactionHash;
                    }

                    var trytesToSend = await diver.DoPow(trytesToPow.SetApproveTransactions(trunk, branch), 15, cts.Token);

                    await api.IriApi.BroadcastTransactions(trytesToSend);

                    await api.IriApi.StoreTransactions(trytesToSend);

                    var transaction = new TransactionItem(trytesToSend);

                    return(transaction.Hash);
                }
                catch (OperationCanceledException)
                {
                    continue;
                }
            }
        }
Exemplo n.º 25
0
 void Dispose()
 {
     AppSetting.TransferManager.ItemsTransferWork.Remove(this);
     item     = null;
     clientTo = null;
     chunksSizesToUploadMega = null;
     mega_up          = null;
     completionHandle = null;
 }
Exemplo n.º 26
0
        /// <summary>
        /// Finds reminder and creates transaction items
        /// </summary>
        /// <param name="transferItem"></param>
        /// <param name="seed"></param>
        /// <param name="addressItems"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <TransactionItem[]> CreateTransactions(TransferItem transferItem, string seed, IEnumerable <AddressItem> addressItems, CancellationToken cancellationToken)
        {
            addressItems = addressItems.Where(b => b.Balance > 0).ToArray();
            var reminderAddressItem = await FindReminderAddress(seed, addressItems.Max(a => a.Index) + 1, cancellationToken);

            var transactionItems = transferItem.CreateTransactions(reminderAddressItem.Address, addressItems.ToArray());

            return(transactionItems);
        }
Exemplo n.º 27
0
        public static AbstractEntities.TransferItem ToAbstract(this TransferItem dao)
        {
            if (dao == null)
            {
                return(null);
            }

            return(new AbstractEntities.TransferItem(dao.Id, dao.Name, dao.Price, dao.Discount));
        }
        public virtual TransferAction prompt(TransferItem file)
        {
            if (Log.isDebugEnabled())
            {
                Log.debug(String.Format("Prompt for transfer action of {0}", Transfer));
            }
            for (int i = 0; i < Transfer.getRoots().size(); i++)
            {
                TransferItem next = (TransferItem)Transfer.getRoots().get(i);
                TransferPromptModel.Add(next);
            }

            AsyncDelegate wireAction = delegate
            {
                View.ToggleDetailsEvent += View_ToggleDetailsEvent;
                View.DetailsVisible      = PreferencesFactory.get().getBoolean("transfer.toggle.details");

                View.ChangedActionEvent    += View_ChangedActionEvent;
                View.ChangedSelectionEvent += View_ChangedSelectionEvent;

                View.ModelCanExpandDelegate      = TransferPromptModel.CanExpand;
                View.ModelChildrenGetterDelegate = TransferPromptModel.ChildrenGetter;
                View.ModelCheckStateGetter       = TransferPromptModel.GetCheckState;
                View.ModelCheckStateSetter       = TransferPromptModel.SetCheckState;
                View.ModelSizeGetter             = TransferPromptModel.GetSize;
                View.ModelSizeAsStringGetter     = TransferPromptModel.GetSizeAsString;
                View.ModelFilenameGetter         = TransferPromptModel.GetName;
                View.ModelIconGetter             = TransferPromptModel.GetIcon;
                View.ModelWarningGetter          = TransferPromptModel.GetWarningImage;
                View.ModelCreateGetter           = TransferPromptModel.GetCreateImage;
                View.ModelSyncGetter             = TransferPromptModel.GetSyncGetter;
                View.ModelActiveGetter           = TransferPromptModel.IsActive;

                View.ItemsChanged += UpdateStatusLabel;

                View.ViewShownEvent += delegate
                {
                    View.SetModel(TransferPromptModel.ChildrenGetter(null));
                    //select first one if there is any
                    IEnumerator <TransferItem> en = TransferPromptModel.ChildrenGetter(null).GetEnumerator();
                    if (en.MoveNext())
                    {
                        View.SelectedItem = en.Current;
                    }
                };
                DialogResult result = View.ShowDialog(_parent.View);

                if (result == DialogResult.Cancel)
                {
                    Action = TransferAction.cancel;
                }
            };

            _parent.Invoke(wireAction, true);
            return(Action);
        }
Exemplo n.º 29
0
        public object GetModified(TransferItem path)
        {
            long modificationDate = path.remote.attributes().getModificationDate();

            if (modificationDate != -1)
            {
                return(UserDefaultsDateFormatter.ConvertJavaMillisecondsToDateTime(modificationDate));
            }
            return(UNKNOWN);
        }
 public void RefreshBrowserObject(TransferItem item)
 {
     if (item != null)
     {
         browser.RefreshObject(item);
     }
     else
     {
         //browser.ReloadTree();
     }
 }
Exemplo n.º 31
0
 private static CompletedTransfer CompleteCraftTransfer(Base @base, TransferItem<Craft> transferredCraft)
 {
     @base.TransferredCrafts.Remove(transferredCraft);
     @base.Crafts.Add(transferredCraft.Item);
     var completedTransfer = new CompletedTransfer
     {
         Name = transferredCraft.Item.Name,
         Quantity = 1,
         Destination = @base.Name
     };
     return completedTransfer;
 }
Exemplo n.º 32
0
 private static CompletedTransfer CompleteSoldierTransfer(Base @base, TransferItem<Soldier> transferredSoldier)
 {
     @base.TransferredSoldiers.Remove(transferredSoldier);
     @base.Soldiers.Add(transferredSoldier.Item);
     var completedTransfer = new CompletedTransfer
     {
         Name = transferredSoldier.Item.Name,
         Quantity = 1,
         Destination = @base.Name
     };
     return completedTransfer;
 }
        public void TestDirectoryCheckContentMD5()
        {
            long fileSize = 5 * 1024 * 1024;
            long totalSize = fileSize * 4;
            string wrongMD5 = "wrongMD5";

            string checkWrongMD5File = "checkWrongMD5File";
            string checkCorrectMD5File = "checkCorrectMD5File";
            string notCheckWrongMD5File = "notCheckWrongMD5File";
            string notCheckCorrectMD5File = "notCheckCorrectMD5File";

            DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);
            DirNode checkMD5Folder = new DirNode("checkMD5");
            DMLibDataHelper.AddOneFileInBytes(checkMD5Folder, checkWrongMD5File, fileSize);
            DMLibDataHelper.AddOneFileInBytes(checkMD5Folder, checkCorrectMD5File, fileSize);
            sourceDataInfo.RootNode.AddDirNode(checkMD5Folder);

            DirNode notCheckMD5Folder = new DirNode("notCheckMD5");
            DMLibDataHelper.AddOneFileInBytes(notCheckMD5Folder, notCheckWrongMD5File, fileSize);
            DMLibDataHelper.AddOneFileInBytes(notCheckMD5Folder, notCheckCorrectMD5File, fileSize);
            sourceDataInfo.RootNode.AddDirNode(notCheckMD5Folder);

            FileNode tmpFileNode = checkMD5Folder.GetFileNode(checkWrongMD5File);
            tmpFileNode.MD5 = wrongMD5;

            tmpFileNode = notCheckMD5Folder.GetFileNode(notCheckWrongMD5File);
            tmpFileNode.MD5 = wrongMD5;

            SourceAdaptor.GenerateData(sourceDataInfo);

            TransferEventChecker eventChecker = new TransferEventChecker();
            TransferContext context = new TransferContext();
            eventChecker.Apply(context);
            
            bool failureReported = false;
            context.FileFailed += (sender, args) =>
                {
                    if (args.Exception != null)
                    {
                        failureReported = args.Exception.Message.Contains(checkWrongMD5File);
                    }
                };

            ProgressChecker progressChecker = new ProgressChecker(4, totalSize, 3, 1, 0, totalSize);
            context.ProgressHandler = progressChecker.GetProgressHandler();

            TransferItem checkMD5Item = new TransferItem()
            {
                SourceObject = SourceAdaptor.GetTransferObject(sourceDataInfo.RootPath, checkMD5Folder),
                DestObject = DestAdaptor.GetTransferObject(sourceDataInfo.RootPath, checkMD5Folder),
                IsDirectoryTransfer = true,
                SourceType = DMLibTestContext.SourceType,
                DestType = DMLibTestContext.DestType,
                IsServiceCopy = DMLibTestContext.IsAsync,
                TransferContext = context,
                Options = new DownloadDirectoryOptions()
                {
                    DisableContentMD5Validation = false,
                    Recursive = true,
                },
            };

            TransferItem notCheckMD5Item = new TransferItem()
            {
                SourceObject = SourceAdaptor.GetTransferObject(sourceDataInfo.RootPath, notCheckMD5Folder),
                DestObject = DestAdaptor.GetTransferObject(sourceDataInfo.RootPath, notCheckMD5Folder),
                IsDirectoryTransfer = true,
                SourceType = DMLibTestContext.SourceType,
                DestType = DMLibTestContext.DestType,
                IsServiceCopy = DMLibTestContext.IsAsync,
                TransferContext = context,
                Options = new DownloadDirectoryOptions()
                {
                    DisableContentMD5Validation = true,
                    Recursive = true,
                },
            };

            var testResult = this.RunTransferItems(new List<TransferItem>() { checkMD5Item, notCheckMD5Item }, new TestExecutionOptions<DMLibDataInfo>());

            DMLibDataInfo expectedDataInfo = sourceDataInfo.Clone();
            expectedDataInfo.RootNode.GetDirNode(checkMD5Folder.Name).DeleteFileNode(checkWrongMD5File);
            expectedDataInfo.RootNode.GetDirNode(notCheckMD5Folder.Name).DeleteFileNode(notCheckWrongMD5File);

            DMLibDataInfo actualDataInfo = testResult.DataInfo;
            actualDataInfo.RootNode.GetDirNode(checkMD5Folder.Name).DeleteFileNode(checkWrongMD5File);
            actualDataInfo.RootNode.GetDirNode(notCheckMD5Folder.Name).DeleteFileNode(notCheckWrongMD5File);

            Test.Assert(DMLibDataHelper.Equals(expectedDataInfo, actualDataInfo), "Verify transfer result.");
            Test.Assert(failureReported, "Verify md5 check failure is reported.");
            VerificationHelper.VerifyFinalProgress(progressChecker, 3, 0, 1);

            if (testResult.Exceptions.Count != 1)
            {
                Test.Error("Expect one exception but actually no exception is thrown.");
            }
            else
            {
                VerificationHelper.VerifyTransferException(testResult.Exceptions[0], TransferErrorCode.SubTransferFails, "1 sub transfer(s) failed.");
            }
        }
Exemplo n.º 34
0
 private static CompletedTransfer CompleteStoreTransfer(Base @base, TransferItem<StoreItem> transferredStore)
 {
     @base.TransferredStores.Remove(transferredStore);
     switch (transferredStore.Item.ItemType)
     {
     case ItemType.Engineer:
         @base.EngineerCount += transferredStore.Item.Count;
         break;
     case ItemType.Scientist:
         @base.ScientistCount += transferredStore.Item.Count;
         break;
     default:
         @base.Stores.Add(transferredStore.Item.ItemType, transferredStore.Item.Count);
         break;
     }
     var completedTransfer = new CompletedTransfer
     {
         Name = transferredStore.Item.ItemType.Metadata().Name,
         Quantity = transferredStore.Item.Count,
         Destination = @base.Name
     };
     return completedTransfer;
 }