Exemple #1
0
        /// <summary>
        /// Starts listening for incoming connection requests.
        /// </summary>
        public void Start()
        {
            try
            {
                // Before Running CheckList
                if (!My.Computer.Network.IsAvailable)
                {
                    Core.Logger.Log("Network is not available.", Logger.LogTypes.Warning);
                    Dispose();
                }
                else
                {
                    IPEndPoint  = new IPEndPoint(IPAddress.Any, Core.Setting.RCONPort);
                    TcpListener = new TcpListener(IPEndPoint);
                    TcpListener.Start();

                    IsActive = true;

                    // Threading
                    Thread Thread = new Thread(new ThreadStart(ThreadStartListening))
                    {
                        IsBackground = true
                    };
                    Thread.Start();
                    ThreadCollection.Add(Thread);
                }
            }
            catch (Exception)
            {
                Dispose();
            }
        }
Exemple #2
0
        public MainViewModel(IDataService service, INavigationServiceSignal navService)
        {
            _dataService = service;
            _navigationService = navService;

            Chats = new ThreadCollection(service);
        }
Exemple #3
0
        /// <summary>
        /// Dispose the Listener.
        /// </summary>
        public void Dispose()
        {
            IsActive = false;

            if (TcpListener != null)
            {
                TcpListener.Stop();
            }
            if (Client != null)
            {
                Client.Close();
            }
            if (Reader != null)
            {
                Reader.Dispose();
            }

            for (int i = 0; i < ThreadCollection.Count; i++)
            {
                if (ThreadCollection[i].IsAlive)
                {
                    ThreadCollection[i].Abort();
                }
            }
            ThreadCollection.RemoveRange(0, ThreadCollection.Count);

            Core.Logger.Log("RCON Listener Disposed.", Logger.LogTypes.Info);
        }
Exemple #4
0
        public void Start()
        {
            try
            {
                // Before Running CheckList
                if (!My.Computer.Network.IsAvailable)
                {
                    Core.Logger.Log("Network is not available.", Logger.LogTypes.Warning);
                    Dispose();
                }
                else
                {
                    // Threading
                    Thread Thread = new Thread(new System.Threading.ThreadStart(CheckListener))
                    {
                        IsBackground = true
                    };
                    Thread.Start();
                    ThreadCollection.Add(Thread);

                    StartListen();

                    var UpdateCycle = new Thread(Update);
                    UpdateCycle.Start();
                    ThreadCollection.Add(UpdateCycle);

                    IsActive = true;
                }
            }
            catch (Exception ex)
            {
                ex.CatchError();
                Dispose();
            }
        }
Exemple #5
0
        /// <summary>
        /// Constructs a TypedList with all the messages in the thread given. Poster info is included, so the
        /// returned dataview is bindable at once to the message list repeater.
        /// </summary>
        /// <param name="threadID">ID of Thread which messages should be returned</param>
        /// <param name="pageNo">The page no.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns>TypedList with all messages in the thread for the page specified</returns>
        public static MessagesInThreadTypedList GetAllMessagesInThreadAsTypedList(int threadID, int pageNo, int pageSize)
        {
            // we'll use a typedlist, MessagesInThread to pull the necessary data from the db. The typedlist contains fields from
            // message, user and usertitle.
            MessagesInThreadTypedList messages = new MessagesInThreadTypedList();

            //create the filter with the threadID passed to the method.
            PredicateExpression filter = new PredicateExpression(MessageFields.ThreadID == threadID);

            // Sort Messages on posting date, ascending, so the first post is located on top.
            SortExpression sorter = new SortExpression(MessageFields.PostingDate.Ascending());

            // fetch the data into the typedlist. Pass in the paging information as well, to perform server-side paging.
            messages.Fill(0, sorter, true, filter, null, null, pageNo, pageSize);

            // update thread entity directly inside the DB with a non-transactional update statement so the # of views is increased by one.
            ThreadEntity updater = new ThreadEntity();

            // set the NumberOfViews field to an expression which increases it by 1
            updater.Fields[(int)ThreadFieldIndex.NumberOfViews].ExpressionToApply = (ThreadFields.NumberOfViews + 1);
            updater.IsNew = false;

            // update the entity directly, and filter on the PK
            ThreadCollection threads = new ThreadCollection();

            threads.UpdateMulti(updater, (ThreadFields.ThreadID == threadID));

            // return the constructed typedlist
            return(messages);
        }
        /// <summary>
        /// Starts listening for incoming connection requests.
        /// </summary>
        public void Start()
        {
            try
            {
                // Before Running CheckList
                if (!My.Computer.Network.IsAvailable)
                {
                    Core.Logger.Log("Network is not available.", Logger.LogTypes.Warning);
                    Dispose();
                }
                else
                {
                    TcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, Core.Setting.Port));
                    TcpListener.Start();

                    IsActive = true;

                    // Threading
                    ThreadCollection.Add(new ThreadStart(ThreadStartListening));
                    ThreadCollection.Add(new ThreadStart(Core.World.Update));

                    if (Core.Setting.AutoRestartTime >= 10)
                    {
                        Core.Logger.Log($"The server will restart every {Core.Setting.AutoRestartTime.ToString()} seconds.", Logger.LogTypes.Info);

                        ThreadCollection.Add(new ThreadStart(ThreadAutoRestart));
                    }
                }
            }
            catch (Exception ex)
            {
                ex.CatchError();
                Dispose();
            }
        }
        public void RemoveTestRemoveExistingActiveThreads()
        {
            ThreadCollection tc = new ThreadCollection();
            GThreadMock      threadToRemove1 = new GThreadMock();
            GThreadMock      threadToRemove2 = new GThreadMock();
            GThreadMock      threadToRemove3 = new GThreadMock();
            GThreadMock      threadToRemove4 = new GThreadMock();

            tc.Add(threadToRemove1);
            tc.Add(threadToRemove2);
            tc.Add(threadToRemove3);
            tc.Add(threadToRemove4);

            Assert.AreEqual(4, tc.Count);

            threadToRemove1.SetState(ThreadState.Ready);
            threadToRemove2.SetState(ThreadState.Scheduled);
            threadToRemove3.SetState(ThreadState.Started);
            threadToRemove4.SetState(ThreadState.Unknown);

            tc.Remove(threadToRemove1);
            tc.Remove(threadToRemove2);
            tc.Remove(threadToRemove3);
            tc.Remove(threadToRemove4);

            // the thread should not have been removed
            // this remove function only allows the removal of Dead or Finished threads
            Assert.AreEqual(4, tc.Count);
        }
