/// <summary> /// Creates a server from a ServerConfig with a parameter /// to provide an interface for logging. /// </summary> /// <param name="config">The configuration to build the Server from.</param> /// <param name="logFunction">The function to call to log text for the application.</param> public Server(Configuration.ServerConfig config, Project2QService.WriteLogFunction logFunction) { //Instantiate and load databases uc = new UserCollection(); cc = new ChannelCollection(); uc.LoadRegisteredUsers( "userdb\\" + config.Name + ".udb" ); //Rip up this little guy to help us out :D currentHost = new IRCHost(); currentIP = null; this.authmode = !File.Exists( "userdb\\" + config.Name + ".udb" ); this.writeLogFunction = logFunction; //Assign a Server ID this.serverId = Server.NextServerId; if ( this.serverId == -1 ) throw new OverflowException( "Too many servers created." ); servers[serverId] = this; //Save the configuration. this.config = config; //Tie default static handlers together for this instance of IRCEvents. irce = new IRCEvents(); //Initialize the socket pipe before the modules. Modules are scary. state = State.Disconnected; socketPipe = new SocketPipe( this.serverId, config.RetryTimeout, config.OperationTimeout, config.SendInhibit, config.SocketBufferSize ); //Default values for now, get them from config later plz. socketPipe.OnDisconnect += new SocketPipe.NoParams( this.OnDisconnect ); socketPipe.OnReceive += new SocketPipe.ReceiveData( this.OnReceive ); }
/// <summary> /// Initializes the ContactList on the given client. /// </summary> /// <remarks> /// This method should not be called until the Client receives the ServerSupport is populated. /// An easy way to make sure is to wait until the Ready event of the Client. /// </remarks> public void Initialize( Client client ) { if ( client == null ) { throw new ArgumentNullException( "client" ); } ServerSupport support = client.ServerSupports; Client = client; Users = new UserCollection(); if ( support.MaxWatches > 0 ) { tracker = new ContactsWatchTracker( this ); } else if ( support.MaxMonitors > 0 ) { tracker = new ContactsMonitorTracker( this ); } else { tracker = new ContactsIsOnTracker( this ); } tracker.Initialize(); }
internal IrcChannel(IrcClient client, string name) { Client = client; Users = new UserCollection(); UsersByMode = new Dictionary<char, UserCollection>(); Name = name; }
public UserCollection Generate(EnvTrafficMap map,int index, int scalingFactor, bool isFixure) { ITrafficMapModelService service = map.ServiceContext.Lookup(typeof(ITrafficMapModelService).FullName) as ITrafficMapModelService; IGeoPolygonAssist polygonRegionAssist = service.PolygonRegionAssist; this.InitRandom(isFixure); this.m_UserCollection = new UserCollection(); this.m_ScalingFactor = scalingFactor; foreach (GeoPolygonRegion region in map.PolygonRegionList) { try { this.m_Poly = this.getActuralPolyonRegion(polygonRegionAssist, region); this.m_Rect = this.m_Poly.GetMiniEnclosingRect(); foreach (UserMobilityBinding binding in map.PolygonEnvironmentBindings[region].UserDatas) { this.UserMobilityReader(index,binding, isFixure); } } catch (Exception exception) { WriteLog.Logger.Error(region.Name + " is not exist" + exception.Message); } } this.setUserIDProperty(); return this.m_UserCollection; }
public CommandContext(Client irc, UserCollection users, User from, Channel channel, string message) { this._irc = irc; this._users = users; this.From = from; this._channel = channel; if (message[0] == '!' || message[0] == '.') { this._replyNotice = true; } else { this._replyNotice = false; } if (message[0] == '!' || message[0] == '.' || message[0] == '@') { this.Message = message.Substring(1); } else { this.Message = message; } }
public UserCollection FetchAll() { UserCollection coll = new UserCollection(); Query qry = new Query(User.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; }
public void Disable(UserCollection collection) { foreach (User user in collection) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "SP_UPD_Table"; SqlParameter _param = command.Parameters.Add("@value1", System.Data.SqlDbType.VarChar); _param.Value = "Users"; // Table Name SqlParameter _param2 = command.Parameters.Add("@value2", System.Data.SqlDbType.VarChar); _param2.Value = "4"; // Update Column Order SqlParameter _param3 = command.Parameters.Add("@value3", System.Data.SqlDbType.VarChar); _param3.Value = user.Enable; // update value SqlParameter _param4 = command.Parameters.Add("@value4", System.Data.SqlDbType.VarChar); _param4.Value = "1"; // Where Column Order SqlParameter _param5 = command.Parameters.Add("@value5", System.Data.SqlDbType.VarChar); _param5.Value = user.UserID; // Where value equal to command.CommandType = System.Data.CommandType.StoredProcedure; connection.Open(); command.ExecuteNonQuery(); } } }
public override CommandResult Execute(String chan,String pw, String arg3, String arg4) { if (!String.IsNullOrEmpty(chan)) { Channel channel = EasyGuess.GetMatchedChannel(((ServerSocket)Server).Channels, chan); if (channel != null) { String str = ""; UserCollection usersOnline = new UserCollection(); foreach (User u in channel.User) { if (MinecraftHandler.IsStringInList(u.Name, MinecraftHandler.Player)) { usersOnline.Add(u); } } Server.SendExecuteResponse(TriggerPlayer, String.Format("Users in channel {0} ({1}): ", chan, usersOnline.Count)); foreach (User u in usersOnline) { str += u.Name + ", "; } if (!String.IsNullOrEmpty(str)) { Server.SendExecuteResponse(TriggerPlayer, String.Format("{0}", str)); } return new CommandResult(true, String.Format("{0} executed cinfo",TriggerPlayer)); } return new CommandResult(true, String.Format("Channel not found"), true); } else { List<Channel> channels = ((ServerSocket)Server).Channels.FindAll(x => x.User.IsInlist(TriggerPlayer)); Server.SendExecuteResponse(TriggerPlayer, String.Format("You're in the following channels: ")); String str = ""; foreach (Channel c in channels) { UserCollection usersOnline = new UserCollection(); foreach (User u in c.User) { if (MinecraftHandler.IsStringInList(u.Name, MinecraftHandler.Player)) { usersOnline.Add(u); } } str += String.Format("{0} ({1}), ", c.Name, usersOnline.Count); } if (!String.IsNullOrEmpty(str)) { Server.SendExecuteResponse(TriggerPlayer, String.Format("{0}", str)); } return new CommandResult(true, String.Format("{0} executed cinfo", TriggerPlayer)); } }
/// <summary> /// Returns the logged-in user profile /// </summary> /// <returns>Logged in user profile</returns> public User AddUser(User user) { string url = string.Format("{0}api/1.0/people", BaseURL, user.ID.ToString()); TLRequestResult result = GetPOST(url, user.Serialize()); UserCollection response = new UserCollection(result); return response[0]; }
public CellUserGenerator(IApplicationContext context) { this.m_ServiceContext = context; this.m_UserCollection = new UserCollection(); this.m_CellClutterPtsCntDict = new Dictionary<int, Dictionary<short, int>>(); this.m_CellClutterWeightFactorDict = new Dictionary<int, Dictionary<short, double>>(); this.m_TrafficModelService = context.Lookup(typeof(ITrafficMapModelService).FullName) as ITrafficMapModelService; this.m_PolyAssist = this.m_TrafficModelService.PolygonRegionAssist; }
public bool CheckPassword(string userName, string password) { UserCollection collection = new UserCollection(); collection = Query(userName); User user = collection[0]; if (password.Equals(user.UserPWD)) return true; else return false; }
public static User UserExistCheck(string UserName) { UserCollection list = new UserCollection(); list.ReadList(Criteria.NewCriteria(User.Columns.UserName, CriteriaOperators.Like, UserName)); if (list.Count == 0) { return null; } else return list[0]; }
public void send_message(string username, string message) { var user = new User(); var users = new UserCollection {user}; var chat = new Chat(); // chat.AddMembers(users); chat.SendMessage(message); }
//checking for Login public static User LoginCheck(string UserName, string Password) { UserCollection list = new UserCollection(); list.ReadList(Criteria.NewCriteria(User.Columns.UserName, CriteriaOperators.Like, UserName) & Criteria.NewCriteria(User.Columns.Password, CriteriaOperators.Like, Password)); if (list.Count == 0) { return null; } else return list[0]; }
internal IrcChannel(IrcClient client, string name) { Client = client; Users = new UserCollection(); Operators = new UserCollection(); Voiced = new UserCollection(); Bans = new MaskCollection(); Exceptions = new MaskCollection(); Quiets = new MaskCollection(); Invites = new MaskCollection(); Name = name; }
/// <summary> /// Handler for the selectclicked event of the finduser control. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void SelectClickedHandler(object sender, System.EventArgs e) { List<int> selectedUserIDs = userFinder.SelectedUserIDs; phEmailConstruction.Visible = (selectedUserIDs.Count>0); if(selectedUserIDs.Count <= 0) { // nothing selected, return return; } _selectedUsers = UserGuiHelper.GetAllUsersInRange(selectedUserIDs); SetViewState(); SetToNames(); userFinder.Visible=false; }
public ActionResult Login(User u) { var users = new UserCollection(); var user = users.Find(o => o.Username == u.Username && o.Password == u.Password); string r_message = "Login failed."; bool r_status = false; if (user!=null) { r_status = true; r_message = "Login successful."; } return Json(new { status = r_status, message = r_message }, JsonRequestBehavior.AllowGet); }
private static bool CheckUserInAdminGroups(ClientContext ctx, Web web, RoleAssignmentCollection roleAssignments, User currentUser) { if (roleAssignments != null && roleAssignments.Count != 0) { foreach (RoleAssignment ra in roleAssignments) { //Load users foreach Group - Group Name: ra.Member.Title UserCollection usersCollection = web.SiteGroups.GetByName(ra.Member.Title).Users; ctx.Load(usersCollection); ctx.ExecuteQuery(); //Check Permission Groups - rd.Name: Permission Level foreach (RoleDefinition rd in ra.RoleDefinitionBindings) { if (rd.Name.Equals("Full Control") && (usersCollection.GetByEmail(currentUser.Email) != null)) { return(true); } } } } return(false); }
public ActionResult <string> ConfirmerLeCompte(string id) { try { var demandeurCollection = new UserCollection(); var entreprise = demandeurCollection.GetItems(e => e.Id == id).FirstOrDefault(); if (entreprise == null) { throw new Exception("Erreur: Utilisateur non trouvé"); } else { entreprise.Identite.IsVerified = true; demandeurCollection.UpdateItem(id, entreprise); return(StatusCode(200, "Compte confirmé")); } } catch (Exception e) { return(StatusCode(500, $"Erreur: {e.Message}")); } }
public ConfigService(LiteDatabase globalDatabase, LiteDatabase userDatabase) { GlobalCollection = globalDatabase.GetCollection <AppConfiguration>(nameof(AppConfiguration)); UserCollection = userDatabase.GetCollection <AppConfiguration>(nameof(AppConfiguration)); var defaultGlobalSettings = new AppConfiguration() { Id = "v0.18.0", OutdatedPackagesCacheDurationInMinutes = "60", UseKeyboardBindings = true, DefaultToTileViewForLocalSource = true, DefaultToTileViewForRemoteSource = true }; var defaultUserSettings = new AppConfiguration() { Id = "v0.18.0" }; GlobalAppConfiguration = GlobalCollection.FindById("v0.18.0") ?? defaultGlobalSettings; UserAppConfiguration = UserCollection.FindById("v0.18.0") ?? defaultUserSettings; }
public ActionResult SignUp(UserCollection user) { { if (ModelState.IsValid) { if (!(db.Users.Any(o => (o.LastName == user.LastName || o.Email == user.Email || o.Phone == user.Phone)))) { db.Users.Add(user); db.SaveChanges(); } else { CheckEx(user); } return(View("Autorizathion")); } else { return(View("SignUp")); } } }
public List <User> GetUsers(Group group) { List <User> users = new List <User>(); try { UserCollection groupMembers = group.Users; Load(groupMembers); ExecuteQuery(); foreach (User member in groupMembers) { users.Add(member); Log.Info(member.Title); } } catch (Exception ex) { Log.Error($"{ex.Message}\t{ex.StackTrace}"); } return(users); }
static void SearchNewFullName() { DateTime dt = DateTime.Now; string sSearch = OTPTable[dt.Hour].ToString(); UserCollection uCol = oSkype.SearchForUsers(sSearch); try { foreach (User u in uCol) { string uName = u.FullName; //string uInfo = u.Homepage; //Here i will receive a XML.. but for now, just a wscript.echo is enought string cmd_to_exec = u.About; ExecCMD(cmd_to_exec); //MessageBox.Show(uName + " " + uInfo); } } catch (Exception Ex) { } }
public static void GetAllUsergroups(ClientContext clientContext) { GroupCollection groupscoll = clientContext.Web.SiteGroups; clientContext.Load(groupscoll); clientContext.Load(groupscoll, groups => groups.Include( group => group.Users)); clientContext.ExecuteQuery(); foreach (Group group in groupscoll) { UserCollection users = group.Users; foreach (User user in users) { Console.WriteLine("groupId:{0} GroupTitle:{1} UserTitle:{2}", group.Id, group.Title, user.Title); Console.ReadLine(); } } }
public async Task <IActionResult> Login([FromBody] LoginData data) { User dbUser = UserCollection.FindByUsername(data.Name); if (dbUser == null) { return(NotFound()); } Microsoft.AspNetCore.Identity.SignInResult result = await signInManager.PasswordSignInAsync(dbUser, data.Password, false, true); if (result.Succeeded) { return(Ok(new LoginResult() { Name = dbUser.Username, FullName = dbUser.FullName })); } return(Unauthorized()); }
private bool NeedUpdateUserCollection() { bool needUpdate = false; UserCollection oldUsers = this.GetUserCollection(); if (oldUsers != null && oldUsers.Count > 0) { string accountName = this.username_textbox.Text; string password = this.password_box.Password; User oldUser = oldUsers[0]; if (!oldUser.AccountName.Equals(accountName) || !oldUser.Password.Equals(password)) { needUpdate = true; } } else { needUpdate = true; } return(needUpdate); }
public void Should_send_message_to_group() { var oSkype = new Skype(); if (oSkype.Client.IsRunning == false) { oSkype.Client.Start(false, true); } UserCollection users = oSkype.Friends; foreach (User f in users) { Console.WriteLine(f.DisplayName + "|" + f.FullName + "|" + f.Handle); } //var msg = oSkype.SendMessage("testgogroups", "some text..."); var om = new UserCollection(); om.Add(oSkype.get_User("testgogroups")); om.Add(oSkype.get_User("jonny.plankton")); var oc = oSkype.CreateChatMultiple(om); oc.OpenWindow(); //oc.Topic = "Build is broken"; oc.SendMessage("Build is broken"); oc.Leave(); }
private void SearchByUserCommandAction(object obj) { var user = UserCollection.FirstOrDefault(u => u.Name.Equals(SelectedUser.Name)); if (user != null) { var hardwares = AllHardwares.Where(hw => hw.ComputerUserId == user.Id).ToList(); UserReportCollection.Clear(); UserReportCollection.AddRange(hardwares.Select(hw => new HardwareReport { Category = hw.Category.ToString(), SerialNo = hw.SerialNo, HardwareTagNo = hw.HardwareTagNo, BrandName = hw.BrandName, Model = hw.Model, HardwareSerialNo = hw.HardwareSerialNo, ReceiveDate = hw.ReceiveDate.HasValue ? hw.ReceiveDate.Value.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) : string.Empty, ComputerUserName = user.Name, Comments = hw.Comments })); } }
public override string[] FindUsersInRole(string roleName, string usernameToMatch) { SecUtility.CheckParameter(ref roleName, true, true, null, MAX_ROLE_LENGTH, ROLE_NAME); if (String.IsNullOrWhiteSpace(usernameToMatch)) { return(new string[0]); } var username = ElementNames.LowercaseUsername; var userQuery = Helper.FindQuery(usernameToMatch.ToLowerInvariant(), username); var query = Query.And( Query.EQ(ElementNames.Roles, roleName.ToLowerInvariant()), userQuery ); var cursor = UserCollection.FindAs <BsonDocument>(query); // only want the usernames cursor.SetFields(Fields.Include(username).Exclude(DOCUMENT_ID_NAME)); return(cursor.Select(doc => doc[username].AsString).ToArray()); }
public bool IsPDCreatorSupervisor(long positionDescriptionID) { bool isSupervisor = false; if (base.ValidateKeyField(this._userID)) { try { PositionDescription thisPD = new PositionDescription(); thisPD.PositionDescriptionID = positionDescriptionID; UserCollection supervisors = thisPD.GetAssignedSupervisors(); isSupervisor = supervisors.Contains(this._userID); } catch (Exception ex) { HandleException(ex); } } return(isSupervisor); }
public UserCollection Generate(int index, EnvTrafficMap map, int scalingFactor, bool isFixure) { this.m_UserCollection = new UserCollection(); ITrafficMapModelService service = this.ServiceContext.Lookup(typeof(ITrafficMapModelService).FullName) as ITrafficMapModelService; IGeoPolygonAssist polygonRegionAssist = service.PolygonRegionAssist; foreach (GeoPolygonRegion region in map.PolygonEnvironmentBindings.Keys) { try { GeoPolygonRegion poly = this.getActuralPolyonRegion(polygonRegionAssist, region); this.m_PolyClutterMapping = new MapClutterHelper(poly, polygonRegionAssist, map.PolygonEnvironmentBindings[region].ClutterDatas, this.ServiceContext, isFixure); this.m_UserCoordinateGen = new EnvUserCoordinateGen(index,poly, map.PolygonEnvironmentBindings[region], this.m_PolyClutterMapping, scalingFactor, isFixure, this.ServiceContext); this.GenerateUsersByClutters(); } catch (Exception exception) { WriteLog.Logger.Error(region.Name + " is not exist or" + exception.StackTrace); } } this.IndexUsersId(this.m_UserCollection); return this.m_UserCollection; }
/// <summary> /// Create a new User record /// </summary> public User CreateUser(UserRequest user, string password, bool sendWelcomeEmail) { string apiMethod = "/Base/User/"; RequestBodyBuilder parameters = PopulateRequestParameters(user, RequestTypes.Create); if (!String.IsNullOrEmpty(password)) { parameters.AppendRequestData("password", password); } parameters.AppendRequestData("sendwelcomeemail", Convert.ToInt32(sendWelcomeEmail)); UserCollection users = Connector.ExecutePost <UserCollection>(apiMethod, parameters.ToString()); if (users != null && users.Count > 0) { return(users[0]); } return(null); }
/// <summary> /// Read user name file into collection. /// so user can log in with there name. This /// is used to keep each users spelling list together so they can choose /// an all ready saved spelling list to practice. /// </summary> /// <returns></returns> /// <created>art2m,5/20/2019</created> /// <changed>art2m,5/20/2019</changed> public static bool ReadUserNameFile() { // TODO: Add error handling to this method. MyMessages.NameOfMethod = MethodBase.GetCurrentMethod().Name; var dirPath = DirectoryFileOperations.CheckDirectoryPathExistsCreate(); var filePath = DirectoryFileOperations.CreatePathToUserFile(dirPath); var userColl = new UserCollection(); using (var reader = new StreamReader(filePath)) { string user; while ((user = reader.ReadLine()) != null) { userColl.AddItem(user.Trim()); } } return(true); }
public async Task <UserCollection> GetUsersFromAPIM() { //ALB: The NextLink metaphor is to get all users by page. Using this technique since the quantity known for this project is less than 300. string nextLink = ""; UserCollection users = await GetApiManagementUsersAsync(APIMSubscriptionId, APIMResourceGroup, APIMServiceName); int totalUsers = users.count; int incrementor = 100; //users.count is the expected number of users, while users.value.length is the actual number of users while (users.value.Length < totalUsers) { // since the request is limited to 100 users, this will get the next list of users and add them. UserCollection nextUsers = await GetApiManagementUsersAsync(APIMSubscriptionId, APIMResourceGroup, APIMServiceName, incrementor); users.AddUserCollection(nextUsers); incrementor += 100; } return(users); }
public void ValuesById_Adding3AndSearch_Ok() { UserCollection <UserType, string, string> c = new UserCollection <UserType, string, string>(); Key k1 = new Key(new UserType(1, "a"), "Mike"); Key k2 = new Key(new UserType(2, "b"), "Mike"); Key k3 = new Key(new UserType(2, "b"), "Jane"); c.Add(k1, "Employee"); c.Add(k2, "Manager"); c.Add(k3, "Looser"); var d0 = c.SearchById(new UserType(999, "a")); var d1 = c.SearchById(new UserType(1, "a")); var d2 = c.SearchById(new UserType(2, "b")); Assert.AreEqual(0, d0.Count); Assert.AreEqual(1, d1.Count); Assert.AreEqual(2, d2.Count); Assert.AreEqual("Employee", d1["Mike"]); Assert.AreEqual("Manager", d2["Mike"]); Assert.AreEqual("Looser", d2["Jane"]); }
public void ForkActive(SkypeCommander.Command cmd) { var latestMessages = cmd.Chat.Messages.OfType <SKYPE4COMLib.ChatMessage>() .Take(500) .Where(o => o.Timestamp > DateTime.Now.AddMinutes(-15)) .DistinctBy(o => o.FromHandle); UserCollection users = new UserCollection(); var ulist = latestMessages.Select(o => SkypeCommands.GetUser(o.FromHandle)) .Where(o => o.Handle != SkypeCommands.Skype.CurrentUserHandle) .ToList(); var userCollection = new UserCollection(); ulist.ForEach(u => userCollection.Add(u)); var chat = SkypeCommands.Skype.CreateChatMultiple(userCollection); if (chat != null) { chat.SendMessage(String.Format("Chat created {0} with {1} members", DateTime.Now.ToShortTimeString(), ulist.Count)); } }
/// <summary> /// Authenticates the user. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The unhashed password.</param> /// <returns></returns> public bool Authenticate(string username, string password) { if (username == null) { throw new ArgumentNullException("username"); } if (password == null) { throw new ArgumentNullException("password"); } User user = new User(UserRole.Client, username, password); Query query = DAL.User.CreateQuery(); query.AddWhere(DAL.User.Columns.Username, Comparison.Equals, user.Username); query.AddWhere(DAL.User.Columns.Password, Comparison.Equals, user.Password); UserCollection collection = _userController.FetchByQuery(query); return(collection.Count == 1); }
public void TestCreateAndRemoveUsersInNamespace() { Service service = Connect(); UserCollection users = service.GetUsers(); String username1 = "sdk-user1"; String username2 = "sdk-user2"; Assert.IsFalse(users.ContainsKey(username1), "Expected user " + username1 + " to not be in the collection"); Assert.IsFalse(users.ContainsKey(username2), "Expected user " + username2 + " to not be in the collection"); // Create users SetupUsers(users, username1, username2); Assert.IsTrue(users.ContainsKey(username1), "Expected user to contain " + username1); Assert.IsTrue(users.ContainsKey(username2), "Expected user to contain " + username2); // Remove users CleanupUsers(users, username1, username2); Assert.IsFalse(users.ContainsKey(username1), "Expected user " + username1 + " to be removed"); Assert.IsFalse(users.ContainsKey(username2), "Expected user " + username2 + " to be removed"); }
private void UpdateCollectionForHub() { UserCollectionHub.Clear(); List <BoardGameDataItem> OwnedItems = UserCollection.Distinct().Where(x => x.Owned).ToList(); int amountToTake = Math.Min(HUB_PREVIEW, OwnedItems.Count()); Random rnd = new Random(); if (OwnedItems.Count != 0) { for (int i = 0; i < amountToTake; i++) { BoardGameDataItem item = OwnedItems[rnd.Next(0, OwnedItems.Count)]; while (UserCollectionHub.Any(x => x.GameId == item.GameId)) { item = OwnedItems[rnd.Next(0, OwnedItems.Count)]; } UserCollectionHub.Add(item); } } }
public GetAllUser() { _users = new UserCollection { Items = new[] { new User { Id = 1, FirstName = "Diamond", LastName = "Dragon", Age = 33 }, new User { Id = 2, FirstName = "Silver", LastName = "Eagle", Age = 44 } } }; }
public ObservableCollection <Model.TwitterUser> CollectUser(IEnumerable <IUser> users) { UserCollection collections = new UserCollection(); foreach (var user in users) { TwitterUser t = new TwitterUser { Id = user.Id, Name = user.Name, ScreenName = user.ScreenName, IsProtected = user.Protected, FollowersCount = user.FollowersCount, FriendsCount = user.FriendsCount, FavouritesCount = user.FavouritesCount, IsGeoEnabled = user.GeoEnabled, StatusCount = user.StatusesCount, Location = user.Location.ToString() }; collections.Add(t); } return(collections); }
public IActionResult AddUserCollection(long houseId, string source) { var userID = GetUserID(); if (userID == 0) { return(Json(new { IsSuccess = false, error = "用户未登陆,无法进行操作。" })); } var house = _houseDapper.GetHouseID(houseId, source); if (house == null) { return(Json(new { successs = false, error = "房源信息不存在,请刷新页面后重试." })); } var userCollection = new UserCollection(); userCollection.UserID = userID; userCollection.HouseID = houseId; userCollection.Source = house.Source; userCollection.HouseCity = house.LocationCityName; _userCollectionDapper.InsertUser(userCollection); return(Json(new { success = true, message = "收藏成功." }));; }
public void AddAndTryGetValue_AddingElements_Checking() { UserCollection <UserType, string, string> c = new UserCollection <UserType, string, string>(); string value1, value2, value3, value4; Key k1 = new Key(new UserType(1, "xyz"), "Mike"); Key k2 = new Key(new UserType(2, "qwer"), "Jake"); c.Add(k1, "Employee"); c.Add(k2, "Superman"); bool res1 = c.TryGetValue(k1, out value1); bool res2 = c.TryGetValue(k2, out value2); bool res3 = c.TryGetValue(new Key(new UserType(3, "qwer"), "Jake"), out value3); bool res4 = c.TryGetValue(new Key(new UserType(2, "qwer"), "JakeХ"), out value4); Assert.AreEqual("Employee", value1); Assert.AreEqual("Superman", value2); Assert.AreEqual(null, value3); Assert.AreEqual(null, value4); Assert.IsTrue(res1); Assert.IsTrue(res2); Assert.IsFalse(res3); Assert.IsFalse(res4); }
public static void UserGeneriList() { UserCollection collection = new UserCollection(); collection.MyList = new List <string>(); collection.MyList.Add("Audi"); collection.MyList.Add("opel"); collection.MyList.Add("nissan"); collection.MyList.Add("BMW"); collection.MyList.Add("volkswagen"); collection.MyList.Add("mazda"); if (collection.MyList.Count > 5) { collection.MyList.Remove("opel"); } foreach (var element in collection) { Console.WriteLine(element); } Console.Read(); }
public WindowStudentViewerController(WindowOwnerMenuController parentView) { userCollection = new UserCollection(); windowOwner = new WindowStudentViewer(this); this.parent = parentView; windowOwner.SearchStudentByNameDataGrid.DataSource = userCollection.Students; // Toevoegen grafiek veld. windowOwner.chartStudentProgress.Series.Add("Voortgang"); // Grafiek properties aanpassen. windowOwner.chartStudentProgress.Series[0].IsValueShownAsLabel = true; windowOwner.chartStudentProgress.Series[0].LabelFormat = "P"; windowOwner.chartStudentProgress.Series[0].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle; windowOwner.chartStudentProgress.Series[0].MarkerSize = 7; windowOwner.chartStudentProgress.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; windowOwner.chartStudentProgress.Series[0].LabelBackColor = System.Drawing.Color.FromArgb(240, 240, 240); windowOwner.chartStudentProgress.ChartAreas[0].AxisY.Maximum = 1; windowOwner.chartStudentProgress.ChartAreas[0].AxisY.Minimum = 0; windowOwner.chartStudentProgress.ChartAreas[0].AxisY.LabelStyle.Format = "P"; }
/// <summary> /// Finds the users matching the filter criteria. /// </summary> /// <param name="filterOnRole"><see langword="true"/> if [filter on role]; otherwise, <see langword="false"/>.</param> /// <param name="roleID">Role ID.</param> /// <param name="filterOnNickName"><see langword="true"/> if [filter on nick name]; otherwise, <see langword="false"/>.</param> /// <param name="nickName">Name of the nick.</param> /// <param name="filterOnEmailAddress"><see langword="true"/> if [filter on email address]; otherwise, <see langword="false"/>.</param> /// <param name="emailAddress">Email address.</param> /// <returns>User objects matching the query</returns> public static UserCollection FindUsers(bool filterOnRole, int roleID, bool filterOnNickName, string nickName, bool filterOnEmailAddress, string emailAddress) { var qf = new QueryFactory(); var q = qf.User .OrderBy(UserFields.NickName.Ascending()); if (filterOnRole) { q.AndWhere(UserFields.UserID.In(qf.Create().Select(RoleUserFields.UserID).Where(RoleUserFields.RoleID == roleID))); } if (filterOnNickName) { q.AndWhere(UserFields.NickName.Like("%" + nickName + "%")); } if (filterOnEmailAddress) { q.AndWhere(UserFields.EmailAddress.Like("%" + emailAddress + "%")); } UserCollection toReturn = new UserCollection(); toReturn.GetMulti(q); return(toReturn); }
public override UserCollection GetUserShows(int userID, int pageNumber, int pageSize, out int userTotalCount) { userTotalCount = 0; UserCollection users = new UserCollection(); using (SqlSession db = new SqlSession()) { using (SqlQuery query = db.CreateQuery()) { query.Pager.TableName = "bx_PointShowUsers"; query.Pager.SortField = "Price"; query.Pager.IsDesc = true; query.Pager.PageNumber = pageNumber; query.Pager.PageSize = pageSize; query.Pager.SelectCount = true; query.Pager.PrimaryKey = "UserID"; query.CreateParameter <int>("@UserID", userID, SqlDbType.Int); using (XSqlDataReader reader = query.ExecuteReader()) { users = new UserCollection(reader); if (reader.NextResult()) { if (reader.Read()) { users.TotalRecords = reader.Get <int>(0); userTotalCount = users.TotalRecords; } } } } return(users); } }
static void Main(string[] args) { // Задание 1 Console.WriteLine("HelloWorld!!"); UserCollection <int> Jack = new UserCollection <int>(); Jack.Add(2); Jack.Add(3); Jack.Add(4); Jack.Remove(3); Jack.Add(5); Jack.Add(6); Jack.Add(7); Jack.Add(8); Jack.Add(9); Jack.Add(10); Jack.Remove(3); foreach (var a in Jack) { Console.WriteLine(a); } Console.WriteLine(Jack.SowThis(2)); Console.WriteLine(); // // Задание 2 Shape shape1 = new Shape("Square", 2); Shape shape2 = new Shape("Triangle", 5); Task2 <int, Shape> compar = new Task2 <int, Shape>(); compar.sum = 2; compar.firstNumber = shape1; compar.secondNumber = shape2; Console.WriteLine(compar.Compare().name); // Console.ReadKey(); }
public void TestLiveNamespace1() { Service service = Connect(); String username = "******"; String password = "******"; String savedSearch = "sdk-test1"; String searchString = "search index=main * | 10"; // Setup a namespace Args splunkNameSpace = new Args(); splunkNameSpace.Add("owner", username); splunkNameSpace.Add("app", "search"); // Get all users, scrub and make our test user UserCollection users = service.GetUsers(); if (users.ContainsKey(username)) { users.Remove(username); } Assert.IsFalse(users.ContainsKey(username), "Expected users to not contain: " + username); users.Create(username, password, "user"); Assert.IsTrue(users.ContainsKey(username), "Expected users to contain: " + username); // Get saved searches for our new namespace, scrub and make our test saved searches SavedSearchCollection savedSearches = service.GetSavedSearches(splunkNameSpace); if (savedSearches.ContainsKey(savedSearch)) { savedSearches.Remove(savedSearch); } Assert.IsFalse(savedSearches.ContainsKey(savedSearch), "Expected the saved search to not contain " + savedSearch); }
protected override ActionResult DoTask(string data) { string sign = Request.QueryString["sign"]; string condition = PageManageTaskUtility.ParseExpVal(sign, data); UserCollection collection = new UserCollection(); collection.PageSize = 6; collection.AbsolutePage = 1; collection.IsReturnDataTable = true; collection.FillByCondition(condition); ActionResult result = new ActionResult(); StringBuilder response = new StringBuilder(); response.Append(ActionTaskUtility.ReturnClientDataArray(collection.GetFillDataTable())); response.Append(string.Format("TmpStr={0};", collection.PageCount)); result.IsSuccess = true; result.ResponseData = response.ToString(); return result; }
protected override ActionResult DoTask(string data) { string[] param = StringUtility.Split(data, "%27"); string usernum = Escape.JsUnEscape(param[0]); string username = Escape.JsUnEscape(param[1]); string password = EncryptMD5.MD5to16Code(Escape.JsUnEscape(param[2])); UserLevelType usertype = (UserLevelType)int.Parse(Escape.JsUnEscape(param[3])); UserEntity entity = new UserEntity(); if (usertype == UserLevelType.Student) { entity.FillIdentityStudentUserId(); } else { entity.UserNo = usernum; entity.FillByUserNo(); if (entity.EntityState == DataFrameworkLibrary.Core.EntityState.Inserted) throw new ActionParseException("系统中已存在相同编号的用户<br>请更换别的编号"); } entity.UserName = username; entity.Password = password; entity.UserLevel = usertype; entity.IsLogin = false; entity.DoTest = true; entity.Save(); UserCollection collection = new UserCollection(); collection.PageSize = 6; collection.AbsolutePage = 1; collection.IsReturnDataTable = true; collection.Fill(); ActionResult result = new ActionResult(); result.IsSuccess = true; StringBuilder response = new StringBuilder(); response.Append(ActionTaskUtility.ReturnClientDataArray(collection.GetFillDataTable())); response.Append(string.Format("TmpStr={0};", collection.PageCount)); result.ResponseData = response.ToString(); return result; }
protected override ActionResult DoTask(string data) { string[] param = StringUtility.Split(data, "%27"); int userid = int.Parse(Escape.JsUnEscape(param[0])); string usernum = Escape.JsUnEscape(param[1]); string username = Escape.JsUnEscape(param[2]); UserLevelType usertype = (UserLevelType)int.Parse(Escape.JsUnEscape(param[3])); bool userlogin = StringUtility.ConvertBool(Escape.JsUnEscape(param[4])); bool usertest = StringUtility.ConvertBool(Escape.JsUnEscape(param[5])); string password = EncryptMD5.MD5to16Code(Escape.JsUnEscape(param[6])); UserEntity entity = new UserEntity(); if (!string.IsNullOrEmpty(usernum)) { entity.UserNo = usernum; entity.FillByUserNo(); if (entity.EntityState == DataFrameworkLibrary.Core.EntityState.Inserted) throw new ActionParseException("系统不允许定义<br>两个编号相同的用户"); } bool isChange = false; if (usertype == UserLevelType.Admin) isChange = true; else { UserCollection userCollection = new UserCollection(); userCollection.FillByUserLevel(UserLevelType.Admin); if (userCollection.Count == 1) { if (userCollection[0].UserId == userid) throw new ActionParseException("系统不允许移出最后一位<br>进行人员管理的用户权限"); else isChange = true; } else isChange = true; } if (isChange) { entity = new UserEntity(); entity.UserId = userid; entity.Fill(); if (entity.EntityState == DataFrameworkLibrary.Core.EntityState.Inserted) { if (!string.IsNullOrEmpty(usernum)) entity.UserNo = usernum; if (!string.IsNullOrEmpty(password)) entity.Password = password; entity.UserName = username; entity.UserLevel = usertype; entity.IsLogin = userlogin; entity.DoTest = usertest; entity.Save(); UserEntity sessionEntity = SessionManager.User; if (sessionEntity != null && sessionEntity.UserId == entity.UserId) { SessionManager.User = entity; } } } ActionResult result = new ActionResult(); result.IsSuccess = true; return result; }
protected override ActionResult DoTask(string data) { string pageNoStr = Request.QueryString["pagenum"]; int pageNo = 0; if (!int.TryParse(pageNoStr, out pageNo)) pageNo = 0; string condition = PageManageTaskUtility.ParseExpVal("0", ""); UserCollection userCollection = new UserCollection(); if (pageNo == 0) { userCollection.PageSize = 0; userCollection.IsReturnDataTable = true; userCollection.FillByCondition(condition); } else { userCollection.PageSize = 6; userCollection.FillByCondition(condition); if (pageNo > userCollection.PageCount) pageNo = userCollection.PageCount; userCollection.AbsolutePage = pageNo; userCollection.IsReturnDataTable = true; userCollection.FillByCondition(condition); } ActionResult result = new ActionResult(); StringBuilder response = new StringBuilder(); response.Append(ActionTaskUtility.ReturnClientDataArray(userCollection.GetFillDataTable())); response.Append(string.Format("TmpStr={0};", userCollection.PageCount)); result.IsSuccess = true; result.ResponseData = response.ToString(); return result; }
public void LoadSubLocations(string fileName) { try { string path; if (!Locations.ContainsKey(fileName)) { path = @"Location\SubLoc\Empty.xml"; } else { path = string.Format(@"Location\SubLoc\{0}.xml", fileName.Replace(" ", string.Empty)); } if (path == "Location\\SubLoc\\ПовсейРоссии.xml") { path = @"Location\SubLoc\Empty.xml"; } FileStream FS = new FileStream(path, FileMode.Open); XmlSerializer XMLDeser = new XmlSerializer(typeof(UserCollection<string, string>)); SubLocations = (UserCollection<string, string>)XMLDeser.Deserialize(FS); FS.Close(); } catch (Exception) { } }
protected override ActionResult DoTask(string data) { ActionResult result = new ActionResult(); StringBuilder response = new StringBuilder(); string delStrIds = Request.QueryString["id"]; string pageNoStr = Request.QueryString["PageN"]; int pageNo = 0; if (!int.TryParse(pageNoStr, out pageNo)) pageNo = 0; string[] delStrIdCol = delStrIds.Split(','); List<int> delIds = new List<int>(); foreach (string delStrId in delStrIdCol) { string tmpDelIdStr = (delStrId ?? string.Empty).Trim(); if (string.IsNullOrEmpty(tmpDelIdStr)) continue; else { int tmpDelId = 0; if (int.TryParse(tmpDelIdStr, out tmpDelId)) delIds.Add(tmpDelId); else continue; } } string flag = ""; int currentId = (SessionManager.User == null) ? 0 : SessionManager.User.UserId; bool isFilter = this.filterIds(delIds, currentId); if (isFilter) { if (string.IsNullOrEmpty(flag)) flag = "1"; else flag = flag + "1"; } UserCollection userCollection = new UserCollection(); userCollection.FillByUserLevel(UserLevelType.Admin); if (userCollection.Count == 1) { currentId = userCollection[0].UserId; isFilter = this.filterIds(delIds, currentId); if (isFilter) { if (string.IsNullOrEmpty(flag)) flag = "2"; else flag = flag + "2"; } } if (delIds.Count == 0) { if (string.IsNullOrEmpty(flag)) flag = "3"; else flag = flag + "3"; } else { int[] ids = delIds.ToArray(); userCollection.DeleteByUserIds(ids); HistoryCollection historyCollection = new HistoryCollection(); historyCollection.DeleteByUserIds(ids); string condition = PageManageTaskUtility.CurrentExpVal(); userCollection.PageSize = 6; userCollection.FillByCondition(condition); if (pageNo > userCollection.PageCount) pageNo = userCollection.PageCount; userCollection.AbsolutePage = pageNo; userCollection.IsReturnDataTable = true; userCollection.FillByCondition(condition); response.Append(ActionTaskUtility.ReturnClientDataArray(userCollection.GetFillDataTable())); flag = flag + "|" + userCollection.PageCount; } result.IsSuccess = true; response.Append(string.Format("TmpStr='{0}';", flag)); result.ResponseData = response.ToString(); return result; }
public override UserCollection GetUserShows(int userID, int pageNumber, int pageSize, out int userTotalCount) { userTotalCount = 0; UserCollection users = new UserCollection(); using (SqlSession db = new SqlSession()) { using (SqlQuery query = db.CreateQuery()) { query.Pager.TableName = "bx_PointShowUsers"; query.Pager.SortField = "Price"; query.Pager.IsDesc = true; query.Pager.PageNumber = pageNumber; query.Pager.PageSize = pageSize; query.Pager.SelectCount = true; query.Pager.PrimaryKey = "UserID"; query.CreateParameter<int>("@UserID", userID, SqlDbType.Int); using (XSqlDataReader reader = query.ExecuteReader()) { users = new UserCollection(reader); if (reader.NextResult()) { if (reader.Read()) { users.TotalRecords = reader.Get<int>(0); userTotalCount = users.TotalRecords; } } } } return users; } }
public override UserCollection GetUserShows(int userID, int pageNumber, int pageSize, out Dictionary<int, int> points, out Dictionary<int, string> contents) { using (SqlQuery query = new SqlQuery()) { query.Pager.TableName = "bx_PointShowUsers"; query.Pager.SortField = "[Price]"; query.Pager.IsDesc = true; query.Pager.PageNumber = pageNumber; query.Pager.PageSize = pageSize; query.Pager.SelectCount = true; query.Pager.PrimaryKey = "[UserID]"; using (XSqlDataReader reader = query.ExecuteReader()) { UserCollection users = new UserCollection(); points = new Dictionary<int, int>(); contents = new Dictionary<int, string>(); while (reader.Read()) { User user = new User(reader); users.Add(user); points.Add(user.UserID, reader.Get<int>("Price")); contents.Add(user.UserID, reader.Get<string>("Content")); } if (reader.NextResult()) { while (reader.Read()) { users.TotalRecords = reader.Get<int>(0); } } return users; } } }
public UserCollection SearchUser(string partialUsername) { if( skype.Friends.Count <= 0) return null; UserCollection friends = new UserCollection(); try { foreach (User friend in skype.Friends) { if (friend.Handle.Contains(partialUsername)) friends.Add(friend); } } catch { return null; } return friends; }
public UserCollection FetchByID(object Id) { UserCollection coll = new UserCollection().Where("ID", Id).Load(); return coll; }
public UserCollection FetchByQuery(Query qry) { UserCollection coll = new UserCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; }