public ThreadsWindow(int processId) { InitializeComponent(); model = new ThreadModel(); model.GetAllProcessThreads(processId); threadSource.ItemsSource = model.GetThreadsList(); }
public ThreadModel GetThreadByThreadID(int threadId) { ThreadModel thread = new ThreadModel(); try { using (SqlConnection conn = new SqlConnection(ConnectionString)) { conn.Open(); string sql = "Select threads.threadID, threads.userID, threads.categoryID, threads.threadName, threads.threadDate, users.username from threads join users on users.userID = threads.userID where threadID = @threadID"; SqlCommand cmd2 = new SqlCommand(sql, conn); cmd2.Parameters.AddWithValue("@threadID", threadId); SqlDataReader reader = cmd2.ExecuteReader(); while (reader.Read()) { thread.ThreadID = Convert.ToInt32(reader["threadID"]); thread.UserID = Convert.ToInt32(reader["userID"]); thread.CategoryID = Convert.ToInt32(reader["categoryID"]); thread.ThreadName = Convert.ToString(reader["threadName"]); thread.Username = Convert.ToString(reader["username"]); thread.ThreadDate = Convert.ToDateTime(reader["threadDate"]); } return(thread); } } catch (SqlException e) { Console.WriteLine(e.Message); throw; } }
public ActionResult ViewAllThreads(ThreadModel thread) { //put threads in thread db table into a list for each class threadList.Clear(); foreach (var x in db.Thread) { if (x.ClassID == thread.ClassID) { threadList.Add(x); } } //validate the class exists and redirect if not var dbToList = db.Thread.ToList(); while (!dbToList.Exists(x => x.ClassID == thread.ClassID)) { return(View("Index")); } if (threadList == null) { return(RedirectToAction("Index")); } return(RedirectToAction("ClassThreads")); }
private async Task RunPrio() { while (ThreadCollection.RunningThreads.Count != 0) { lock (mutex) { ThreadCollection.RunningThreads.Sort(); Current = ThreadCollection.RunningThreads.FirstOrDefault(); Current.ProcState = ThreadModel.State.RUNNING; } await Task.Delay(100); lock (mutex) { if (Current.ProcState == ThreadModel.State.BLOCKED) { continue; } Current.Priority -= 3; Current.Value++; if (Current.Value == Current.AllocTime) { Current.ProcState = ThreadModel.State.FINISHED; Current.Color = "Red"; ThreadCollection.RunningThreads.Remove(Current); var item = ProgressBars.Items; continue; } Current.ProcState = ThreadModel.State.READY; } } }
public ThreadShould() { var conf = this.mockConfig.GetAdminSettings(); this.repo = new MockRepository(MockBehavior.Strict); this.cookieStorage = this.repo.Create <ICookieStorage>(); this.getIp = this.repo.Create <IGetIp>(); this.threadService = this.repo.Create <IThreadService>(); this.postService = this.repo.Create <IPostService>(); this.bannedImageLogger = this.repo.Create <IBannedImageLogger>(); this.iIsAdmin = this.repo.Create <IIsAdmin>(); this.uploadMapper = new UploadMapper(new ThumbNailer.ThumbNailer(this.mockConfig.GetThumbNailerSettings())); this.thread = new ThreadModel( new IpHasherFactory(this.mockConfig.GetHasherSettings()), new TripCodeHasher(this.mockConfig.GetTripCodeHasherSettings()), this.cookieStorage.Object, this.getIp.Object, this.threadService.Object, this.postService.Object, this.bannedImageLogger.Object, this.iIsAdmin.Object, this.uploadMapper) { PageContext = new Microsoft.AspNetCore.Mvc.RazorPages.PageContext(), }; }
private static void MapThread(ThreadModel threadModel, DbThread thread) { threadModel.Id = thread.ThreadId; threadModel.Viewed = thread.Viewed; threadModel.NewPostCount = thread.NewPostCount; threadModel.PostCount = thread.PostCount; }
// MainThread code can call everything, AllowEveryCaller code can be called by // everything, SingleThread can call SingleThread/Serializable/Concurrent, and Serializable/ // Concurrent can call Serializable/Concurrent. static bool IsValidCall(ThreadModel caller, ThreadModel target) { // MainThread code can call everything if (caller.Is(ThreadModel.MainThread)) { return(true); } // AllowEveryCaller code can be called by everything else if (target.AllowsEveryCaller()) { return(true); } // SingleThread can call SingleThread/Serializable/Concurrent else if (caller.Is(ThreadModel.SingleThread) && (target.Is(ThreadModel.SingleThread) || target.Is(ThreadModel.Serializable) || target.Is(ThreadModel.Concurrent))) { return(true); } // Serializable/Concurrent can call Serializable/Concurrent else if ((caller.Is(ThreadModel.Serializable) || caller.Is(ThreadModel.Concurrent)) && (target.Is(ThreadModel.Serializable) || target.Is(ThreadModel.Concurrent))) { return(true); } return(false); }
public static void DoWork(FileInfo fileInfo) { Dictionary <string, int> longestWords = new Dictionary <string, int>(); ThreadModel threadModel = new ThreadModel(fileInfo); using (FileStream fs = File.Open(threadModel.fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (BufferedStream bs = new BufferedStream(fs)) { using (StreamReader sr = new StreamReader(bs)) { string line; while ((line = sr.ReadLine()) != null) { lock (locker) { DictionaryUpdater.AppendDictionary(longestWords, WordFinder.FindLongestWord(line, 10)); } } } } } DictionaryUpdater.MergeTwoDictionary(ref ThreadModel.generalDictionary, longestWords); }
async Task IMiddleware.OnTurnAsync(ITurnContext turnContext, NextDelegate next, CancellationToken cancellationToken) { var thread = new ThreadModel(turnContext, codeModel); arenas.Add(thread); threads.Add(thread); threadByTurnId.TryAdd(TurnIdFor(turnContext), thread); try { thread.Run.Post(Phase.Started); await UpdateThreadPhaseAsync(thread, null, cancellationToken).ConfigureAwait(false); IDialogDebugger trace = this; turnContext.TurnState.Add(trace); await next(cancellationToken).ConfigureAwait(false); } finally { thread.Run.Post(Phase.Exited); await UpdateThreadPhaseAsync(thread, null, cancellationToken).ConfigureAwait(false); threadByTurnId.TryRemove(TurnIdFor(turnContext), out var ignored); threads.Remove(thread); arenas.Remove(thread); } }
public async Task <ThreadModel> AddThread(ThreadModel thread) { var added = db.Threads.Add(thread); await db.SaveChangesAsync(); return(added); }
//To view ONE thread public IActionResult Index(int?id) { //get the id of the thread var thread = _service.GetById(id); if (thread == null) { return(NotFound()); //if the thread number does not exist then not found } //make a list of users that liked the thread var listOfLikes = _service.ListOfLikes(id); //get the list of reports var numberOfReports = _service.ListOfReports(id).Count(); var tags = _service.GetThreadTags(thread); //make a view model for the thread var model = new ThreadModel { Id = thread.ID, AuthorId = thread.UserID, AuthorUserName = thread.UserName, Created = thread.CreateDate, Description = thread.Description, Picture = thread.Image, Title = thread.Title, Rating = listOfLikes.Count(), LikedBy = listOfLikes, NoReports = numberOfReports, Tags = tags, Lat = thread.Lat, Lng = thread.Lng }; return(View(model)); }
private ulong EncodeFrame(ThreadModel thread, ICodePoint frame) { var threadCode = threads[thread]; var valueCode = thread.FrameCodes.Add(frame); return(Identifier.Encode(threadCode, valueCode)); }
private async Task RunRR() { while (ThreadCollection.RunningThreads.Count != 0) { lock (mutex) { Current = ThreadCollection.RunningThreads.FirstOrDefault(); Current.ProcState = ThreadModel.State.RUNNING; } await Task.Delay(100); lock (mutex) { if (Current.ProcState == ThreadModel.State.BLOCKED) { continue; } Current.Value++; ThreadCollection.RunningThreads.Remove(Current); if (Current.Value == Current.AllocTime) { Current.ProcState = ThreadModel.State.FINISHED; Current.Color = "Red"; continue; } Current.ProcState = ThreadModel.State.READY; ThreadCollection.RunningThreads.Add(Current); } } }
//add thread to threads table given name and description public async Task <bool> AddThread(ThreadModel thread) { await Db.Connection.ChangeDataBaseAsync("posts"); using (var cmd = Db.Connection.CreateCommand()) { //create SQL query to insert thread into threads table cmd.CommandText = "INSERT INTO threads (name, description)" + "VALUES (@name, @description)"; cmd.Parameters.AddWithValue("@name", thread.name); cmd.Parameters.AddWithValue("@description", thread.description); //try to execute query, return true if it works, false otherwise try { await cmd.ExecuteNonQueryAsync(); return(true); } catch (Exception) { return(false); } } }
public ActionResult SendMessage(FormCollection collection, string item) { try { MessageModel message = (MessageModel)Session["Message"]; var msgThread = new ThreadModel() { Message = collection.Get("Message"), MessageModelId = message.Id, Author = db.Users.Find(User.Identity.Name), Date = DateTime.Now }; message.Subject = collection.Get("Subject"); message.isRead = false; db.Messages.Add(message); db.Threads.Add(msgThread); db.SaveChanges(); } catch (Exception ex) { ErrorMessage.ErrorCode = ErrorCode.UNKNOWN; return(View("ErrorMessage", ErrorMessage)); } return(RedirectToAction("Details", "Item", new { id = item })); }
public bool SubmitThread(ThreadModel thread) { int rowsAffected = 0; try { using (SqlConnection conn = new SqlConnection(ConnectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("Insert into threads Values (@userID, @categoryID, @threadName, @threadDate);", conn); cmd.Parameters.AddWithValue("@userID", thread.UserID); cmd.Parameters.AddWithValue("@categoryID", thread.CategoryID); cmd.Parameters.AddWithValue("@threadName", thread.ThreadName); cmd.Parameters.AddWithValue("@threadDate", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")); rowsAffected = cmd.ExecuteNonQuery(); } } catch (SqlException e) { Console.WriteLine(e.Message); throw; } return(rowsAffected > 0); }
public ThreadView() { this.InitializeComponent(); CurrentPage = 1; appBar.Width = ActualWidth; btnPopupPostMessage.IsEnabled = false; BtnRating.IsEnabled = false; comment.IsEnabled = false; bookMark = new BookmarkModelData(); helper = new HtmlHelper(); thread = new ThreadModel(); myLogin = new AccountHelper(); define = new DefineEmoticon(); appSetting = new AppSettingModel(); threadController = new ThreadController(); if (Windows.Foundation.Metadata.ApiInformation.IsPropertyPresent("Windows.UI.Xaml.FrameworkElement", "AllowFocusOnInteraction")) { fl_Page.AllowFocusOnInteraction = true; tbMessage.AllowFocusOnInteraction = true; jumpTextBox.AllowFocusOnInteraction = true; getIdthread.AllowFocusOnInteraction = true; } _instance = this; //this.NavigationCacheMode = NavigationCacheMode.Enabled; }
protected override void OnNavigatingFrom(MtNavigatingCancelEventArgs e) { base.OnNavigatingFrom(e); if (e.NavigationMode == NavigationMode.Back) { //mainGridThread.Children.Remove(myWebview); this.NavigationCacheMode = NavigationCacheMode.Disabled; helper = null; bookMark = null; thread = null; myLogin = null; define = null; appSetting = null; threadController = null; myWebview = null; tbMessage.Text = Resource.STR_EMPTY; if (wbPopup != null) { wbPopup.Navigate(new Uri("about:blank")); wbPopup = null; } _instance = null; GC.Collect(); } else { if (wbPopup != null) { wbPopup.Navigate(new Uri("about:blank")); } } }
public string Create(ThreadModel model) { var item = _context.Threads.Add(model); _context.SaveChanges(); return(item.Id); }
public void ThreadMasterTest() { var sut = new ThreadModel(); var expected = "fred"; var actual = sut.ThreadMaster(expected); Assert.True(expected == actual); }
public ActionResult AddAThread(ThreadModel model) { forumDAL.SubmitThread(model); List <ThreadModel> AllThreads = new List <ThreadModel>(); AllThreads = forumDAL.GetThreadsByCategory(model.CategoryID); return(View("ViewThreads", AllThreads)); }
public static ThreadModel ThreadModelFactory(string forumId, string threadId) { XmlNode node = TelligentService.TelligentService.ReadThread(forumId, threadId); ThreadModel th = new ThreadModel(node, Common.Helpers.DataFormatHelper.FormatDate, TelligentService.TelligentService.FormatString100, TelligentService.TelligentService.ReadReplies); return(th); }
// GroupDiscussionList rptGroupDiscussion; protected void Page_Load(object sender, EventArgs e) { lbSubmitReply.Text = DictionaryConstants.SubmitButtonText; // rptGroupDiscussion = (GroupDiscussionList)Page.LoadControl("~/Presentation/Sublayouts/Common/GroupDiscussionList.ascx"); // rptGroupDiscussion.ID = "rptGroupCards"; // plhGroupDiscussions.Controls.Add(rptGroupDiscussion); //if (!IsPostBack) //{ txtBody.Attributes.Add("placeholder", "Join the discussion"); txtBody.Attributes.Add("id", "join-discussion-text"); Item currItem = Sitecore.Context.Item; if (currItem != null) { hrfBack.HRef = LinkManager.GetItemUrl(currItem.Parent); litBack.Text = currItem.Parent.Name; GroupDiscussionItem grpDItem = new GroupDiscussionItem(currItem); if (grpDItem != null) { Session["discussionItem"] = grpDItem; string forumID = grpDItem.ForumID.Text; string threadID = grpDItem.ThreadID.Text; try { ThreadModel thModel = UnderstoodDotOrg.Services.CommunityServices.Threads.ThreadModelFactory(forumID, threadID); //Populate the initial Post ProfileCommentCard.LoadState(thModel.Author); rptGroupDiscussion.DataSource = thModel.Replies; rptGroupDiscussion.DataBind(); if (thModel.Author != null) { ThanksButton.LoadState(thModel.Author.UserName); ThinkingOfYouButton.LoadState(thModel.Author.UserName); } lblSubject.Text = thModel.Subject; litComment.Text = thModel.Body; litNumReplies.Text = thModel.ReplyCount; LikeButton.LoadState(thModel.ContentId, thModel.ContentTypeId); litMemberCount.Text = thModel.Replies.Select(m => m.AuthorName).Distinct().Count().ToString(); } catch (Exception ex) { Sitecore.Diagnostics.Error.LogError("Error Retrieving replies Page_Load Parent Group Discussions.\nError" + ex.Message); } } } //} }
protected void rptThreads_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.DataItem != null) { if (e.Item.DataItem is ThreadModel) { ThreadModel item = (ThreadModel)e.Item.DataItem; Item thread = null; HiddenField hdFrmID = (HiddenField)e.Item.FindControl("forumId"); HiddenField hdThID = (HiddenField)e.Item.FindControl("threadId"); string forumId = String.Empty; string threadId = String.Empty; if (hdFrmID != null && hdThID != null) { forumId = hdFrmID.Value; threadId = hdThID.Value; thread = Threads.ConvertThreadtoSitecoreItem(forumId, threadId); //Sitecore.Context.Database.SelectSingleItem("fast:/sitecore/content/Home//*[@Subject = '" + subject + "']"); // ID = thread.ID.ToString(); } HtmlAnchor hrefDiscussions = (HtmlAnchor)e.Item.FindControl("hrefDiscussion"); if (hrefDiscussions != null) { if (thread != null) { hrefDiscussions.HRef = LinkManager.GetItemUrl(thread); } } HtmlAnchor hrefLastPostUser = (HtmlAnchor)e.Item.FindControl("hrefLastPostUser"); if (hrefLastPostUser != null) { if (thread != null) { hrefLastPostUser.HRef = MembershipHelper.GetPublicProfileUrl(item.LastPostUser); } } Literal litDiscussionLabel = (Literal)e.Item.FindControl("litDiscussionLabel"); if (litDiscussionLabel != null) { litDiscussionLabel.Text = DictionaryConstants.DiscussionLabel; } Literal litRepliesLabel = (Literal)e.Item.FindControl("litRepliesLabel"); if (litRepliesLabel != null) { litRepliesLabel.Text = DictionaryConstants.RepliesLabel; } Literal litLatestPostLabel = (Literal)e.Item.FindControl("litLatestPostLabel"); if (litLatestPostLabel != null) { litLatestPostLabel.Text = DictionaryConstants.LatestPostLabel; } } } }
public async Task <IEnumerable <Post> > GetNewPostsAsync(uint lastId, bool ignoreCache = false) { if (ignoreCache) { _cachedJson = null; } return((await GetNewPostsAsync().ConfigureAwait(false)).SkipWhile(p => p.PostNumber <= lastId)); }
private static void MapPost(ThreadModel threadModel, DbPost post) { // note that we don't map thread id here threadModel.Title = post.Title; threadModel.Excerpt = post.Message; threadModel.UserId = post.UserId; threadModel.Username = post.Username; threadModel.Updated = post.Updated ?? post.Posted; }
private async Task UpdateThreadPhaseAsync(ThreadModel thread, object item, CancellationToken cancellationToken) { var run = thread.Run; if (run.Phase == run.PhaseSent) { return; } var phase = run.Phase; var suffix = item != null ? $" ==> {codeModel.NameFor(item)}" : string.Empty; var threadText = $"{Ellipsis(thread?.Name, 18)}"; if (threadText.Length <= 2) { threadText = thread.TurnContext.Activity.Type; } var description = $"{threadText} ==> {phase.ToString().PadRight(16)}{suffix}"; await OutputAsync(description, item, null, cancellationToken).ConfigureAwait(false); var threadId = this.threads[thread]; if (phase == Phase.Next) { phase = Phase.Continue; } string reason = phase.ToString().ToLower(); if (phase == Phase.Started || phase == Phase.Exited) { await SendAsync(Protocol.Event.From(NextSeq, "thread", new { threadId, reason }), cancellationToken).ConfigureAwait(false); } else if (phase == Phase.Continue) { await SendAsync(Protocol.Event.From(NextSeq, "continued", new { threadId, allThreadsContinued = false }), cancellationToken).ConfigureAwait(false); } else { var body = new { reason, description, threadId, text = description, preserveFocusHint = false, allThreadsStopped = false, }; await SendAsync(Protocol.Event.From(NextSeq, "stopped", body), cancellationToken).ConfigureAwait(false); } run.PhaseSent = run.Phase; }
private static void MapRatings(ThreadModel threadModel, IEnumerable <DbRating> ratings) { threadModel.InterestingCount = ratings.Count(r => r.Value == (int)VoteValue.Interesting); threadModel.ThanksCount = ratings.Count(r => r.Value == (int)VoteValue.Thanks); threadModel.ExcellentCount = ratings.Count(r => r.Value == (int)VoteValue.Excellent); threadModel.AgreedCount = ratings.Count(r => r.Value == (int)VoteValue.Agreed); threadModel.DisagreedCount = ratings.Count(r => r.Value == (int)VoteValue.Disagreed); threadModel.Plus1Count = ratings.Count(r => r.Value == (int)VoteValue.Plus1); threadModel.FunnyCount = ratings.Count(r => r.Value == (int)VoteValue.Funny); }
public IActionResult EditThread(int id) { if (ViewBag.Username == null) { _logger.LogInformation("User tried to edit a thread without being logged in"); TempData["Message"] = "You need to login to edit threads"; return(RedirectToAction("Login", "Account")); } Thread thread = _context.Threads .Include(t => t.User) .SingleOrDefault(t => t.Id == id); if (thread == null) { _logger.LogError($"Thread \"{id}\" that was attempted to get edited " + $"by \"{ViewBag.Username}\" was not found in the database"); TempData["Message"] = "Error: The thread you tried to edit was not found in the database. Try again."; return(RedirectToAction("Index")); } if (ViewBag.RankLevel < 1 && !thread.User.Username.Equals(ViewBag.Username)) { _logger.LogInformation($"User \"{ViewBag.Username}\" tried to edit the thread \"{id}\" " + "without being the author nor having high enough rank"); TempData["Message"] = "You are not the author nor ranked high enough to edit the thread"; return(RedirectToAction("Index")); } List <Tag> tags = _context.Tags.ToList(); List <ThreadTag> threadTags = _context.ThreadTags .Where(tt => tt.ThreadId == id) .Include(tt => tt.Tag) .ToList(); foreach (ThreadTag tt in threadTags) { foreach (Tag t in tags) { if (t.Name.Equals(tt.Tag.Name)) { t.Chosen = true; break; } } } ThreadModel model = new ThreadModel { Id = id, UserId = thread.UserId, Title = thread.Title, Message = thread.Message, CreationTime = thread.CreationTime, Tags = tags }; return(View("Create-Thread", model)); }
public ActionResult Thread(string threadName = null, string themeName = null, int pageIndex = 0) { var messages = GetMessages(threadName, themeName, ref pageIndex); var userName = User.Identity.IsAuthenticated ? User.Identity.Name : ""; var isAdmin = User.Identity.IsAuthenticated && User.IsInRole(Role.Admin.ToString()); var model = new ThreadModel(messages, threadName, themeName, pageIndex, userName, isAdmin); return(View(model)); }
private ThreadModelAttribute BasicCheck (ThreadModel model, bool every) { string name = model.ToString (); ThreadModelAttribute tma = new ThreadModelAttribute (model); Assert.AreEqual (model & ~ThreadModel.AllowEveryCaller, tma.Model, name); Assert.AreEqual (every, tma.AllowsEveryCaller, name + ".AllowsEveryCaller"); Assert.AreEqual (every, tma.ToString ().Contains ("AllowEveryCaller"), "ToString()"); int code = tma.GetHashCode (); tma.AllowsEveryCaller = !tma.AllowsEveryCaller; Assert.AreNotEqual (code, tma.GetHashCode (), name + "!HashCode"); tma.AllowsEveryCaller = !tma.AllowsEveryCaller; return tma; }
void AddThread(Thread thread) { if (thread == null) return; // remove the object if exists RemoveThread(thread); ThreadModel obj = new ThreadModel(thread); runningThreads.Add(obj); thread.Exited += (s, e) => RemoveThread(e.Thread); }
public ThreadModelAttribute(ThreadModel model) { Model = model; }
// MainThread code can call everything, AllowEveryCaller code can be called by // everything, SingleThread can call SingleThread/Serializable/Concurrent, and Serializable/ // Concurrent can call Serializable/Concurrent. static bool IsValidCall (ThreadModel caller, ThreadModel target) { // MainThread code can call everything if (caller.Is (ThreadModel.MainThread)) return true; // AllowEveryCaller code can be called by everything else if (target.AllowsEveryCaller ()) return true; // SingleThread can call SingleThread/Serializable/Concurrent else if (caller.Is (ThreadModel.SingleThread) && (target.Is (ThreadModel.SingleThread) || target.Is (ThreadModel.Serializable) || target.Is (ThreadModel.Concurrent))) return true; // Serializable/Concurrent can call Serializable/Concurrent else if ((caller.Is (ThreadModel.Serializable) || caller.Is (ThreadModel.Concurrent)) && (target.Is (ThreadModel.Serializable) || target.Is (ThreadModel.Concurrent))) return true; return false; }
//[ActionName("create")] public void PostThread_ShouldSaveToDatabase() { var testThread = new ThreadModel() { Title = "Test", Content = "Test", CreatedBy = "Tester", DateCreated = DateTime.Now }; var model = this.PostTestThread(httpServer, testThread); Assert.AreEqual(testThread.Title, model.Title); Assert.IsTrue(model.Id > 0); }
private ThreadModel PostTestThread(InMemoryHttpServer httpServer, ThreadModel testThread) { LoggedUserModel loggedUser = RegisterTestUser(httpServer, testUser); var headers = new Dictionary<string, string>(); headers["X-sessionKey"] = loggedUser.SessionKey; var response = httpServer.Post("api/threads/create", testThread, headers); var contentString = response.Content.ReadAsStringAsync().Result; var threadModel = JsonConvert.DeserializeObject<ThreadModel>(contentString); return threadModel; }