Exemple #8
0
 public ThreadPatroller(PatrolTable patterns, IndividualPatrolPattern individualPattern, ThreadCollection store)
     : this()
 {
     this.patterns = patterns;
     this.individualPattern = individualPattern;
     this.store = store;
 }
Exemple #9
0
        public void CorrectResultTest()
        {
            var resultingList = new ConcurrentBag <int>();
            var expectedList  = new List <int>();

            SetupTest((item) => { resultingList.Add(item); Thread.Sleep(100); });

            for (var i = 0; i < 100; i++)
            {
                queue.Add(i);
                expectedList.Add(i);
            }

            using (threadCollection = new ThreadCollection(new SimpleThreadPoolSettings(10)))
            {
                var addResult = AddThreads(10);

                queue.CompleteAdding();

                Assert.IsTrue(addResult);
            }

            var finalList = new List <int>(resultingList);

            finalList.Sort();
            Assert.AreEqual(expectedList.Aggregate(string.Empty, (res, i) => res + i), finalList.Aggregate(string.Empty, (res, i) => res + i));
        }
Exemple #10
0
        /// <summary>
        /// New Networking
        /// </summary>
        /// <param name="Client">Client</param>
        public Networking(TcpClient Client)
        {
            // Set Client Property.
            this.Client = Client;
            IsActive    = true;

            Reader = new StreamReader(Client.GetStream());
            Writer = new StreamWriter(Client.GetStream());

            LastValidPing     = DateTime.Now;
            LastValidMovement = DateTime.Now;

            Thread Thread = new Thread(new ThreadStart(ThreadStartListening))
            {
                IsBackground = true
            };

            Thread.Start();
            ThreadCollection.Add(Thread);

            Thread Thread2 = new Thread(new ThreadStart(ThreadStartPinging))
            {
                IsBackground = true
            };

            Thread2.Start();
            ThreadCollection.Add(Thread2);
        }
Exemple #11
0
        public MainViewModel(IDataService service, INavigationServiceSignal navService)
        {
            _dataService       = service;
            _navigationService = navService;

            Chats = new ThreadCollection(service);
        }
Exemple #12
0
        public void RemoveThreadTest()
        {
            var resultingList = new ConcurrentBag <int>();
            var expectedList  = new List <int>();

            SetupTest((item) => { Thread.Sleep(1000); resultingList.Add(item); });

            using (threadCollection = new ThreadCollection(new SimpleThreadPoolSettings(2)))
            {
                var addResult = AddThreads(2);

                Assert.IsTrue(addResult);

                for (var i = 0; i < 2; i++)
                {
                    queue.Add(i);
                    expectedList.Add(i);
                    Thread.Sleep(500);
                }

                queue.CompleteAdding();

                // просим отменится второй поток, который сейчас работает
                var removeResult = threadCollection.TryRemoveThread();

                Assert.IsTrue(removeResult);
            }

            // если бы dispose не дождался тот второй отменённый поток, то в finalList не попал бы результат
            var finalList = new List <int>(resultingList);

            finalList.Sort();
            Assert.AreEqual(expectedList.Aggregate(string.Empty, (res, i) => res + i), finalList.Aggregate(string.Empty, (res, i) => res + i));
        }
Exemple #13
0
        public async Task ThreadCollectionTest()
        {
            var collection = new ThreadCollection(Community.MSDN, "wpdevelop");

            var threads = await collection.NavigateToPageAsync(1);

            Assert.AreEqual(20, threads.Count());
        }
        public void RemoveTestNullThreadToRemove()
        {
            ThreadCollection tc             = new ThreadCollection();
            GThreadMock      threadToRemove = null;

            tc.Remove(threadToRemove);

            // if we get this far then there was no exception so we are happy
            Assert.IsTrue(true);
        }
Exemple #15
0
		/// <summary>
		/// Updates the user/forum/thread statistics after a message insert. Also makes sure if the thread isn't in a queue and the forum has a default support
		/// queue that the thread is added to that queue
		/// </summary>
		/// <param name="threadID">The thread ID.</param>
		/// <param name="userID">The user ID.</param>
		/// <param name="transactionToUse">The transaction to use.</param>
		/// <param name="postingDate">The posting date.</param>
		/// <param name="addToQueueIfRequired">if set to true, the thread will be added to the default queue of the forum the thread is in, if the forum
		/// has a default support queue and the thread isn't already in a queue.</param>
		/// <remarks>Leaves the passed in transaction open, so it doesn't commit/rollback, it just performs a set of actions inside the
		/// passed in transaction.</remarks>
		internal static void UpdateStatisticsAfterMessageInsert(int threadID, int userID, Transaction transactionToUse, DateTime postingDate, bool addToQueueIfRequired, bool subscribeToThread)
		{
			// user statistics
			UserEntity userUpdater = new UserEntity();
			// set the amountofpostings field to an expression so it will be increased with 1. 
			userUpdater.Fields[(int)UserFieldIndex.AmountOfPostings].ExpressionToApply = (UserFields.AmountOfPostings + 1);
			UserCollection users = new UserCollection();
			transactionToUse.Add(users);
			users.UpdateMulti(userUpdater, (UserFields.UserID == userID));	// update directly on the DB. 

			// thread statistics
			ThreadEntity threadUpdater = new ThreadEntity();
			threadUpdater.ThreadLastPostingDate = postingDate;
			threadUpdater.MarkedAsDone = false;
			ThreadCollection threads = new ThreadCollection();
			transactionToUse.Add(threads);
			threads.UpdateMulti(threadUpdater, (ThreadFields.ThreadID == threadID));

			// forum statistics. Load the forum from the DB, as we need it later on. Use a fieldcompareset predicate to fetch the forum as we don't know the 
			// forumID as we haven't fetched the thread
			ForumCollection forums = new ForumCollection();
			transactionToUse.Add(forums);
			// use a fieldcompare set predicate to select the forumid based on the thread. This filter is equal to
			// WHERE ForumID == (SELECT ForumID FROM Thread WHERE ThreadID=@ThreadID)
			var forumFilter = new FieldCompareSetPredicate(
								ForumFields.ForumID, ThreadFields.ForumID, SetOperator.Equal, (ThreadFields.ThreadID == threadID));
			forums.GetMulti(forumFilter);
			ForumEntity containingForum = null;
			if(forums.Count>0)
			{
				// forum found. There's just one.
				containingForum = forums[0];
				containingForum.ForumLastPostingDate = postingDate;
				// save the forum. Just save the collection
				forums.SaveMulti();
			}

			if(addToQueueIfRequired)
			{
				// If the thread involved isn't in a queue, place it in the default queue of the forum (if applicable)
				SupportQueueEntity containingQueue = SupportQueueGuiHelper.GetQueueOfThread(threadID, transactionToUse);
				if((containingQueue == null) && (containingForum != null) && (containingForum.DefaultSupportQueueID.HasValue))
				{
					// not in a queue, and the forum has a default queue. Add the thread to the queue of the forum
					SupportQueueManager.AddThreadToQueue(threadID, containingForum.DefaultSupportQueueID.Value, userID, transactionToUse);
				}
			}

            //subscribe to thread if indicated
            if(subscribeToThread)
            {
				UserManager.AddThreadToSubscriptions(threadID, userID, transactionToUse);
            }
		}
