private void SetupTorrentWatcher() { watcher = new GatorShare.Services.BitTorrent.TorrentFolderWatcher(Path.GetFullPath(TORRENT_DIR), "*.torrent"); watcher.TorrentFound += delegate(object sender, TorrentWatcherEventArgs e) { try { // This is a hack to work around the issue where a file triggers the event // before it has finished copying. As the filesystem still has an exclusive lock // on the file, monotorrent can't access the file and throws an exception. // The best way to handle this depends on the actual application. // Generally the solution is: Wait a few hundred milliseconds // then try load the file. System.Threading.Thread.Sleep(500); Torrent t = Torrent.Load(e.TorrentPath); // There is also a predefined 'InfoHashTrackable' MonoTorrent.Tracker which // just stores the infohash and name of the torrent. This is all that the tracker // needs to run. So if you want an ITrackable that "just works", then use InfoHashTrackable. // ITrackable trackable = new InfoHashTrackable(t); ITrackable trackable = new CustomITrackable(t); lock (tracker) tracker.Add(trackable); } catch (Exception ex) { Debug.WriteLine("Error loading torrent from disk: {0}", ex.Message); Debug.WriteLine("Stacktrace: {0}", ex.ToString()); } }; watcher.Start(); watcher.ForceScan(); }
protected override void ResetTrackedObservables() { Tracker.MarkAllStale(); if (DataSource != null) { Tracker.Add(DataSource, HandleTimeEntryPropertyChanged); if (DataSource.Project != null) { Tracker.Add(DataSource.Project, HandleProjectPropertyChanged); if (DataSource.Project.Client != null) { Tracker.Add(DataSource.Project.Client, HandleClientPropertyChanged); } } if (DataSource.Task != null) { Tracker.Add(DataSource.Task, HandleTaskPropertyChanged); } } Tracker.ClearStale(); }
internal void Initialise(int torrents, int peers, int requests) { long ipAddress; byte[] infoHash; for (int i = 0; i < torrents; i++) { if (i % 20 == 0) { Console.WriteLine("Loaded {0:0.00}%", (double)i / torrents * 100); } // Create the fake infohash and add the torrent to the tracker. infoHash = new byte[20]; random.NextBytes(infoHash); tracker.Add(new InfoHashTrackable(i.ToString(), infoHash)); hashes.Add(infoHash); ipAddress = 1; peers = averagePeers;// random.Next((int)(averagePeers * 0.5), (int)(averagePeers * 1.5)); for (int j = 0; j < peers; j++) { listener.Handle(infoHash, new IPAddress(ipAddress++), true); } } threadSleepTime = (int)(20000.0 / requests + 0.5); threads = new Thread[20]; }
static void Database(int Index) { Tracker.Add(Engines.DB_ShortName[Index - 1]); Engines.Load.Sqlite(Engines.DB_Path[Index - 1]); Engines.GetSchema(Engines.CurrentDatabase); Engines.GetColumnsofTable(Engines.CurrentDatabase, Engines.CurrentTable); LDControls.ComboBoxContent(GlobalStatic.ComboBox["FunctionList"], Engines.Functions(Engines.EnginesMode.SQLITE).ToPrimitiveArray()); Sorts(1); Table(1); LDControls.ComboBoxSelect(GlobalStatic.ComboBox["Sorts"], 1); LDControls.ComboBoxSelect(GlobalStatic.ComboBox["Table"], 1); if (GlobalStatic.SortBy == 4) { Engines.SetDefaultTable("sqlite_master"); Engines.GetColumnsofTable(Engines.CurrentDatabase, Engines.CurrentTable); LDControls.ComboBoxContent(GlobalStatic.ComboBox["Table"], "1=" + Engines.CurrentTable + ";2=sqlite_temp_master;"); return; } Engines.GetColumnsofTable(Engines.CurrentDatabase, Engines.CurrentTable); return; }
/// <summary> /// Starts a new progress transaction. Events may raise from this call. /// </summary> /// <returns>Unique ID for the transaction</returns> public int StartNewTransaction() { var id = GetUniqueID(); Tracker.Add(id); UpdateProgress(); return(id); }
public void UnconfirmedTransactionsWithoutReceivedCoinsShouldNotShowUp() { BlockchainBuilder builder = new BlockchainBuilder(); Tracker tracker = new Tracker(); Key bob = new Key(); tracker.Add(bob); Key alice = new Key(); var tx1 = builder.GiveMoney(bob, Money.Coins(1.0m)); var b = builder.FindBlock(); tracker.NotifyTransaction(tx1, builder.Chain.Tip, b); var tx2 = builder.SpendCoin(tx1.Outputs.AsCoins().First(), alice, Money.Coins(0.1m)); b = builder.FindBlock(); tracker.NotifyTransaction(tx2, builder.Chain.Tip, b); var tx3 = builder.SpendCoin(tx2.Outputs.AsCoins().Skip(1).First(), alice, Money.Coins(0.2m)); Assert.True(tracker.NotifyTransaction(tx3)); var transactions = tracker.GetWalletTransactions(builder.Chain); Assert.True(transactions.Count == 3); Assert.True(transactions.Summary.UnConfirmed.TransactionCount == 1); Assert.True(transactions.Summary.UnConfirmed.Amount == -Money.Coins(0.2m)); Assert.True(transactions.Summary.Confirmed.TransactionCount == 2); Assert.True(transactions.Summary.Confirmed.Amount == Money.Coins(0.9m)); Assert.True(transactions.Summary.Spendable.TransactionCount == 3); Assert.True(transactions.Summary.Spendable.Amount == Money.Coins(0.7m)); builder.Chain.SetTip(builder.Chain.GetBlock(1)); transactions = tracker.GetWalletTransactions(builder.Chain); Action _ = () => { Assert.True(transactions.Count == 3); Assert.True(transactions.Summary.Confirmed.TransactionCount == 1); Assert.True(transactions.Summary.Confirmed.Amount == Money.Coins(1.0m)); Assert.True(transactions.Summary.Spendable.TransactionCount == 3); Assert.True(transactions.Summary.Spendable.Amount == Money.Coins(0.7m)); Assert.True(transactions.Summary.UnConfirmed.TransactionCount == 2); Assert.True(transactions.Summary.UnConfirmed.Amount == -Money.Coins(0.3m)); }; _(); tracker.NotifyTransaction(tx2); //Notifying tx2 should have no effect, since it already is accounted because it was orphaned _(); }
protected override void ResetTrackedObservables() { Tracker.MarkAllStale(); if (DataSource != null) { Tracker.Add(DataSource, HandleTagPropertyChanged); } Tracker.ClearStale(); }
protected override void ResetTrackedObservables() { Tracker.MarkAllStale(); if (model != null) { Tracker.Add(model, HandleClientPropertyChanged); } Tracker.ClearStale(); }
public void CanTrackScriptCoins() { BlockchainBuilder builder = new BlockchainBuilder(); Tracker tracker = new Tracker(); Key bob = new Key(); tracker.Add(bob.PubKey, true); var tx1 = builder.GiveMoney(bob.PubKey.ScriptPubKey.Hash, Money.Coins(1.0m)); Assert.True(tracker.NotifyTransaction(tx1)); Assert.True(tracker.GetWalletTransactions(builder.Chain)[0].ReceivedCoins[0] is ScriptCoin); }
public TrackedCommand(ICommandTracker tracker, Action <T> execute, Action <T> undoExecute) : base(tracker) { ExecuteCommand = new DelegateCommand <T>((arg) => { LastUsedArguments = arg; execute.Invoke(arg); Tracker.Add(this); }); UndoCommand = new DelegateCommand <T>((arg) => { LastUsedArguments = arg; undoExecute.Invoke(arg); Tracker.Add(this); }); }
protected void LogInUser(object sender, EventArgs e) { //check to see if this person has a cookie if (Request.Cookies["shopperID"] != null) { string sAnonID = Request.Cookies["shopperID"].Value; //synch the tracker Tracker.SynchTrackingCookie(Login1.UserName, sAnonID); //Log it Tracker.Add(BehaviorType.LoggingIn); //reset the cookie so we know who this is Response.Cookies["shopperID"].Value = Login1.UserName; Response.Cookies["shopperID"].Expires = DateTime.Today.AddDays(365); } }
/// <summary> /// CreateTempDocs and tracker, together, show how one might create documents in a temporary location, then move/move /// them to another location later. This is handly for the Tester application to be able to choose documents at random /// for moving/linking and choosing a percentage of documents for performaing actions on. /// Use Cases [Import New RestDocument], [Copy/Move RestDocument], [DeleteDocument] /// [Folder Structure] /// </summary> /// <returns></returns> protected void CreateTempDocs() { tempPath = tempPath + "-" + threadNum; WriteOutput("[CreateOrGetFolderPath] - Creating or getting folder by path: " + tempPath); Folder tempFolder = CurrentRepository.GetOrCreateFolderByPath(tempPath); WriteOutput("\tFolder: " + tempFolder.GetPropertyValue("object_name") + ":" + tempFolder.GetPropertyValue("r_object_id") + " successfully created!"); WriteOutput("\tCreating " + numDocs + " random documents."); string previousChildId = null; for (int i = 0; i < numDocs; i++) { FileInfo file = ObjectUtil.getRandomFileFromDirectory(importFilesDirectory); Document tempDoc = CurrentRepository.ImportNewDocument(file, testPrefix + "-" + file.Name, tempPath); WriteOutput("\t\t[ImportDocument] - RestDocument " + file.FullName + " imported as " + tempDoc.GetPropertyValue("object_name") + " ObjectID: " + tempDoc.GetPropertyValue("r_object_id").ToString()); WriteOutput("\t\t\t[DeDuplication] - Performing Duplicate Detection on content in holding area...."); CheckDuplicates(tempDoc, tempPath); // Cannot randomly move parentFolders as threads will step on each other. Limit one thread to one // parentFolder String childId = parentFolderId + " CHILD-" + new Random().Next(0, 5); String objectId = (String)tempDoc.GetPropertyValue("r_object_id"); WriteOutput("[CreateAndtrackerDocument] \t\tCreated " + tempDoc.GetPropertyValue("object_name") + ":" + objectId + " Moveing to Parent: " + parentFolderId + " Child: " + childId); WriteOutput("[ChangeExiFetchDocument] - ReFetching and Setting title attribute"); Document doc = tempDoc.Fetch <Document>(); doc.SetPropertyValue("title", "Set properties test"); doc.Save(); Tracker.Add(new DocumentTracker(objectId, parentFolderId, childId)); // To show we can move the same document to multiple childFolderDocs if (previousChildId != null && !previousChildId.Equals(childId)) { WriteOutput("\t\t\tMoveing this document to another child to show the same document can be copied/moveed to multiple childFolderDocs"); Tracker.Add(new DocumentTracker(objectId, parentFolderId, previousChildId)); } previousChildId = childId; } // Done with temp creation loop }
protected void CreateFromTemplate() { Random rnd = new Random(); //get list of templates Feed <Document> results = CurrentRepository.ExecuteDQL <Document>(String.Format("select * from dm_document where FOLDER('/Templates') "), new FeedGetOptions { Inline = true, Links = true }); List <Document> docs = ObjectUtil.getFeedAsList <Document>(results, true); int resultSamples = docs.Count; WriteOutput(String.Format("\t[TemplateList] Returning list of templates...")); foreach (Document doc in docs) { WriteOutput(String.Format("\t\t\tTemplate Name: {0} ID: {1}", doc.GetPropertyValue("object_name").ToString(), doc.GetPropertyValue("r_object_id").ToString())); } List <string> req = childList; for (int i = 0; i < 10; i++) { DocumentTracker trackerDoc = Tracker[rnd.Next(0, Tracker.Count)]; string movePath = trackerDoc.getPath(); string childId = trackerDoc.ChildId; //select one of the documents Document template = docs[rnd.Next(0, resultSamples)]; Document newDoc = CurrentRepository.CopyDocument(template.GetPropertyValue("r_object_id").ToString(), ProcessBasePath + movePath); newDoc.SetPropertyValue("subject", "Created From Template: " + template.GetPropertyValue("object_name")); string documentName = ObjectUtil.NewRandomDocumentName("FROMTEMPLATE"); newDoc.SetPropertyValue("object_name", documentName); newDoc.Save(); string objectId = newDoc.GetPropertyValue("r_object_id").ToString(); //String childId = parentFolderId + " CHILD-" + new Random().Next(0, 5); Tracker.Add(new DocumentTracker(objectId, parentFolderId, childId)); WriteOutput("\t[CreateDocumentFromTemplate] Created document " + documentName + " from template " + template.GetPropertyValue("object_name").ToString()); } }
private void Clone(IChangeSet <T> changes) { foreach (var change in changes) { switch (change.Reason) { case ListChangeReason.Add: Tracker.Add(change.Item.Current); break; case ListChangeReason.AddRange: foreach (var t in change.Range) { Tracker.Add(t); } break; case ListChangeReason.Replace: Tracker.Remove(change.Item.Previous.Value); Tracker.Add(change.Item.Current); break; case ListChangeReason.Remove: Tracker.Remove(change.Item.Current); break; case ListChangeReason.RemoveRange: case ListChangeReason.Clear: foreach (var t in change.Range) { Tracker.Remove(t); } break; } } }
protected void Application_Start(object sender, EventArgs e) { server = new Tracker(); server.AllowUnregisteredTorrents = false; server.AnnounceInterval = new TimeSpan(0, 5, 0); // 10 min de atualização // carrega os torrents ja registrados using (var repositorio = new DataRepository <Torrent>()) { ObjectSet <Torrent> torrents = (ObjectSet <Torrent>)repositorio.GetAll(); foreach (var torr in torrents) { server.Add(new CustomTrackable(torr.Nome, torr.HashInfo)); } } listener = new AspNetListener(); listener.AnnounceReceived += listener_AnnounceReceived; server.RegisterListener(listener); Application.Add("server", server); Application.Add("listener", listener); }
public void CanTrackKey() { BlockchainBuilder builder = new BlockchainBuilder(); Key bob = new Key(); Tracker tracker = new Tracker(); tracker.Add(bob); var tx1 = builder.GiveMoney(bob, Money.Coins(1.0m)); var coin = tx1.Outputs.AsCoins().First(); Assert.True(tracker.NotifyTransaction(tx1)); Thread.Sleep(10); Key alice = new Key(); var tx2 = builder.SpendCoin(coin, alice, Money.Coins(0.6m)); Assert.True(tracker.NotifyTransaction(tx2)); var block = builder.FindBlock(); foreach (var btx in block.Transactions) { if (!btx.IsCoinBase) { Assert.True(tracker.NotifyTransaction(btx, builder.Chain.GetBlock(block.GetHash()), block)); Assert.True(tracker.NotifyTransaction(btx, builder.Chain.GetBlock(block.GetHash()), block)); //Idempotent } } var transactions = tracker.GetWalletTransactions(builder.Chain); Assert.True(transactions.Count == 2); Assert.True(transactions[0].Transaction.GetHash() == tx2.GetHash()); Assert.True(transactions[1].Transaction.GetHash() == tx1.GetHash()); Assert.True(transactions[0].Balance == -Money.Coins(0.6m)); var tx3 = builder.GiveMoney(bob, Money.Coins(0.01m)); coin = tx3.Outputs.AsCoins().First(); block = builder.FindBlock(); Assert.True(tracker.NotifyTransaction(block.Transactions[1], builder.Chain.GetBlock(block.GetHash()), block)); transactions = tracker.GetWalletTransactions(builder.Chain); Assert.True(transactions.Count == 3); Assert.True(transactions.Summary.UnConfirmed.TransactionCount == 0); Assert.True(transactions[0].Transaction.GetHash() == block.Transactions[1].GetHash()); Assert.Equal(2, transactions.GetSpendableCoins().Count()); // the 1 change + 1 gift builder.Chain.SetTip(builder.Chain.Tip.Previous); transactions = tracker.GetWalletTransactions(builder.Chain); Assert.True(transactions.Count == 3); Assert.True(transactions.Summary.UnConfirmed.TransactionCount == 1); //Test roundtrip serialization var filterBefore = tracker.CreateBloomFilter(0.005); MemoryStream ms = new MemoryStream(); tracker.Save(ms); tracker = new Tracker(); ms.Position = 0; tracker = Tracker.Load(ms); transactions = tracker.GetWalletTransactions(builder.Chain); Assert.True(transactions.Count == 3); Assert.True(transactions.Summary.UnConfirmed.TransactionCount == 1); var filterAfter = tracker.CreateBloomFilter(0.005); Assert.True(filterBefore.ToBytes().SequenceEqual(filterAfter.ToBytes())); ///// }
public void CanPrune() { BlockchainBuilder builder = new BlockchainBuilder(); Tracker tracker = new Tracker(); Key bob = new Key(); Key alice = new Key(); tracker.Add(bob); var oldUnconf = builder.GiveMoney(bob, Money.Coins(1.0m)); Assert.True(tracker.NotifyTransaction(oldUnconf)); builder.Mempool.Clear(); var oldConf = builder.GiveMoney(bob, Money.Coins(0.9m)); var oldConfSpent = builder.SpendCoin(oldConf.Outputs.AsCoins().First(), alice, Money.Coins(0.01m)); var block = builder.FindBlock(); Assert.True(tracker.NotifyTransaction(oldConf, builder.Chain.Tip, block)); Assert.True(tracker.NotifyTransaction(oldConfSpent, builder.Chain.Tip, block)); for (int i = 0; i < 9; i++) { builder.FindBlock(); } Assert.True(tracker.Prune(builder.Chain, 10).Count == 0); builder.FindBlock(); //Prune tracked outpoint var pruned = tracker.Prune(builder.Chain, 10); Assert.Equal(1, pruned.Count); Assert.True(pruned.First() is Tracker.TrackedOutpoint); //Prune old unconf pruned = tracker.Prune(builder.Chain, timeExpiration: TimeSpan.Zero); Assert.Equal(1, pruned.Count); var op = pruned.OfType <Tracker.Operation>().First(); Assert.True(op.BlockId == null); var conf = builder.GiveMoney(bob, Money.Coins(0.9m)); block = builder.FindBlock(); Assert.True(tracker.NotifyTransaction(conf, builder.Chain.Tip, block)); var oldSpentForked = builder.SpendCoin(conf.Outputs.AsCoins().First(), alice, Money.Coins(0.021m)); block = builder.FindBlock(); Assert.True(tracker.NotifyTransaction(oldSpentForked, builder.Chain.Tip, block)); var forked = builder.Chain.Tip; builder.Chain.SetTip(builder.Chain.Tip.Previous); for (int i = 0; i < 10; i++) { builder.FindBlock(); } pruned = tracker.Prune(builder.Chain, 10); Assert.True(pruned.Count == 1); //Tracked outpoint of conf Assert.True(pruned.First() is Tracker.TrackedOutpoint); block = builder.FindBlock(); pruned = tracker.Prune(builder.Chain, 10); //Old forked spent Assert.Equal(1, pruned.Count); op = pruned.OfType <Tracker.Operation>().First(); Assert.Equal(forked.HashBlock, op.BlockId); }
public SimpleTracker(string announcementEndpoint, string torrentsDirectoryPath) { // Make the listner. var listener = new HttpListener(announcementEndpoint); // Make the tracker. Tracker = new Tracker (); Tracker.AnnounceInterval = new TimeSpan (0, 1, 0); Tracker.AllowUnregisteredTorrents = true; Tracker.RegisterListener (listener); // Make mappings. Mappings = new ConcurrentDictionary<string, InfoHashTrackable> (); // Make watcher. Watcher = new TorrentFolderWatcher (torrentsDirectoryPath, "*.torrent"); Watcher.TorrentFound += (sender, e) => { try { // Wait for file to finish copying. System.Threading.Thread.Sleep (500); // Make InfoHashTrackable from torrent. var torrent = Torrent.Load (e.TorrentPath); var trackable = new InfoHashTrackable (torrent); // Add to tracker. lock (Tracker) Tracker.Add (trackable); // Save to mappings. Mappings[e.TorrentPath] = trackable; // Log. Console.WriteLine("Added {0}", e.TorrentPath); } catch (Exception exception) { Debug.WriteLine ("Error loading torrent from disk: {0}", exception.Message); Debug.WriteLine ("Stacktrace: {0}", exception.ToString ()); } }; Watcher.TorrentLost += (sender, e) => { try { // Get from mappings. var trackable = Mappings[e.TorrentPath]; // Remove from tracker. lock(Tracker) Tracker.Remove(trackable); // Remove from mappings. Mappings.TryRemove(e.TorrentPath, out trackable); // Log. Console.WriteLine("Removed {0}", e.TorrentPath); } catch(Exception exception) { Debug.WriteLine ("Error uploading torrent from disk: {0}", exception.Message); Debug.WriteLine ("Stacktrace: {0}", exception.ToString ()); } }; // Register close events. AppDomain.CurrentDomain.ProcessExit += (sender, e) => Tracker.Dispose (); // Run. listener.Start(); Watcher.Start(); Watcher.ForceScan(); }