public void AssignUsers(UsersCollection users) { UserscheckedListBox.Items.Clear(); foreach (User user in users) { UserscheckedListBox.Items.Add(user.Userid); } }
private UserAdminUtilities() { Users = new UsersCollection(); Roles = new RolesCollection(); Rights = new RightsCollection(); UserPatterns = new UserPatternCollection(); organizations = new OrganizationCollection(); groups = new GroupCollection(); Desearilize(); }
public void Desearilize() { try { Users = UsersCollection.Desearilize(); Rights = RightsCollection.Desearilize(); Roles = RolesCollection.Desearilize(); UserPatterns = UserPatternCollection.Desearilize(); organizations = OrganizationCollection.Desearilize(); groups = GroupCollection.Desearilize(); } catch { } }
public RedmineServiceContext(Uri serviceUri, string apiKey) { _serviceUri = serviceUri; _apiKey = apiKey; _news = new NewsCollection(this); _projects = new ProjectsCollection(this); _issues = new IssuesCollection(this); _users = new UsersCollection(this); _userRoles = new UserRolesCollection(this); _relations = new IssueRelationsCollection(this); _trackers = new IssueTrackersCollection(this); _statuses = new IssueStatusesCollection(this); _priorities = new IssuePrioritiesCollection(this); _categories = new IssueCategoriesCollection(this); _versions = new ProjectVersionsCollection(this); _attachments = new AttachmentsCollection(this); _customFields = new CustomFieldsCollection(this); _queries = new QueriesCollection(this); _syncRoot = new object(); }
public static List <Tweet> Get(string screenname, ulong maxStatusID) { int fetchMultiplier = int.Parse( !string.IsNullOrEmpty(ConfigurationManager.AppSettings["FetchMultiplier"]) ? ConfigurationManager.AppSettings["FetchMultiplier"] : "10"); List <string> screenNames = new List <string>(); screenNames.AddRange(TwitterModel.Instance.GetRelevantScreenNames(screenname)); List <Tweet> tweets = new List <Tweet>(); screenNames.ForEach(name => { var t = CachedRepository <Tweet> .Instance.Query(name + TwitterModel.TWEETS); if (t != null) { tweets.AddRange(t); } }); if (tweets != null) { tweets = tweets.OrderByDescending(t => t.Status.CreatedAt).ToList(); } if (tweets == null || tweets.Count() < 5 || !tweets.Select(t => t.Status.CreatedAt).IsWithinAverageRecurrenceInterval(multiplier: fetchMultiplier)) { var lastStatusID = (tweets != null && tweets.Count() > 0) ? ulong.Parse(tweets.First().Status.StatusID) : 0; var user = UsersCollection.Single(screenname) ?? UsersCollection.PrimaryUser(); if (user.CanAuthorize) { try { Expression <Func <Status, bool> > where; if (maxStatusID > 0 && lastStatusID > 0) { where = (s => s.MaxID == maxStatusID && s.SinceID == lastStatusID && s.ScreenName == screenname && s.IncludeEntities == true && s.Type == StatusType.User && s.Count == 50); } else if (lastStatusID > 0) { where = (s => s.SinceID == lastStatusID && s.ScreenName == screenname && s.IncludeEntities == true && s.Type == StatusType.Home && s.Count == 200); } else { where = (s => s.ScreenName == screenname && s.IncludeEntities == true && s.Type == StatusType.Home && s.Count == 200); } var statuses = TwitterModel.Instance.GetAuthorizedTwitterContext(user.TwitterScreenName) .Status .Where(where) .ToList(); List <Tweet> results; if (statuses != null && statuses.Count > 0) { results = statuses.Select(s => new Tweet(s)).ToList(); } else { results = null; } return(results); } catch { return(null); } } } return(null); }
public void DropUsers() { UsersCollection.Drop(); }
void GivenThereAreNoUsersInTheUsersCollection() { UsersCollection.Clear(); }
static void Main(string[] args) { if (!EnsureSingleLoad()) { Console.WriteLine("{0}: Another Instance Currently Runing", DateTime.Now); return; } Console.WriteLine("{0}: Started", DateTime.Now); var screenname = UsersCollection.PrimaryUser().TwitterScreenName; var secret = ConfigurationManager.AppSettings["TwitterCustomerSecret"]; HubConnection hubConnection = null; IHubProxy streamingHub = null; while (streamingHubConnectAttempts++ < 3) { if (streamingHubConnectAttempts > 1) { System.Threading.Thread.Sleep(5000); } Console.WriteLine("{0}: Attempting To Connect To PushURL '{1}' (Attempt: {2})", DateTime.Now, ConfigurationManager.AppSettings["PushURL"], streamingHubConnectAttempts); hubConnection = (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["PushURL"])) ? new HubConnection(ConfigurationManager.AppSettings["PushURL"]) : null; if (hubConnection != null) { try { streamingHub = hubConnection.CreateHubProxy("streamingHub"); hubConnection.StateChanged += new Action <Microsoft.AspNet.SignalR.Client.StateChange>(sc => { if (sc.NewState == Microsoft.AspNet.SignalR.Client.ConnectionState.Connected) { Console.WriteLine("{0}: Push Connection Established", DateTime.Now); lock (queue_push_lock) { if (queue_push.Count > 0) { Console.WriteLine("{0}: Pushing {1} Tweets to Web Application", DateTime.Now, queue_push.Count()); streamingHub.Invoke("Send", new StreamItem() { Secret = secret, Data = queue_push }).Wait(); queue_push.Clear(); } } } else if (sc.NewState == Microsoft.AspNet.SignalR.Client.ConnectionState.Disconnected) { Console.WriteLine("{0}: Push Connection Lost", DateTime.Now); } else if (sc.NewState == Microsoft.AspNet.SignalR.Client.ConnectionState.Reconnecting) { Console.WriteLine("{0}: Reestablishing Push Connection", DateTime.Now); } else if (sc.NewState == Microsoft.AspNet.SignalR.Client.ConnectionState.Connecting) { Console.WriteLine("{0}: Establishing Push Connection", DateTime.Now); } }); var startHubTask = hubConnection.Start(); startHubTask.Wait(); if (!startHubTask.IsFaulted) { break; } } catch (Exception ex) { hubConnection = null; Console.WriteLine("{0}: Error: {1}", DateTime.Now, ex.ToString()); } } } Console.WriteLine("{0}: Getting Friends for {1}", DateTime.Now, screenname); TwitterModel.Instance.UpdateFriendsForPrimaryUser(); Console.WriteLine("{0}: Finished Getting Friends for {1}", DateTime.Now, screenname); Console.WriteLine("{0}: Listening to Stream", DateTime.Now); var context = TwitterModel.Instance.GetAuthorizedTwitterContext(screenname); stream = StartTwitterStream(context); queueTimer = new Timer(60000); queueTimer.Elapsed += new ElapsedEventHandler((x, y) => { queueTimer.Enabled = false; try { Console.WriteLine("{0}: Processing Queue", DateTime.Now); lock (queue_lock) { if (queue.Count == 0) { Console.WriteLine("{0}: No Items to Process", DateTime.Now); return; } tweets = new Tweet[queue.Count]; queue.CopyTo(tweets); queue.Clear(); } Console.WriteLine("{0}: Processing {1} Items from Queue", DateTime.Now, tweets.Length); var tp = new TweetProcessor(tweets, true); tp.Start(); tweets .GroupBy(t => t.User.Identifier.ScreenName) .ToList() .ForEach(g => { CachedRepository <Tweet> .Instance.Save(g.Key + TwitterModel.TWEETS, g.OrderBy(t => t.CreatedAt).Select(t => t).ToList()); Console.WriteLine("{0}: {1} Tweets Saved for {2}", DateTime.Now, g.Count(), g.Key); }); //CachedRepository<Tweet>.Instance.FlushChanges(); if (hubConnection != null && streamingHub != null) { int retweetThreshold = UsersCollection.PrimaryUser().RetweetThreshold; tweets = tweets.Where(t => t.RetweetCount >= retweetThreshold).ToArray(); if (hubConnection.State == Microsoft.AspNet.SignalR.Client.ConnectionState.Connected) { if (tweets.Length > 0) { Console.WriteLine("{0}: Pushing {1} Tweets to Web Application", DateTime.Now, tweets.Count()); streamingHub.Invoke("Send", new StreamItem() { Secret = secret, Data = tweets }).Wait(); } } else { lock (queue_push_lock) { queue_push.AddRange(tweets); } } } tweets = null; } catch (Exception ex) { Console.WriteLine("{0}: Error: {1}", DateTime.Now, ex.ToString()); } finally { try { if (Math.Abs((lastCallBackTime - DateTime.Now).TotalSeconds) > 90) //The Stream Stalled or was Closed { if (hadStreamFailure) { Console.WriteLine("{0}: LinqToTwitter UserStream Was Closed Attempting to Reconnect", DateTime.Now); } else { Console.WriteLine("{0}: LinqToTwitter UserStream Stalled Attempting to Restart It", DateTime.Now); } context = TwitterModel.Instance.GetAuthorizedTwitterContext(screenname); stream = StartTwitterStream(context); } } catch (Exception ex) { Console.WriteLine("{0}: Error: {1}", DateTime.Now, ex.ToString()); } queueTimer.Enabled = true; Console.WriteLine("{0}: Completed Processing Queue", DateTime.Now); } }); queueTimer.Start(); /* * It appears like firing off the friends update while running the stream will * cause the stream to stop working. * * var friendTimer = new Timer(3600000); * friendTimer.Elapsed += new ElapsedEventHandler((x, y) => * { * friendTimer.Enabled = false; * try * { * Console.WriteLine("{0}: Getting Friends for {1}", DateTime.Now, screenname); * Friends.Update(); * Console.WriteLine("{0}: Finished Getting Friends for {1}", DateTime.Now, screenname); * } * catch (Exception ex) * { * Console.WriteLine("{0}: Error: {1}", DateTime.Now, ex.ToString()); * } * finally * { * friendTimer.Enabled = true; * } * }); * friendTimer.Start(); */ while (Console.ReadLine() != "exit") { ; } Console.WriteLine("{0}: Exiting", DateTime.Now); stream.CloseStream(); }
/// <summary> /// Deletes a User using its Id. /// </summary> /// <param name="id"></param> public void Delete(string id) { var filterId = Builders <UserModel> .Filter.Eq(x => x.Id, id); UsersCollection.FindOneAndDelete(filterId); }
public void addNewUser(string firstname, string lastname, string username, string email, string password, UserType userType) { User newUser = UsersCollection.CreateNewUser(firstname, lastname, email, username, password, userType); UsersCollection.AddUser(newUser); }
public static UsersCollection GetAll() { resourceSchema.Dal.Users dbo = null; try { dbo = new resourceSchema.Dal.Users(); System.Data.DataSet ds = dbo.Users_Select_All(); UsersCollection collection = new UsersCollection(); if (GlobalTools.IsSafeDataSet(ds)) { for (int i = 0; (i < ds.Tables[0].Rows.Count); i = (i + 1)) { Users obj = new Users(); obj.Fill(ds.Tables[0].Rows[i]); if ((obj != null)) { collection.Add(obj); } } } return collection; } catch (System.Exception ) { throw; } finally { if ((dbo != null)) { dbo.Dispose(); } } }
static void Main(string[] args) { if (!EnsureSingleLoad()) { Console.WriteLine("{0}: Another Instance Currently Running", DateTime.Now); return; } var start = DateTime.Now; Console.WriteLine("{0}: Started", start); var users = UsersCollection.PrimaryUsers() ?? new List <PostworthyUser>(); var tasks = new List <Task>(); users.AsParallel().ForAll(u => { var tweet = ""; var repoIndex = new SimpleRepository <ArticleStubIndex>(u.TwitterScreenName); var repoPage = new SimpleRepository <ArticleStubPage>(u.TwitterScreenName); ArticleStubIndex articleStubIndex = null; string dayTag = ""; DateTime day = DateTime.MinValue; if (args.Length > 0) { if (DateTime.TryParse(args[0], out day)) { day = day.StartOfDay(); dayTag = "_" + day.ToShortDateString(); articleStubIndex = repoIndex.Query(TwitterModel.Instance(u.TwitterScreenName).CONTENT_INDEX).FirstOrDefault() ?? new ArticleStubIndex(); if (articleStubIndex.ArticleStubPages.Where(x => x.Key == day.ToFileTimeUtc()).Count() == 0) { articleStubIndex.ArticleStubPages.Add(new KeyValuePair <long, string>(day.ToFileTimeUtc(), day.ToShortDateString())); } else { articleStubIndex = null; } } } else { articleStubIndex = repoIndex.Query(TwitterModel.Instance(u.TwitterScreenName).CONTENT_INDEX).FirstOrDefault() ?? new ArticleStubIndex(); day = DateTime.Now.AddDays(-1); day = day.StartOfDay(); if (articleStubIndex.ArticleStubPages.Where(x => x.Key == day.ToFileTimeUtc()).Count() == 0) { dayTag = "_" + day.ToShortDateString(); articleStubIndex.ArticleStubPages.Add(new KeyValuePair <long, string>(day.ToFileTimeUtc(), day.ToShortDateString())); var domain = u.PrimaryDomains.OrderBy(x => x.Length).FirstOrDefault(); if (!string.IsNullOrEmpty(domain) && !domain.StartsWith("beta")) { tweet = "Here are the top articles from " + day.ToShortDateString().Replace('/', '-') + " http://" + domain + "/" + day.ToShortDateString().Replace('/', '-'); } } else { articleStubIndex = null; day = DateTime.MinValue; dayTag = ""; } } var groupingResults = CreateGroups(u, day == DateTime.MinValue ? null : (DateTime?)day); var existing = repoPage.Query(TwitterModel.Instance(u.TwitterScreenName).CONTENT + dayTag).FirstOrDefault(); var contentTask = CreateContent(u, groupingResults, existing); Console.WriteLine("{0}: Waiting on content for {1}", DateTime.Now, u.TwitterScreenName); var continueTask = contentTask.ContinueWith(task => { Console.WriteLine("{0}: Content completed for {1}", DateTime.Now, u.TwitterScreenName); var stubs = task.Result.Take(MAX_CONTENT); if (stubs.Count() > 0 || !string.IsNullOrEmpty(dayTag)) { var articleStubPage = new ArticleStubPage(1, stubs); if (existing != null && existing.ExcludedArticleStubs.Count > 0) { articleStubPage.ExcludedArticleStubs = existing.ExcludedArticleStubs.Where(e => articleStubPage.ArticleStubs.Contains(e)).ToList(); } Console.WriteLine("{0}: Deleting old data from files from storage for {1}", DateTime.Now, u.TwitterScreenName); repoPage.Delete(TwitterModel.Instance(u.TwitterScreenName).CONTENT + dayTag); Console.WriteLine("{0}: Storing data in repository for {1}", DateTime.Now, u.TwitterScreenName); repoPage.Save(TwitterModel.Instance(u.TwitterScreenName).CONTENT + dayTag, articleStubPage); if (articleStubIndex != null) { repoIndex.Save(TwitterModel.Instance(u.TwitterScreenName).CONTENT_INDEX, articleStubIndex); } if (!string.IsNullOrEmpty(tweet)) { try { TwitterModel.Instance(u.TwitterScreenName).UpdateStatus(tweet, processStatus: false); } catch (Exception ex) { Console.WriteLine("{0}: Could not tweet message: {1}" + Environment.NewLine + "The following exception was thrown: {2}", DateTime.Now, tweet, ex.ToString()); } } } else { Console.WriteLine("{0}: No articles found for {1}", DateTime.Now, u.TwitterScreenName); } }); tasks.Add(contentTask); tasks.Add(continueTask); }); Task.WaitAll(tasks.ToArray()); var end = DateTime.Now; Console.WriteLine("{0}: Ending and it took {1} minutes to complete", end, (end - start).TotalMinutes); }
public void ReadUsersSection() { var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var usersSection = config.GetSection("UsersSection") as UsersSection; if (usersSection != null) { users = usersSection.Users; } else { users = null; } }
static void Main(string[] args) { if (!EnsureSingleLoad()) { Console.WriteLine("{0}: Another Instance Currently Runing", DateTime.Now); return; } var start = DateTime.Now; Console.WriteLine("{0}: Started", start); var users = UsersCollection.PrimaryUsers() ?? new List <PostworthyUser>(); users.AsParallel().ForAll(user => { var primaryUserName = user.TwitterScreenName; Console.WriteLine("{0}: Deleting old groups from files from storage", DateTime.Now); CachedRepository <TweetGroup> .Instance(primaryUserName).Delete(TwitterModel.Instance(primaryUserName).GROUPING); List <string> screenNames = null; screenNames = TwitterModel.Instance(primaryUserName).GetRelevantScreenNames(user.TwitterScreenName); int RetweetThreshold = user.RetweetThreshold; Func <Tweet, bool> where = t => //Should everything be displayed or do you only want content (user.OnlyTweetsWithLinks == false || (t.Links != null && t.Links.Count > 0)) && //Minumum threshold applied so we get results worth seeing (if it is your own tweet it gets a pass on this step) ((t.RetweetCount > RetweetThreshold /*&& t.CreatedAt > DateTime.Now.AddHours(-48)*/) || t.User.ScreenName.ToLower() == user.TwitterScreenName.ToLower()); var startGrouping = DateTime.Now; Console.WriteLine("{0}: Starting grouping procedure", startGrouping); var tweets = screenNames //For each screen name (i.e. - you and your friends if included) select the most recent tweets .SelectMany(x => CachedRepository <Tweet> .Instance(primaryUserName).Query(x + TwitterModel.Instance(primaryUserName).TWEETS, where : where) ?? new List <Tweet>()) //Order all tweets based on rank (TweetRank takes into acount many important factors, i.e. - time, mentions, hotness, ect.) .OrderByDescending(t => t.TweetRank) //Just to make sure we are not trying to group a very very large number of items .Take(1000); var groups = tweets //Group similar tweets (the ordering is done first so that the earliest tweet gets credit) .GroupSimilar(log: Console.Out) //Convert groups into something we can display .Select(g => new TweetGroup(g) { RepositoryKey = TwitterModel.Instance(primaryUserName).GROUPING }) //For the sake of space we only want to store groups that have more than 1 item .Where(g => g.GroupStatusIDs.Count > 1); var results = groups.ToList(); var endGrouping = DateTime.Now; Console.WriteLine("{0}: Grouping procedure completed and it took {1} minutes to complete", endGrouping, (endGrouping - startGrouping).TotalMinutes); Console.WriteLine("Storing data in repository"); if (results != null && results.Count > 0) { CachedRepository <TweetGroup> .Instance(primaryUserName).Save(TwitterModel.Instance(primaryUserName).GROUPING, results); } }); var end = DateTime.Now; Console.WriteLine("{0}: Ending and it took {1} minutes to complete", end, (end - start).TotalMinutes); }
public static void InitializeUse(UserData user, UnityAction <bool> onUserInitilized) { CurrentUser = user; UsersCollection.SaveUser(_userId, user, onUserInitilized); }
partial void BtnAdd_TouchUpInside(UIButton sender) { if (string.IsNullOrEmpty(txtFirstName.Text) || string.IsNullOrEmpty(txtLastName.Text) || string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtPassword.Text)) { var emptyFieldAlert = UIAlertController.Create("Required Field Empty", "A required field is not entered", UIAlertControllerStyle.Alert); emptyFieldAlert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null)); this.PresentViewController(emptyFieldAlert, true, null); return; } //String validations for Password var hasNumber = new Regex(@"[0-9]+"); var hasUpperChar = new Regex(@"[A-Z]+"); var hasLowerChar = new Regex(@"[a-z]+"); var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]"); var isBetween5And12Chars = new Regex(@".{5,12}"); //Length has to be between 5 and 12 if (!isBetween5And12Chars.IsMatch(txtPassword.Text)) { var passwordLengthAlert = UIAlertController.Create("Password Validation", "Password must be between 5 and 12 characters", UIAlertControllerStyle.Alert); passwordLengthAlert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null)); this.PresentViewController(passwordLengthAlert, true, null); return; } //Has atleast one number if (!hasNumber.IsMatch(txtPassword.Text)) { var passwordLengthAlert = UIAlertController.Create("Password Validation", "Password must have atleast one number", UIAlertControllerStyle.Alert); passwordLengthAlert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null)); this.PresentViewController(passwordLengthAlert, true, null); return; } //Has atleast one letter if (!hasUpperChar.IsMatch(txtPassword.Text) && !hasLowerChar.IsMatch(txtPassword.Text)) { var passwordLengthAlert = UIAlertController.Create("Password Validation", "Password must have atleast one letter", UIAlertControllerStyle.Alert); passwordLengthAlert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null)); this.PresentViewController(passwordLengthAlert, true, null); return; } //Cannot have special characters if (hasSymbols.IsMatch(txtPassword.Text)) { var passwordLengthAlert = UIAlertController.Create("Password Validation", "Password cannot have special characters", UIAlertControllerStyle.Alert); passwordLengthAlert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null)); this.PresentViewController(passwordLengthAlert, true, null); return; } var newUser = new User { FirstName = txtFirstName.Text, LastName = txtLastName.Text, UserName = txtUserName.Text, Password = txtPassword.Text }; var users = new UsersCollection(); users.AddUser(newUser).GetAwaiter(); NSNotificationCenter.DefaultCenter.PostNotificationName("NewUserAdded", this); this.DismissViewController(true, null); }
public override void ViewDidLoad() { base.ViewDidLoad(); UsersCollection = new UsersCollection(); tableViewUsers.Source = new UsersTableSource(UsersCollection.Users); }
public void InitialData() { UsersCollection.InitiateUser(); ItemCollection.InitiateData(); }
/// <summary> /// Interpreta los usuarios de un nodo /// </summary> private static void ParseUsers(MLNodesCollection objMLColNodes, UsersCollection objColUsers) { foreach (MLNode objMLChild in objMLColNodes) if (objMLChild.Name.Equals(cnstStrTagUser)) objColUsers.Add(Parse(objMLChild)); else if (objMLChild.Name.Equals(cnstStrTagNextCursor)) objColUsers.NextCursor = objMLChild.Value; else if (objMLChild.Name.Equals(cnstStrTagPreviousCursor)) objColUsers.PreviousCursor = objMLChild.Value; }
static void Main(string[] args) { if (!EnsureSingleLoad()) { Console.WriteLine("{0}: Another Instance Currently Runing", DateTime.Now); return; } TweetProcessor tp; List <Tweet> tweets; var start = DateTime.Now; Console.WriteLine("{0}: Started", start); var primaryUser = UsersCollection.PrimaryUser(); Console.WriteLine("{0}: Getting Friends for {1}", DateTime.Now, primaryUser.TwitterScreenName); Postworthy.Models.Twitter.TwitterModel.Instance.UpdateFriendsForPrimaryUser(); Console.WriteLine("{0}: Getting Tweets for {1}", DateTime.Now, primaryUser.TwitterScreenName); tweets = StatusTimeline.Get(); if (tweets != null) { Console.WriteLine("{0}: Processing {1} Tweets", DateTime.Now, tweets.Count); tp = new TweetProcessor(tweets); tp.Start(); Console.WriteLine("{0}: Saving Tweets", DateTime.Now); tweets .GroupBy(t => t.User.Identifier.ScreenName) .ToList() .ForEach(g => { Repository <Tweet> .Instance.Save(g.Key + TwitterModel.TWEETS, g.Select(x => x).ToList()); Console.WriteLine("{0}: {1} Tweets Saved for {2}", DateTime.Now, g.Count(), g.Key); }); Repository <Tweet> .Instance.FlushChanges(); } else { tweets = new List <Tweet>(); } List <string> screenNames = new List <string>(); screenNames.AddRange(TwitterModel.Instance.GetRelevantScreenNames(primaryUser.TwitterScreenName)); Console.WriteLine("{0}: Update Retweet Counts", DateTime.Now); List <Tweet> updateTweets = new List <Tweet>(); foreach (var screenName in screenNames) { var tweetsToUpdate = Repository <Tweet> .Instance.Query(screenName + TwitterModel.TWEETS, where : t => t.CreatedAt > DateTime.Now.AddHours(-48)); if (tweetsToUpdate != null && tweetsToUpdate.Count > 1) { tweetsToUpdate = tweetsToUpdate.Except(tweets).OrderByDescending(t => t.Status.CreatedAt).ToList(); if (tweetsToUpdate != null && tweetsToUpdate.Count > 1) { Console.WriteLine("{0}: Updating Retweet Counts for {1}", DateTime.Now, screenName); var updatedStatuses = StatusTimeline.Get(screenName, tweetsToUpdate.First().StatusID); if (updatedStatuses != null && updatedStatuses.Count > 0) { int tweetsAdded = 0; foreach (var s in updatedStatuses) { var t = tweetsToUpdate.SingleOrDefault(x => x.StatusID == s.StatusID); if (t != null && t.RetweetCount != s.RetweetCount) { t.Status.RetweetCount = s.RetweetCount; updateTweets.Add(t); tweetsAdded++; } } if (tweetsAdded > 0) { Console.WriteLine("{0}: {1} Retweet Counts Updated for {2}", DateTime.Now, tweetsAdded, screenName); } } } } } if (updateTweets.Count > 0) { Console.WriteLine("{0}: Processing {1} Tweets with New Retweet Counts", DateTime.Now, updateTweets.Count); tp = new TweetProcessor(updateTweets); tp.Start(); Repository <Tweet> .Instance.FlushChanges(); } var end = DateTime.Now; Console.WriteLine("{0}: Finished in {1} minutes", end, (end - start).TotalMinutes); }
/// <summary> /// Interpreta un documento XML para obtener una colección de datos de usuario /// </summary> internal static UsersCollection ParseCollection(MLFile objMLFile) { UsersCollection objColUsers = new UsersCollection(); // Interpreta los datos foreach (MLNode objMLNode in objMLFile.Nodes) if (objMLNode.Name.Equals("Root")) { objColUsers.NextCursor = objMLNode.Attributes[cnstStrTagNextCursor].Value; objColUsers.PreviousCursor = objMLNode.Attributes[cnstStrTagPreviousCursor].Value; foreach (MLNode objMLChild in objMLNode.Nodes) if (objMLChild.Name.Equals(cnststrTagUsersList)) { foreach (MLNode objMLUser in objMLChild.Nodes) if (objMLUser.Name.Equals(cnstStrTagUsers)) ParseUsers(objMLUser.Nodes, objColUsers); } else if (objMLChild.Name.Equals(cnstStrTagUsers)) foreach (MLNode objMLStruct in objMLChild.Nodes) if (objMLStruct.Name == "Struct") objColUsers.Add(Parse(objMLStruct)); } // Devuelve los usuarios return objColUsers; }
public ActionResult Personalization() { PostworthyUser model = UsersCollection.Single(User.Identity.Name); return(View(model)); }
private void Clean() { this.Sysid = null; this.Publicid = null; this.Path = string.Empty; this.Createdate = null; this.Lastmodifieddate = null; this.Active = null; this._usersCollection = null; }
/// <summary> /// Obtiene el siguiente lote de amigos /// </summary> public UsersCollection GetNextFriends(UsersCollection objColUsers, string strScreenName) { // Carga el siguiente lote de seguidores for (int intIndex = 0; intIndex < 10 && !base.Account.HasError; intIndex++) if (objColUsers == null || objColUsers.Count == 0 || !objColUsers.HasEndLoad) { UsersCollection objColNewFollowers; // Crea la colección si no existía if (objColUsers == null) objColUsers = new UsersCollection(); // Carga los seguidores if (objColUsers.Count == 0) objColNewFollowers = GetFriends(null, strScreenName, "-1", false); else objColNewFollowers = GetFriends(null, strScreenName, objColUsers.NextCursor, false); // Si no ha habido ningún error, añade los nuevos seguidores, si no, guarda de nuevo el cursor anterior if (!base.Account.HasError) { // Añade los usuarios objColUsers.AddRange(objColNewFollowers); // Asigna los cursores objColUsers.NextCursor = objColNewFollowers.NextCursor; objColUsers.PreviousCursor = objColNewFollowers.PreviousCursor; } } // Devuelve la colección de seguidores return objColUsers; }
public async Task GetById_SHOULD_not_throw_exception_and_return_null_WHEN_id_does_not_exist() { var users = new UsersCollection(_fixture.UsersRepo, _fixture.PatcherProvider, _fixture.Instanciator); Assert.Null(await users.GetByIdAsync(Guid.NewGuid(), new Query <User>())); }
public OrganizationMembersViewModel(IApplicationService applicationService) { LoadCommand = ReactiveCommand.CreateAsyncTask( t => UsersCollection.SimpleCollectionLoad(applicationService.Client.Organizations[OrganizationName].GetMembers(), t as bool?)); }
public MockDatabase() { User user1 = new User { Id = 1, UniversityId = "s0000001", FirstName = "Connagh", LastName = "Muldoon", Email = "*****@*****.**", PhoneNumber = "01452699316", DateOfBirth = new DateTime(1995, 06, 01), Role = UserRole.Student, Graduated = false }; User user2 = new User { Id = 2, UniversityId = "s0000002", FirstName = "Thomas", LastName = "Clark", Email = "*****@*****.**", PhoneNumber = "01452234765", DateOfBirth = new DateTime(1995, 02, 23), Role = UserRole.Student, Enrollments = new List <Identifier>() }; User user3 = new User { Id = 3, UniversityId = "s0000003", FirstName = "Abu", LastName = "Alam", Email = "*****@*****.**", PhoneNumber = "01452543876", DateOfBirth = new DateTime(1988, 08, 12), Role = UserRole.Lecturer }; Module module1 = new Module { Id = 1, ModuleTitle = "Applied Ass Kicking", ModuleCode = "CT1337" }; ModuleRun moduleRun1 = new ModuleRun { Id = 1, Lecturer = user3.ToIdentifier(), Module = module1.ToIdentifier() }; module1.ModuleRuns = new List <Identifier>() { moduleRun1.ToIdentifier() }; Assignment assignment1 = new Assignment { Id = 1, AssignmentName = "1. Chew Bubblegum", ModuleRun = moduleRun1.ToIdentifier() }; moduleRun1.Assignments = new List <Identifier>() { assignment1.ToIdentifier() }; Course course1 = new Course { Id = 1, Title = "Computing - BSc W/Hons", CourseLeader = user3.ToIdentifier(), ModuleRuns = new List <Identifier>() { moduleRun1.ToIdentifier() }, Students = new List <Identifier>() { user1.ToIdentifier() } }; Result result1 = new Result() { Id = 1, Assignment = assignment1.ToIdentifier(), Grade = 74, Student = user1.ToIdentifier() }; assignment1.Results = new List <Identifier>() { result1.ToIdentifier() }; user1.Enrollments = new List <Identifier>() { moduleRun1.ToIdentifier() }; user1.Course = new Identifier(course1); user3.Enrollments = new List <Identifier>() { moduleRun1.ToIdentifier() }; user3.Course = new Identifier(course1); UsersCollection.Add(user1); UsersCollection.Add(user2); UsersCollection.Add(user3); ModulesCollection.Add(module1); ModuleRunsCollection.Add(moduleRun1); AssignmentsCollection.Add(assignment1); ResultsCollection.Add(result1); CoursesCollection.Add(course1); }
public LoginWindowViewModel(string user, string pass) { ListaUsers = UsersCollection.GetAllUsers(); Username = user; Password = pass; }
/// <summary> /// Get Users /// </summary> /// <param name="status"></param> /// <returns></returns> public UsersCollection<TopRockUser> GetUsers(enumStatuses status) { UsersCollection<TopRockUser> _coll = new UsersCollection<TopRockUser>(this.ConnectionString); ArgumentsList _arg = new ArgumentsList(new ArgumentsListItem("Status", Convert.ToInt32(status).ToString())); _coll.LitePopulate(_arg,false, null); return _coll; }
public override void UpdateUser(MembershipUser user) { UsersCollection.Save(user, WriteConcern.Acknowledged); }
private static bool EnsureSingleLoad() { bool result; var mutex = new System.Threading.Mutex(true, "Postworthy.Tasks.Streaming." + UsersCollection.PrimaryUser().TwitterScreenName, out result); return(result); }
public NewUserModuleTests() { UsersCollection.Clear(); _browser = new Browser(with => with.Modules(typeof(NewUserModule))); }
public UserFollowersViewModel(IApplicationService applicationService) { LoadCommand = ReactiveCommand.CreateAsyncTask(t => UsersCollection.SimpleCollectionLoad(applicationService.Client.Users[Username].GetFollowers(), t as bool?)); }
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true); OnValidatingPassword(args); if (args.Cancel) { status = MembershipCreateStatus.InvalidPassword; return(null); } if (this.RequiresQuestionAndAnswer) { if (passwordQuestion.IsNullOrEmpty()) { status = MembershipCreateStatus.InvalidQuestion; return(null); } else if (passwordAnswer.IsNullOrEmpty()) { status = MembershipCreateStatus.InvalidQuestion; return(null); } } if (password.Length < MinRequiredPasswordLength) { throw new Exception(String.Format("Password length is too weak. Minimum password length is {0}", MinRequiredPasswordLength)); } string name = GetUserNameByEmail(email); if (RequiresUniqueEmail && name.IsNotNullAndEmpty()) { status = MembershipCreateStatus.DuplicateEmail; return(null); } if (!UsersCollection.IsExist(username, ApplicationName)) { string salt = getPasswordSalt(); User user = new User(username, ApplicationName, email, encodePassword(password, salt)); user.PasswordSalt = ASCIIEncoding.ASCII.GetBytes(salt); user.ProviderName = this.Name; user.PasswordQuestion = passwordQuestion; user.PasswordAnswer = passwordAnswer.IsNullOrEmpty() ? null : encodePassword(passwordAnswer, salt); user.IsApproved = isApproved; user.ApplicationName = ApplicationName; user.IsLockedOut = false; user.DateCreated = DateTime.Now; user.LastLockedOutDate = DateTime.Now; user.FailedPasswordAttemptWindowStart = DateTime.Now; user.FailedPasswordAnswerAttemptWindowStart = DateTime.Now; try { UsersCollection.Save(user); status = MembershipCreateStatus.Success; } catch (Exception e) { status = MembershipCreateStatus.UserRejected; throw e; } return(user); } else { status = MembershipCreateStatus.DuplicateUserName; } return(null); }
public void UpdateUser(User user) { UsersCollection.Save(user); }
public override string ResetPassword(string username, string answer) { User user = getProviderUser(username, true); if (!EnablePasswordReset) { throw new Exception("Password reset is not enabled."); } if (RequiresQuestionAndAnswer && (answer.IsNull() || answer.Length == 0)) { updateFailureCount(user, FailureType.PasswordAnswer); throw new Exception("Password answer required."); } string newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters); ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true); OnValidatingPassword(args); if (args.Cancel) { if (args.FailureInformation != null) { throw args.FailureInformation; } else { throw new Exception("Reset password canceled."); } } bool isLockedOut = false; string salt = String.Empty; string dbAnswer = getPasswordAnswer(username, out isLockedOut, out salt); if (isLockedOut) { throw new Exception(String.Format("Wrong password. Max invalid password attempts {0} has been reached.", MaxInvalidPasswordAttempts)); } if (RequiresQuestionAndAnswer && !validatePassword(answer, dbAnswer, salt)) { updateFailureCount(user, FailureType.PasswordAnswer); throw new Exception("Incorrect password answer."); } user.Password = ASCIIEncoding.ASCII.GetBytes(encodePassword(newPassword, salt)); user.PasswordSalt = ASCIIEncoding.ASCII.GetBytes(salt); user.PasswordAnswer = encodePassword(dbAnswer, salt); user.LastPasswordChangedDate = DateTime.Now; user.ResetPasswordOnFirstLogin = false; user.FailedPasswordAttemptCount = 0; user.FailedPasswordAttemptWindowStart = DateTime.Now; user.FailedPasswordAnswerAttemptCount = 0; user.FailedPasswordAnswerAttemptWindowStart = DateTime.Now; try { UsersCollection.Save(user, SafeMode.True); } catch { throw new Exception(String.Format("Password {0} not reset.", username)); } return(newPassword); }
public static List <Tweet> Get() { return(Get(UsersCollection.PrimaryUser().TwitterScreenName, 0)); }
public override void UpdateUser(MembershipUser user) { UsersCollection.Save(user); }
/// <summary> /// Initializes a new instance of the <see cref="UsersService"/> class. /// </summary> /// <param name="databaseSettingsOptions"> /// The database settings options. /// </param> public UsersService(IOptions <DatabaseSettings> databaseSettingsOptions) { _usersCollection = new UsersCollection(databaseSettingsOptions); }
private void updateFailureCount(User user, FailureType failureType) { DateTime windowStart = new DateTime(); int failureCount = 0; switch (failureType) { case FailureType.Password: failureCount = user.FailedPasswordAttemptCount; windowStart = user.FailedPasswordAttemptWindowStart; break; case FailureType.PasswordAnswer: failureCount = user.FailedPasswordAnswerAttemptCount; windowStart = user.FailedPasswordAnswerAttemptWindowStart; break; } DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow); if (failureCount == 0 || DateTime.Now > windowEnd) { switch (failureType) { case FailureType.Password: user.FailedPasswordAttemptCount = 1; user.FailedPasswordAttemptWindowStart = DateTime.Now; break; case FailureType.PasswordAnswer: user.FailedPasswordAnswerAttemptCount = 1; user.FailedPasswordAnswerAttemptWindowStart = DateTime.Now; break; } } else if (++failureCount >= MaxInvalidPasswordAttempts) { user.IsLockedOut = true; switch (failureType) { case FailureType.Password: user.FailedPasswordAttemptCount = failureCount; user.FailedPasswordAttemptWindowStart = windowEnd; break; case FailureType.PasswordAnswer: user.FailedPasswordAnswerAttemptCount = failureCount; user.FailedPasswordAnswerAttemptWindowStart = windowEnd; break; } user.LastLockedOutDate = DateTime.Now; } else { switch (failureType) { case FailureType.Password: user.FailedPasswordAttemptCount = failureCount; break; case FailureType.PasswordAnswer: user.FailedPasswordAnswerAttemptCount = failureCount; break; } } UsersCollection.Save(user, SafeMode.True); }
public RepositoryCollaboratorsViewModel(IApplicationService applicationService) { LoadCommand = ReactiveCommand.CreateAsyncTask(t => UsersCollection.SimpleCollectionLoad( applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetCollaborators(), t as bool?)); }
/// <summary>Create <see cref="Repository"/>.</summary> /// <param name="gitAccessor">Git repository access provider.</param> /// <param name="workingDirectory">Repository working directory.</param> /// <param name="load"><c>true</c> to load repository; <c>false</c> otherwise.</param> private Repository(IGitAccessor gitAccessor, string workingDirectory, bool load) { Verify.Argument.IsNotNull(gitAccessor, "gitAccessor"); Verify.Argument.IsNotNull(workingDirectory, "workingDirectory"); _workingDirectory = GetWorkingDirectory(workingDirectory); _gitDirectory = GetGitDirectory(_workingDirectory); _configurationManager = GetConfigurationManager(_gitDirectory); _accessor = gitAccessor.CreateRepositoryAccessor(this); _revisionCache = new RevisionCache(this); _configuration = new ConfigParametersCollection(this); _status = new Status(this); _stash = new StashedStatesCollection(this); _refs = new RefsCollection(this); _notes = new NotesCollection(this); _remotes = new RemotesCollection(this); _submodules = new SubmodulesCollection(this); _users = new UsersCollection(this); _hooks = new HooksCollection(this); if(load) { try { LoadCore(this, null, CancellationToken.None); } catch { Dispose(); throw; } } }