Exemple #16
0
        // *********************************************************************
        //  Initializeskin
        //
        /// <summary>
        /// Initialize the control template and populate the control with values
        /// </summary>
        // ***********************************************************************/
        override protected void InitializeSkin(Control skin)
        {
            // Find the thread tracking thread list control
            threadTracking = (ThreadList)skin.FindControl("ThreadTracking");
            if (null != threadTracking)
            {
                ThreadCollection trackedThreads = Threads.GetThreadsUserIsTracking(ForumUser.Username);

                if (trackedThreads.Count > 0)
                {
                    threadTracking.DataSource = trackedThreads;
                    threadTracking.DataBind();
                }
                else
                {
                    threadTracking.Visible = false;
                    Label label = (Label)skin.FindControl("NoTrackedThreads");
                    if (null != label)
                    {
                        label.Visible = true;
                    }
                }
            }

            // Find the participated threads control
            participatedThreads = (ThreadList)skin.FindControl("ParticipatedThreads");
            if (null != participatedThreads)
            {
                ThreadCollection participatedInThreads = Threads.GetThreadsUserMostRecentlyParticipatedIn(ForumUser.Username);

                if (participatedInThreads.Count > 0)
                {
                    participatedThreads.DataSource = participatedInThreads;
                    participatedThreads.DataBind();
                }
                else
                {
                    participatedThreads.Visible = false;
                    Label label = (Label)skin.FindControl("NoParticipatedThreads");
                    if (null != label)
                    {
                        label.Visible = true;
                    }
                }
            }


            // Find the search link
            search = (HyperLink)skin.FindControl("FindMorePosts");
            if (null != search)
            {
                search.NavigateUrl = Globals.UrlSearchForPostsByUser + ForumUser.Username;
            }
        }
        /// <summary>
        /// Dispose the Listener.
        /// </summary>
        public void Dispose()
        {
            IsActive = false;

            if (TcpListener != null)
            {
                TcpListener.Stop();
            }

            ThreadCollection.Dispose();

            Core.Logger.Log("Pokemon 3D Listener Disposed.", Logger.LogTypes.Info);
        }
        /// <summary>
        /// New Networking
        /// </summary>
        /// <param name="IPAddress">IPAddress</param>
        /// <param name="Password">Password</param>
        /// <param name="Port">Port</param>
        public Listener(string IPAddress, string Password, int Port)
        {
            this.IPAddress = IPAddress;
            this.Password  = Password;
            this.Port      = Port;

            Thread Thread = new Thread(new ThreadStart(ThreadStartListening))
            {
                IsBackground = true
            };

            Thread.Start();
            ThreadCollection.Add(Thread);
        }
        private void RenderPostsMenu()
        {
            ThreadCollection posts    = Threads.GetAllThreads(Post.ForumID, 20, 0, DateTime.MinValue, Context.User.Identity.Name, false);
            string           postMenu = "<div class='popupMenu' style='position: absolute; display: none;' id='" + this.UniqueID + ":postMenu'>";

            postMenu += "<div class='popupTitle'>Posts</div>";
            for (int i = 0; i < posts.Count && i < 20; i++)
            {
                postMenu += "<div class='popupItem'> <a href='" + UrlShowPost + ((Post)posts[i]).PostID +
                            "'>" + ((Post)posts[i]).Subject + "</a> </div>";
            }
            postMenu += "</div>";
            Page.RegisterClientScriptBlock(this.UniqueID + ":postMenu", postMenu);
        }
        /// <summary>
        /// Handle Package
        /// </summary>
        /// <param name="p">Package</param>
        public void HandlePackage(Package p)
        {
            if (p.PackageType == (int)Package.PackageTypes.BeginDownloadFile)
            {
                if (p.DataItems[1].ToInt() == 1)
                {
                    Writer = new StreamWriter(Stream);

                    Thread Thread = new Thread(new ThreadStart(GetDownloadSpeed))
                    {
                        IsBackground = true
                    };
                    Thread.Start();
                    ThreadCollection.Add(Thread);
                }

                Download(p);
            }
            else if (p.PackageType == (int)Package.PackageTypes.EndDownloadFile)
            {
                if (CurrentBytes_L == TotalBytes_L)
                {
                    Status = DownloadStatus.Completed.ToString();
                    Speed  = "0 B/s";
                }
                else if (CurrentBytes_L - Encoding.UTF8.GetByteCount(Environment.NewLine.ToCharArray()) == TotalBytes_L)
                {
                    Status = DownloadStatus.Completed.ToString();
                    Speed  = "0 B/s";
                }
                else
                {
                    Status = DownloadStatus.Canceled.ToString();
                }

                Writer.Dispose();

                Core.RCONGUIListener.SentToServer(new Package(Package.PackageTypes.EndDownloadFile, new List <string> {
                    ID.ToString(), Package.EndDownloadFileStatus.DownloadStreamDisposed.ToString()
                }, null));
            }
            else if (p.PackageType == (int)Package.PackageTypes.EndCreateFile)
            {
                Stream.Dispose();

                Core.RCONGUIListener.SentToServer(new Package(Package.PackageTypes.EndCreateFile, new List <string> {
                    ID.ToString(), Package.EndCreateFileStatus.FileStreamDisposed.ToString()
                }, null));
            }
        }
Exemple #21
0
        public void CannotAddThreadTest()
        {
            var resultingList = new ConcurrentBag <int>();

            SetupTest((item) => { resultingList.Add(item); });

            using (threadCollection = new ThreadCollection(new SimpleThreadPoolSettings(1)))
            {
                var addResult = AddThreads(10);

                queue.CompleteAdding();

                Assert.IsFalse(addResult);
            }
        }
Exemple #22
0
        /// <summary>
        /// Deletes the threads matching the passed in filter, inside the transaction specified.
        /// </summary>
        /// <param name="threadFilter">The thread filter.</param>
        /// <param name="trans">The transaction to use.</param>
        private static void DeleteThreads(PredicateExpression threadFilter, Transaction trans)
        {
            // we've to perform a set of actions in a given order to make sure we're not violating FK constraints in the DB.

            // delete messages in thread
            MessageManager.DeleteAllMessagesInThreads(threadFilter, trans);

            // delete bookmarks (if exists) of the threads to be deleted
            BookmarkCollection bookmarks = new BookmarkCollection();

            trans.Add(bookmarks);
            // use again a fieldcompareset predicate
            bookmarks.DeleteMulti(new FieldCompareSetPredicate(BookmarkFields.ThreadID, ThreadFields.ThreadID, SetOperator.In, threadFilter));

            // delete audit info related to this thread. Can't be done directly on the db due to the fact the entities are in a TargetPerEntity hierarchy, which
            // can't be deleted directly on the db, so we've to fetch the entities first.
            AuditDataThreadRelatedCollection threadAuditData = new AuditDataThreadRelatedCollection();

            trans.Add(threadAuditData);
            // use a fieldcompareset predicate filter, based on the threadFilter.
            threadAuditData.GetMulti(new FieldCompareSetPredicate(AuditDataThreadRelatedFields.ThreadID, ThreadFields.ThreadID, SetOperator.In, threadFilter));
            threadAuditData.DeleteMulti();

            // delete support queue thread entity for this thread (if any)
            SupportQueueThreadCollection supportQueueThreads = new SupportQueueThreadCollection();

            trans.Add(supportQueueThreads);
            // use again a fieldcompareset predicate
            supportQueueThreads.DeleteMulti(new FieldCompareSetPredicate(SupportQueueThreadFields.ThreadID, ThreadFields.ThreadID, SetOperator.In, threadFilter));

            // delete threadsubscription entities
            ThreadSubscriptionCollection threadSubscriptions = new ThreadSubscriptionCollection();

            trans.Add(threadSubscriptions);
            // use again a fieldcompareset predicate
            threadSubscriptions.DeleteMulti(new FieldCompareSetPredicate(ThreadSubscriptionFields.ThreadID, ThreadFields.ThreadID, SetOperator.In, threadFilter));

            // delete the threads
            ThreadCollection threads = new ThreadCollection();

            trans.Add(threads);
            // we already have the filter to use, namely the filter passed in.
            threads.DeleteMulti(threadFilter);

            // don't commit the transaction, that's up to the caller.
        }
Exemple #23
0
        public ThreadViewModel(IDataService service, INavigationServiceSignal navService)
        {
            _dataService       = service;
            _navigationService = navService;
            Threads            = new ThreadCollection(service);

            /*Messenger.Default.Register<RefreshThreadMessage>(
             *  this,
             *  async message =>
             *  {
             *
             *      await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
             *      {
             *          Threads.Refresh();
             *          Debug.WriteLine("Thread Refresh");
             *
             *      });
             *
             *
             *  }
             * );*/
        }
        private void ThreadStartListening()
        {
            if (Core.Setting.OfflineMode)
            {
                Core.Logger.Log("Players with offline profile can join the server.", Logger.LogTypes.Info);
            }

            string GameMode = null;

            for (int i = 0; i < Core.Setting.GameMode.Count; i++)
            {
                GameMode += Core.Setting.GameMode[i] + ", ";
            }
            GameMode = GameMode.Remove(GameMode.LastIndexOf(","));

            if (Functions.CheckPortOpen(Core.Setting.Port))
            {
                Core.Logger.Log($"Server started. Players can join using the following address: {Core.Setting.IPAddress}:{Core.Setting.Port.ToString()} (Global), {Functions.GetPrivateIP()}:{Core.Setting.Port.ToString()} (Local) and with the following GameMode: {GameMode}.", Logger.LogTypes.Info);
                ThreadCollection.Add(new ThreadStart(ThreadPortCheck));
            }
            else
            {
                Core.Logger.Log($"The specific port {Core.Setting.Port.ToString()} is not opened. External/Global IP will not accept new players.", Logger.LogTypes.Info);
                Core.Logger.Log($"Server started. Players can join using the following address: {Functions.GetPrivateIP()}:{Core.Setting.Port.ToString()} (Local) and with the following GameMode: {GameMode}.", Logger.LogTypes.Info);
            }

            Core.Logger.Log("Pokémon 3D Listener initialized.", Logger.LogTypes.Info);

            do
            {
                try
                {
                    ThreadPool.QueueWorkItem(new Action <TcpClient>(ThreadAcceptTcpClient), TcpListener.AcceptTcpClient());
                }
                catch (ThreadAbortException) { return; }
                catch (Exception) { }
            } while (IsActive);
        }
        public void RemoveTestRemoveExistingDeadOrFinishedThread()
        {
            ThreadCollection tc = new ThreadCollection();
            GThreadMock      threadToRemove1 = new GThreadMock();
            GThreadMock      threadToRemove2 = new GThreadMock();

            tc.Add(threadToRemove1);
            tc.Add(threadToRemove2);

            Assert.AreEqual(2, tc.Count);

            threadToRemove1.SetState(ThreadState.Dead);
            threadToRemove2.SetState(ThreadState.Finished);

            tc.Remove(threadToRemove1);

            // the thread should have been removed
            Assert.AreEqual(1, tc.Count);

            tc.Remove(threadToRemove2);

            // the thread should have been removed
            Assert.AreEqual(0, tc.Count);
        }
Exemple #26
0
        public void Dispose()
        {
            IsActive = false;

            Listener?.Stop();

            for (int i = 0; i < ThreadCollection.Count; i++)
            {
                if (ThreadCollection[i].IsAlive)
                {
                    ThreadCollection[i].Abort();
                }
            }
            ThreadCollection.RemoveRange(0, ThreadCollection.Count);

            for (int i = 0; i < Clients.Count; i++)
            {
                Clients[i].Dispose();
            }

            Clients.Clear();

            Core.Logger.Log("SCON Listener Disposed.", Logger.LogTypes.Info);
        }
		internal Process(NDebugger debugger, ICorDebugProcess corProcess, string workingDirectory)
		{
			this.debugger = debugger;
			this.corProcess = corProcess;
			this.workingDirectory = workingDirectory;
			
			this.callbackInterface = new ManagedCallback(this);
			
			activeEvals = new EvalCollection(debugger);
			modules = new ModuleCollection(debugger);
			modules.Added += OnModulesAdded;
			threads = new ThreadCollection(debugger);
			appDomains = new AppDomainCollection(debugger);
		}
Exemple #28
0
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        /// <remarks>
        /// Call one of the Initialize methods directly after creating a Thread instance.
        /// 
        /// Code that normally would be present in the constructor.
        /// This code is however put in a separate method to be able to have only
        /// one constructor in DicomThread. This way, it is easier to derive from a
        /// DicomThread class.
        /// 
        /// Use this method if this object should have a parent thread.
        /// </remarks>
        /// <param name="parent">The parent Thread.</param>
        protected void Initialize(Thread parent)
        {
            this.parent = parent;
            this.dotNetThread = new System.Threading.Thread(new System.Threading.ThreadStart(this.ThreadEntryPoint));
            this.threadManager = this.parent.ThreadManager;
            this.topmostThread = this.parent.TopmostThread;

            // See property ThreadManagerLock when to use this lock.
            lock (this.threadManager.ThreadManagerLock)
            {
                this.childs = new ThreadCollection();
                this.parent.childs.Add(this);
                this.threadManager.AddThread(this);
            }

            if (this.parent.ThreadOptions.AttachChildsToUserInterfaces)
            {
                foreach (IThreadUserInterface threadUserInterface in this.parent.AttachedUserInterfaces)
                {
                    threadUserInterface.Attach(this);
                }
            }
        }
Exemple #29
0
        /// <summary>
        /// Deletes the user with the ID passed in. Will reset all posts made by the user to the userid 0.
        /// </summary>
        /// <param name="userID">The user ID.</param>
        /// <remarks>Can't delete user 0</remarks>
        /// <returns>true if succeeded, false otherwise</returns>
        public static bool DeleteUser(int userID)
        {
            if (userID == 0)
            {
                // can't delete the Anonymous coward user.
                return(false);
            }

            UserEntity toDelete = UserGuiHelper.GetUser(userID);

            if (toDelete == null)
            {
                // user doesn't exist
                return(false);
            }

            // all actions have to take place in a transaction.
            Transaction trans = new Transaction(IsolationLevel.ReadCommitted, "DeleteUser");

            try
            {
                // we'll first update all PostedByUserId fields of all messages which are posted by the user to delete.
                MessageEntity messageUpdater = new MessageEntity();
                messageUpdater.PostedByUserID = 0;      // reset to AC.
                MessageCollection messages = new MessageCollection();
                trans.Add(messages);                    // add to the transaction
                // update all entities directly in the DB, which match the following filter and update them with the new values set in messageUpdater.
                messages.UpdateMulti(messageUpdater, (MessageFields.PostedByUserID == userID));

                // set the startuser of threads started by this user to 0
                ThreadEntity threadUpdater = new ThreadEntity();
                threadUpdater.StartedByUserID = 0;
                ThreadCollection threads = new ThreadCollection();
                trans.Add(threads);
                threads.UpdateMulti(threadUpdater, (ThreadFields.StartedByUserID == userID));

                // remove the user from the UserRoles set, as the user shouldn't be in any roles.
                RoleUserCollection roleUsersDeleter = new RoleUserCollection();
                trans.Add(roleUsersDeleter);
                // delete all entities directly from the DB which match the following filter.
                roleUsersDeleter.DeleteMulti(RoleUserFields.UserID == userID);

                // delete all bookmarks of user
                BookmarkCollection bookmarkDeleter = new BookmarkCollection();
                trans.Add(bookmarkDeleter);
                // delete all bookmarks for this user directly from the DB using the following filter.
                bookmarkDeleter.DeleteMulti(BookmarkFields.UserID == userID);

                // delete all audit data
                AuditDataCoreCollection auditDataDeleter = new AuditDataCoreCollection();
                // first fetch it, then delete all entities from the collection, as the audit data is in an inheritance hierarchy of TargetPerEntity which can't
                // be deleted directly from the db.
                trans.Add(auditDataDeleter);
                auditDataDeleter.GetMulti(AuditDataCoreFields.UserID == userID);
                auditDataDeleter.DeleteMulti();

                // set IP bans set by this user to userid 0
                IPBanEntity ipbanUpdater = new IPBanEntity();
                ipbanUpdater.IPBanSetByUserID = 0;
                IPBanCollection ipBans = new IPBanCollection();
                trans.Add(ipBans);
                ipBans.UpdateMulti(ipbanUpdater, (IPBanFields.IPBanSetByUserID == userID));

                // delete threadsubscriptions
                ThreadSubscriptionCollection threadSubscriptionsDeleter = new ThreadSubscriptionCollection();
                trans.Add(threadSubscriptionsDeleter);
                threadSubscriptionsDeleter.DeleteMulti(ThreadSubscriptionFields.UserID == userID);

                // remove supportqueuethread claims
                SupportQueueThreadCollection supportQueueThreads = new SupportQueueThreadCollection();
                trans.Add(supportQueueThreads);
                supportQueueThreads.DeleteMulti(SupportQueueThreadFields.ClaimedByUserID == userID);

                // set all placed in queue references to userid 0, so the threads stay in the queues.
                SupportQueueThreadEntity supportQueueThreadUpdater = new SupportQueueThreadEntity();
                supportQueueThreadUpdater.PlacedInQueueByUserID = 0;
                supportQueueThreads.UpdateMulti(supportQueueThreadUpdater, (SupportQueueThreadFields.PlacedInQueueByUserID == userID));

                // now delete the actual user entity
                trans.Add(toDelete);
                toDelete.Delete();

                // all done
                trans.Commit();
                return(true);
            }
            catch
            {
                trans.Rollback();
                throw;
            }
            finally
            {
                trans.Dispose();
            }
        }
Exemple #30
0
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        /// <remarks>
        /// Call one of the Initialize methods directly after creating a Thread instance.
        /// 
        /// Code that normally would be present in the constructor.
        /// This code is however put in a separate method to be able to have only
        /// one constructor in DicomThread. This way, it is easier to derive from a
        /// DicomThread class.
        /// 
        /// Use this method if this threads should not have a parent thread.
        /// </remarks>
        /// <param name="threadManager">The ThreadManager that manages this object.</param>
        protected void Initialize(ThreadManager threadManager)
        {
            this.parent = null;
            this.dotNetThread = new System.Threading.Thread(new System.Threading.ThreadStart(this.ThreadEntryPoint));
            this.threadManager = threadManager;
            this.topmostThread = this;

            // See property ThreadManagerLock when to use this lock.
            lock (this.threadManager.ThreadManagerLock)
            {
                this.childs = new ThreadCollection();
                this.threadManager.ChildThreads.Add(this);
                this.threadManager.AddChildThread(this);
            }
        }
Exemple #31
0
        /// <summary>
        /// Deletes the threads matching the passed in filter, inside the transaction specified.
        /// </summary>
        /// <param name="threadFilter">The thread filter.</param>
        /// <param name="trans">The transaction to use.</param>
        private static void DeleteThreads(PredicateExpression threadFilter, Transaction trans)
        {
            // we've to perform a set of actions in a given order to make sure we're not violating FK constraints in the DB.

            // delete messages in thread
            MessageManager.DeleteAllMessagesInThreads(threadFilter, trans);

            // delete bookmarks (if exists) of the threads to be deleted
            BookmarkCollection bookmarks = new BookmarkCollection();
            trans.Add(bookmarks);
            // use again a fieldcompareset predicate
            bookmarks.DeleteMulti(new FieldCompareSetPredicate(BookmarkFields.ThreadID, ThreadFields.ThreadID, SetOperator.In, threadFilter));

            // delete audit info related to this thread. Can't be done directly on the db due to the fact the entities are in a TargetPerEntity hierarchy, which
            // can't be deleted directly on the db, so we've to fetch the entities first.
            AuditDataThreadRelatedCollection threadAuditData = new AuditDataThreadRelatedCollection();
            trans.Add(threadAuditData);
            // use a fieldcompareset predicate filter, based on the threadFilter.
            threadAuditData.GetMulti(new FieldCompareSetPredicate(AuditDataThreadRelatedFields.ThreadID, ThreadFields.ThreadID, SetOperator.In, threadFilter));
            threadAuditData.DeleteMulti();

            // delete support queue thread entity for this thread (if any)
            SupportQueueThreadCollection supportQueueThreads = new SupportQueueThreadCollection();
            trans.Add(supportQueueThreads);
            // use again a fieldcompareset predicate
            supportQueueThreads.DeleteMulti(new FieldCompareSetPredicate(SupportQueueThreadFields.ThreadID, ThreadFields.ThreadID, SetOperator.In, threadFilter));

            // delete threadsubscription entities
            ThreadSubscriptionCollection threadSubscriptions = new ThreadSubscriptionCollection();
            trans.Add(threadSubscriptions);
            // use again a fieldcompareset predicate
            threadSubscriptions.DeleteMulti(new FieldCompareSetPredicate(ThreadSubscriptionFields.ThreadID, ThreadFields.ThreadID, SetOperator.In, threadFilter));

            // delete the threads
            ThreadCollection threads = new ThreadCollection();
            trans.Add(threads);
            // we already have the filter to use, namely the filter passed in.
            threads.DeleteMulti(threadFilter);

            // don't commit the transaction, that's up to the caller.
        }
Exemple #32
0
 public PSPage()
 {
     this.InitializeComponent();
     ThreadCollection = new ThreadCollection();
     PrCk.IsChecked   = true;
 }
 public Jane2ch()
 {
     Threads = new ThreadCollection();
     Categories = new CategoryCollection();
 }
Exemple #34
0
        /// <summary>
        /// Updates the user/forum/thread statistics after a message insert. Also makes sure if the thread isn't in a queue and the forum has a default support
        /// queue that the thread is added to that queue
        /// </summary>
        /// <param name="threadID">The thread ID.</param>
        /// <param name="userID">The user ID.</param>
        /// <param name="transactionToUse">The transaction to use.</param>
        /// <param name="postingDate">The posting date.</param>
        /// <param name="addToQueueIfRequired">if set to true, the thread will be added to the default queue of the forum the thread is in, if the forum
        /// has a default support queue and the thread isn't already in a queue.</param>
        /// <remarks>Leaves the passed in transaction open, so it doesn't commit/rollback, it just performs a set of actions inside the
        /// passed in transaction.</remarks>
        internal static void UpdateStatisticsAfterMessageInsert(int threadID, int userID, Transaction transactionToUse, DateTime postingDate, bool addToQueueIfRequired, bool subscribeToThread)
        {
            // user statistics
            UserEntity userUpdater = new UserEntity();
            // set the amountofpostings field to an expression so it will be increased with 1.
            userUpdater.Fields[(int)UserFieldIndex.AmountOfPostings].ExpressionToApply = (UserFields.AmountOfPostings + 1);
            UserCollection users = new UserCollection();
            transactionToUse.Add(users);
            users.UpdateMulti(userUpdater, (UserFields.UserID == userID));	// update directly on the DB.

            // thread statistics
            ThreadEntity threadUpdater = new ThreadEntity();
            threadUpdater.ThreadLastPostingDate = postingDate;
            threadUpdater.MarkedAsDone = false;
            ThreadCollection threads = new ThreadCollection();
            transactionToUse.Add(threads);
            threads.UpdateMulti(threadUpdater, (ThreadFields.ThreadID == threadID));

            // forum statistics. Load the forum from the DB, as we need it later on. Use a fieldcompareset predicate to fetch the forum as we don't know the
            // forumID as we haven't fetched the thread
            ForumCollection forums = new ForumCollection();
            transactionToUse.Add(forums);
            // use a fieldcompare set predicate to select the forumid based on the thread. This filter is equal to
            // WHERE ForumID == (SELECT ForumID FROM Thread WHERE ThreadID=@ThreadID)
            var forumFilter = new FieldCompareSetPredicate(
                                ForumFields.ForumID, ThreadFields.ForumID, SetOperator.Equal, (ThreadFields.ThreadID == threadID));
            forums.GetMulti(forumFilter);
            ForumEntity containingForum = null;
            if(forums.Count>0)
            {
                // forum found. There's just one.
                containingForum = forums[0];
                containingForum.ForumLastPostingDate = postingDate;
                // save the forum. Just save the collection
                forums.SaveMulti();
            }

            if(addToQueueIfRequired)
            {
                // If the thread involved isn't in a queue, place it in the default queue of the forum (if applicable)
                SupportQueueEntity containingQueue = SupportQueueGuiHelper.GetQueueOfThread(threadID, transactionToUse);
                if((containingQueue == null) && (containingForum != null) && (containingForum.DefaultSupportQueueID.HasValue))
                {
                    // not in a queue, and the forum has a default queue. Add the thread to the queue of the forum
                    SupportQueueManager.AddThreadToQueue(threadID, containingForum.DefaultSupportQueueID.Value, userID, transactionToUse);
                }
            }

            //subscribe to thread if indicated
            if(subscribeToThread)
            {
                UserManager.AddThreadToSubscriptions(threadID, userID, transactionToUse);
            }
        }
Exemple #35
0
 public ThreadUpdater(ThreadCollection threads, Predicate<Thread> updateable)
 {
     this.threads = threads;
     this.updateable = updateable;
 }
Exemple #36
0
 public ImageDownloader(ThreadCollection threads)
     : this(threads, thread => thread.Downloadable && (thread.QuickDownloading & QuickDownloadState.Selected) != QuickDownloadState.Selected)
 {
     this.threads = threads;
 }
Exemple #37
0
 public ThreadUpdater(ThreadCollection threads)
     : this(threads, thread => (thread.QuickDownloading & QuickDownloadState.Selected) != QuickDownloadState.Selected &&
         !thread.Header.IsPastlog && !thread.Header.IsLimitOverThread)
 {
 }
Exemple #38
0
 public ImageDownloader(ThreadCollection threads, Predicate<Thread> downloadable)
 {
     this.threads = threads;
     this.downloadable = downloadable;
 }
        private void ThreadStartListening()
        {
            try
            {
                Core.Logger.Log($"Connecting to the specified server... Please wait.", Logger.LogTypes.Info);

                Client = new TcpClient();

                if (!Client.ConnectAsync(IPAddress, Port).Wait(5000))
                {
                    Core.Logger.Log(Core.Setting.Token("RCON_CONNECTFAILED"), Logger.LogTypes.Info);
                    return;
                }

                Reader = new StreamReader(Client.GetStream());
                Writer = new StreamWriter(Client.GetStream());

                SentToServer(new Package(Package.PackageTypes.Authentication, new List <string> {
                    Password.Md5HashGenerator(), Password.SHA1HashGenerator(), Password.SHA256HashGenerator()
                }, null));

                string ReturnMessage = Reader.ReadLine();

                if (string.IsNullOrEmpty(ReturnMessage))
                {
                    Core.Logger.Log(Core.Setting.Token("RCON_CONNECTFAILED"), Logger.LogTypes.Info);
                    return;
                }
                else
                {
                    Package Package = new Package(ReturnMessage, Client);
                    if (Package.IsValid)
                    {
                        Core.Logger.Log($"Receive: {Package.ToString()}", Logger.LogTypes.Debug, Client);

                        if (Package.DataItems[0] == Package.AuthenticationStatus.AccessGranted.ToString())
                        {
                            Core.Logger.Log($"You are now connected to the server.", Logger.LogTypes.Info);
                            IsActive = true;
                        }
                        else if (Package.DataItems[0] == Package.AuthenticationStatus.AccessDenied.ToString())
                        {
                            Core.Logger.Log(Core.Setting.Token("RCON_CONNECTFAILED"), Logger.LogTypes.Info);
                            return;
                        }
                    }
                    else
                    {
                        Core.Logger.Log(Core.Setting.Token("RCON_CONNECTFAILED"), Logger.LogTypes.Info);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                ex.CatchError();
                Core.Logger.Log(Core.Setting.Token("RCON_CONNECTFAILED"), Logger.LogTypes.Info);
                return;
            }

            Thread Thread2 = new Thread(new ThreadStart(ThreadStartPinging))
            {
                IsBackground = true
            };

            Thread2.Start();
            ThreadCollection.Add(Thread2);

            do
            {
                try
                {
                    ThreadPool.QueueWorkItem(new WorkItemCallback(ThreadPreHandlePackage), Reader.ReadLine());
                }
                catch (Exception) { }
            } while (IsActive);
        }
Exemple #40
0
		/// <summary>
		/// Constructs a TypedList with all the messages in the thread given. Poster info is included, so the
		/// returned dataview is bindable at once to the message list repeater.
		/// </summary>
		/// <param name="threadID">ID of Thread which messages should be returned</param>
		/// <param name="pageNo">The page no.</param>
		/// <param name="pageSize">Size of the page.</param>
		/// <returns>TypedList with all messages in the thread for the page specified</returns>
		public static MessagesInThreadTypedList GetAllMessagesInThreadAsTypedList(int threadID, int pageNo, int pageSize)
		{
			// we'll use a typedlist, MessagesInThread to pull the necessary data from the db. The typedlist contains fields from
			// message, user and usertitle. 
			MessagesInThreadTypedList messages = new MessagesInThreadTypedList(); 

			//create the filter with the threadID passed to the method.
			PredicateExpression filter = new PredicateExpression(MessageFields.ThreadID == threadID);

			// Sort Messages on posting date, ascending, so the first post is located on top. 
			SortExpression sorter = new SortExpression(MessageFields.PostingDate.Ascending());

			// fetch the data into the typedlist. Pass in the paging information as well, to perform server-side paging. 
			messages.Fill(0, sorter, true, filter, null, null, pageNo, pageSize);

			// update thread entity directly inside the DB with a non-transactional update statement so the # of views is increased by one.
			ThreadEntity updater = new ThreadEntity();
			// set the NumberOfViews field to an expression which increases it by 1
			updater.Fields[(int)ThreadFieldIndex.NumberOfViews].ExpressionToApply = (ThreadFields.NumberOfViews + 1);
			updater.IsNew = false;

			// update the entity directly, and filter on the PK
			ThreadCollection threads = new ThreadCollection();
			threads.UpdateMulti(updater, (ThreadFields.ThreadID == threadID));
			
			// return the constructed typedlist
			return messages;
		}
Exemple #41
0
        /// <summary>
        /// Deletes the user with the ID passed in. Will reset all posts made by the user to the userid 0. 
        /// </summary>
        /// <param name="userID">The user ID.</param>
        /// <remarks>Can't delete user 0</remarks>
        /// <returns>true if succeeded, false otherwise</returns>
        public static bool DeleteUser(int userID)
        {
            if(userID == 0)
            {
                // can't delete the Anonymous coward user.
                return false;
            }

            UserEntity toDelete = UserGuiHelper.GetUser(userID);
            if(toDelete==null)
            {
                // user doesn't exist
                return false;
            }

            // all actions have to take place in a transaction.
            Transaction trans = new Transaction(IsolationLevel.ReadCommitted, "DeleteUser");

            try
            {
                // we'll first update all PostedByUserId fields of all messages which are posted by the user to delete.
                MessageEntity messageUpdater = new MessageEntity();
                messageUpdater.PostedByUserID = 0;	// reset to AC.
                MessageCollection messages = new MessageCollection();
                trans.Add(messages);	// add to the transaction
                // update all entities directly in the DB, which match the following filter and update them with the new values set in messageUpdater.
                messages.UpdateMulti(messageUpdater, (MessageFields.PostedByUserID == userID));

                // set the startuser of threads started by this user to 0
                ThreadEntity threadUpdater = new ThreadEntity();
                threadUpdater.StartedByUserID = 0;
                ThreadCollection threads = new ThreadCollection();
                trans.Add(threads);
                threads.UpdateMulti(threadUpdater, (ThreadFields.StartedByUserID == userID));

                // remove the user from the UserRoles set, as the user shouldn't be in any roles.
                RoleUserCollection roleUsersDeleter = new RoleUserCollection();
                trans.Add(roleUsersDeleter);
                // delete all entities directly from the DB which match the following filter.
                roleUsersDeleter.DeleteMulti(RoleUserFields.UserID == userID);

                // delete all bookmarks of user
                BookmarkCollection bookmarkDeleter = new BookmarkCollection();
                trans.Add(bookmarkDeleter);
                // delete all bookmarks for this user directly from the DB using the following filter.
                bookmarkDeleter.DeleteMulti(BookmarkFields.UserID == userID);

                // delete all audit data
                AuditDataCoreCollection auditDataDeleter = new AuditDataCoreCollection();
                // first fetch it, then delete all entities from the collection, as the audit data is in an inheritance hierarchy of TargetPerEntity which can't
                // be deleted directly from the db.
                trans.Add(auditDataDeleter);
                auditDataDeleter.GetMulti(AuditDataCoreFields.UserID == userID);
                auditDataDeleter.DeleteMulti();

                // set IP bans set by this user to userid 0
                IPBanEntity ipbanUpdater = new IPBanEntity();
                ipbanUpdater.IPBanSetByUserID = 0;
                IPBanCollection ipBans = new IPBanCollection();
                trans.Add(ipBans);
                ipBans.UpdateMulti(ipbanUpdater, (IPBanFields.IPBanSetByUserID == userID));

                // delete threadsubscriptions
                ThreadSubscriptionCollection threadSubscriptionsDeleter = new ThreadSubscriptionCollection();
                trans.Add(threadSubscriptionsDeleter);
                threadSubscriptionsDeleter.DeleteMulti(ThreadSubscriptionFields.UserID == userID);

                // remove supportqueuethread claims
                SupportQueueThreadCollection supportQueueThreads = new SupportQueueThreadCollection();
                trans.Add(supportQueueThreads);
                supportQueueThreads.DeleteMulti(SupportQueueThreadFields.ClaimedByUserID == userID);

                // set all placed in queue references to userid 0, so the threads stay in the queues.
                SupportQueueThreadEntity supportQueueThreadUpdater = new SupportQueueThreadEntity();
                supportQueueThreadUpdater.PlacedInQueueByUserID=0;
                supportQueueThreads.UpdateMulti(supportQueueThreadUpdater, (SupportQueueThreadFields.PlacedInQueueByUserID == userID));

                // now delete the actual user entity
                trans.Add(toDelete);
                toDelete.Delete();

                // all done
                trans.Commit();
                return true;
            }
            catch
            {
                trans.Rollback();
                throw;
            }
            finally
            {
                trans.Dispose();
            }
        }