private async Task SetRostersFromRolesForGoogleSheetsWithBadUrlFails( GoogleSheetsType type, Func <string, Task> setRosters) { Mock <IGoogleSheetsGenerator> mockGenerator = new Mock <IGoogleSheetsGenerator>(); mockGenerator .Setup(generator => generator.TryUpdateRosters(It.IsAny <IByRoleTeamManager>(), It.IsAny <Uri>())) .Returns(Task.FromResult <IResult <string> >(new SuccessResult <string>(string.Empty))); Mock <IGoogleSheetsGeneratorFactory> mockFactory = new Mock <IGoogleSheetsGeneratorFactory>(); mockFactory .Setup(factory => factory.Create(type)) .Returns(mockGenerator.Object); this.InitializeHandler(googleSheetsGeneratorFactory: mockFactory.Object); using (BotConfigurationContext context = this.botConfigurationfactory.Create()) using (DatabaseAction action = new DatabaseAction(context)) { await action.SetTeamRolePrefixAsync(DefaultGuildId, TeamRolePrefix); } await setRosters("this URL does not parse"); this.MessageStore.VerifyChannelMessages( "The link to the Google Sheet wasn't understandable. Be sure to copy the full URL from the address bar."); mockFactory.Verify(factory => factory.Create(It.IsAny <GoogleSheetsType>()), Times.Never); }
public async Task SetNewReaderAsync(IGuildUser newReader) { if (newReader != null && this.Manager.TryGet(this.Context.Channel.Id, out GameState game)) { string readerRolePrefix; using (DatabaseAction action = this.DatabaseActionFactory.Create()) { readerRolePrefix = await action.GetReaderRolePrefixAsync(this.Context.Guild.Id); } if (!newReader.CanRead(this.Context.Guild, readerRolePrefix)) { await this.Context.Channel.SendMessageAsync( @$ "Cannot set {newReader.Mention} as the reader because they do not have a role with the reader prefix " "{readerRolePrefix}" ""); return; } game.ReaderId = newReader.Id; await this.Context.Channel.SendMessageAsync($"{newReader.Mention} is now the reader."); return; } if (this.Context.Channel is IGuildChannel guildChannel) { Logger.Information( "New reader called in guild '{0}' in channel '{1}' with ID that could not be found: {2}", guildChannel.Guild.Name, guildChannel.Name, newReader?.Id); } await this.Context.Channel.SendMessageAsync($"User could not be found. Could not set the new reader."); }
private async Task SetRostersFromRolesForGoogleSheetsSucceeds( GoogleSheetsType type, Func <string, Task> setRosters) { Mock <IGoogleSheetsGenerator> mockGenerator = new Mock <IGoogleSheetsGenerator>(); mockGenerator .Setup(generator => generator.TryUpdateRosters(It.IsAny <IByRoleTeamManager>(), It.IsAny <Uri>())) .Returns(Task.FromResult <IResult <string> >(new SuccessResult <string>(string.Empty))) .Verifiable(); Mock <IGoogleSheetsGeneratorFactory> mockFactory = new Mock <IGoogleSheetsGeneratorFactory>(); mockFactory .Setup(factory => factory.Create(type)) .Returns(mockGenerator.Object); this.InitializeHandler(googleSheetsGeneratorFactory: mockFactory.Object); using (BotConfigurationContext context = this.botConfigurationfactory.Create()) using (DatabaseAction action = new DatabaseAction(context)) { await action.SetTeamRolePrefixAsync(DefaultGuildId, TeamRolePrefix); } await setRosters("http://localhost/sheetsUrl"); mockFactory.Verify(); this.MessageStore.VerifyChannelMessages("Rosters updated."); }
public async Task EnableBonusesAsync() { if (!this.Manager.TryGet(this.Context.Channel.Id, out GameState game)) { // This command only works during a game return; } else if (game.Format.HighestPhaseIndexWithBonus >= 0) { await this.Context.Channel.SendMessageAsync("Bonuses are already tracked."); return; } bool disableBuzzQueue; using (DatabaseAction action = this.DatabaseActionFactory.Create()) { disableBuzzQueue = await action.GetDisabledBuzzQueueAsync(this.Context.Guild.Id); } // TODO: We should look into cloning the format and changing the HighestPhaseIndexWithBonus field. This // would require an argument for how many bonuses to read game.Format = Format.CreateTossupBonusesShootout(disableBuzzQueue); await this.Context.Channel.SendMessageAsync( "Bonuses are now being tracked. Scores for the current question have been cleared."); }
public void Check_IsEmailExist() { bool check = true; bool result = DatabaseAction.IsEmailExist("*****@*****.**"); Assert.AreEqual(check, result); }
public void Check_IsUsernameExist() { bool check = true; bool result = DatabaseAction.IsUsernameExist("P100"); Assert.AreEqual(check, result); }
/// <summary> /// Attempts to map the generic database exception to specific /// application exception. Returns true if existing exception to /// be re-thrown. /// </summary> public static bool HandleDbException(DatabaseAction operation, DbException e) { // Parse exception int messageId; switch (ParseDbException(e, out messageId)) { case DbError.Application: throw new CustomException("Application error", e); case DbError.ForeignKeyViolation: if (operation == DatabaseAction.Delete) { throw new CommonDbException(CustomException.MESSAGE_DELETE_DATA_IN_USE); } break; case DbError.UniqueKeyViolation: case DbError.PrimaryKeyViolation: if (operation == DatabaseAction.Insert || operation == DatabaseAction.Update) { throw new CommonDbException(CustomException.MESSAGE_DUPLICATE_DATA); } break; } return(true); }
public async Task GetPairedChannelAsync([Summary("Text channel mention (#textChannelName)")] ITextChannel textChannel) { if (textChannel == null) { Logger.Information($"Null text channel passed in to GetPairedChannel"); return; } ulong?voiceChannelId; using (DatabaseAction action = this.DatabaseActionFactory.Create()) { voiceChannelId = await action.GetPairedVoiceChannelIdOrNullAsync(textChannel.Id); } if (voiceChannelId == null) { await this.Context.Channel.SendMessageAsync("Channel isn't paired"); return; } IVoiceChannel voiceChannel = await this.Context.Guild.GetVoiceChannelAsync(voiceChannelId.Value); string message = voiceChannel == null ? "The paired voice channel no longer exists" : @$ "Paired voice channel: " "{voiceChannel.Name}" ""; await this.Context.Channel.SendMessageAsync(message); }
private DynDatabaseRequest CreateDatabaseRequest(dynamic args, DatabaseAction action) { var requestProcessor = CreateRequestProcessor(ServerContext); var dbRequest = (DynDatabaseRequest)requestProcessor.Process(args, Request.Query, action); return(dbRequest); }
/// <inheritdoc /> public void Register <TDatabase>(int count, Func <IDatabasePoolContainer <TDatabase> > createIOPoolContainer = null, DatabaseAction <TDatabase> action = null) where TDatabase : IDatabase, new() { IDatabasePoolContainer container; lock (_databaseIOPool) { if (!_databaseIOPool.TryGetValue(typeof(TDatabase), out container)) { container = createIOPoolContainer?.Invoke() ?? throw new ArgumentNullException(nameof(container)); _databaseIOPool.Add(typeof(TDatabase), container); } } if (container is IDatabasePoolContainer <TDatabase> tContainer) { for (int i = 0; i < count; i++) { TDatabase database = new TDatabase(); action?.Invoke(database); tContainer.Add(database); } } }
public void LoginAttempt_Passwordcheck() { var responsestring = "Password is Wrong"; var loginresult = DatabaseAction.LoginAttempt("P100", "P100Psio", out Employee emp); Assert.AreEqual(responsestring, loginresult); }
public object AddPreviousEmployment(string id, PreviousEmployment previousemployment) { try { previousemployment.Employee_id = DatabaseAction.GetEmployeeID(id); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.PreviousEmployments.Add(previousemployment); db.SaveChanges(); return(new Response { Status = "Success", Message = "Employee PreviousEmployments Details Successfully Added" }); } catch (Exception ex) { LogFile.WriteLog(ex); return(BadRequest()); } }
public object PostEducation1(string id, Education education) { try { education.Employee_id = DatabaseAction.GetEmployeeID(id); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (DatabaseAction.IsCourseExist(education.Employee_id, education.CourseCode)) { return(new Response { Status = "Coursecheck", Message = "Course Data Already Exist" }); } db.Educations.Add(education); db.SaveChanges(); //LogFile.SubmissionLog(education.Employee_id); return(new Response { Status = "Success", Message = "Data Successfully" }); } catch (Exception ex) { LogFile.WriteLog(ex); return(BadRequest()); } }
/// <summary> /// Sends a request to change data into the database queue. Processing is asynchronous /// and you cannot reliably retrieve the data directly from the database immediately afterwards. /// However, data in the cache will be up to date as soon as a value is changed. /// </summary> public void SubmitDataChange(DatabaseAction action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } if (action.Data == null) { throw new ArgumentNullException(nameof(action.Data)); } var actionType = action.Action; foreach (var item in action.Data) { if (actionType == DatabaseActionType.Insert || actionType == DatabaseActionType.Update) { SetIntoCache(item.GetType(), GetEntityKey(item), item); } else if (actionType == DatabaseActionType.Delete) { DeleteFromCache(item.GetType(), GetEntityKey(item)); } } DataQueue.Enqueue(action); }
public async Task SetReaderAsync() { IGuildUser user = await this.Context.Guild.GetUserAsync(this.Context.User.Id); if (user == null) { // If the reader doesn't exist anymore, don't start a game. return; } // This needs to happen before we try creating a game string readerRolePrefix; using (DatabaseAction action = this.DatabaseActionFactory.Create()) { readerRolePrefix = await action.GetReaderRolePrefixAsync(this.Context.Guild.Id); } if (!user.CanRead(this.Context.Guild, readerRolePrefix)) { await this.Context.Channel.SendMessageAsync( @$ "{user.Mention} can't read because they don't have a role starting with the prefix " "{readerRolePrefix}" "."); return; } if (!(this.Manager.TryGet(this.Context.Channel.Id, out GameState state) || this.Manager.TryCreate(this.Context.Channel.Id, out state))) { // Couldn't add a new reader. return; }
public void Correctly_constructs_action_executors() { DatabaseAction[] actions = new DatabaseAction[] { DatabaseAction.Create, DatabaseAction.Update }; MockRepository mocks = new MockRepository(); IDatabaseActionResolver resolver = mocks.CreateMock <IDatabaseActionResolver>(); IDataBaseActionLocator locator = mocks.CreateMock <IDataBaseActionLocator>(); IDatabaseActionExecutor creator = mocks.CreateMock <IDatabaseActionExecutor>(); IDatabaseActionExecutor updater = mocks.CreateMock <IDatabaseActionExecutor>(); using (mocks.Record()) { Expect.Call(resolver.GetActions(RequestedDatabaseAction.Create)).Return(actions); Expect.Call(locator.CreateInstance(DatabaseAction.Create)).Return(creator); Expect.Call(locator.CreateInstance(DatabaseAction.Update)).Return(updater); } using (mocks.Playback()) { IDatabaseActionExecutorFactory factory = new DatabaseActionExecutorFactory(resolver, locator); IEnumerable <IDatabaseActionExecutor> executors = factory.GetExecutors(RequestedDatabaseAction.Create); IList <IDatabaseActionExecutor> executorList = new List <IDatabaseActionExecutor>(executors); Assert.That(executorList, Is.EqualTo(new IDatabaseActionExecutor[] { creator, updater })); } mocks.VerifyAll(); }
public async Task CanSetUserWithReaderRoleAsNewReader() { using (BotConfigurationContext context = this.botConfigurationfactory.Create()) using (DatabaseAction action = new DatabaseAction(context)) { await action.SetReaderRolePrefixAsync(DefaultGuildId, "Reader"); } ulong newReaderId = GetExistingNonReaderUserId(); string newReaderMention = $"@User_{newReaderId}"; this.CreateHandler( out ReaderCommandHandler handler, out GameState currentGame, out MessageStore messageStore); currentGame.ReaderId = DefaultReaderId; Mock <IGuildUser> mockUser = new Mock <IGuildUser>(); mockUser.Setup(user => user.Id).Returns(newReaderId); mockUser.Setup(user => user.Mention).Returns(newReaderMention); mockUser.Setup(user => user.RoleIds).Returns(new ulong[] { DefaultReaderRoleId }); await handler.SetNewReaderAsync(mockUser.Object); Assert.AreEqual(newReaderId, currentGame.ReaderId, "Reader ID was not set correctly."); Assert.AreEqual(1, messageStore.ChannelMessages.Count, "Unexpected number of messages sent."); string expectedMessage = $"{newReaderMention} is now the reader."; messageStore.VerifyChannelMessages(expectedMessage); }
public void LoginAttempt_InvalidCredentials() { var responsestring = "Invalid Credentials"; var loginresult = DatabaseAction.LoginAttempt("P1000", "P100Psio", out Employee emp); Assert.AreEqual(responsestring, loginresult); }
public void AddMethodTest() { //Arrange string f = "Joann"; string l = "Alvarez"; string expected = "Joann Alvarez"; string actual = ""; //Act Person person = new Person { firstName = f, lastName = l }; DatabaseAction.AddToDatabase(person); DatabaseAction.Save(); var people = DatabaseAction.Search(1, "Joann"); foreach (Person p in people) { actual = p.firstName + " " + p.lastName; } //Assert Assert.AreEqual(expected, actual); }
private async Task <Response> HandleCreateRuleRequestAsync(dynamic args) { return(await Task.Run(() => { (string dbid, string path, string keyid) = ParseRulesRequestArgs((DynamicDictionary)args, Request); var ruleList = GetCurrentRuleList(dbid, keyid); if (ruleList == null) { return HttpStatusCode.BadRequest; } var allowRule = (string)Request.Query.allow == "1"; // whether the rule should set allow to true var priority = -1; int.TryParse((string)Request.Query.priority, out priority); DatabaseAction ruleFlags = 0; try { var ruleTypes = ((string)Request.Query.type).Split('|') .Select(x => (DatabaseAction)Enum.Parse(typeof(DatabaseAction), x)); foreach (var ruleType in ruleTypes) { ruleFlags |= ruleType; } } catch { return HttpStatusCode.BadRequest; } var rule = new SecurityRule(new Regex(path), ruleFlags, allowRule, priority); ruleList.Add(rule); return Response.AsJsonNet(rule); })); }
public async Task GetDefaultFormatAsync() { Task <bool> useBonuses; Task <bool> disableBuzzQueue; Task <string> readerRolePrefix; Task <string> teamRolePrefix; using (DatabaseAction action = this.DatabaseActionFactory.Create()) { // TODO: Should we make this one call so we don't need to await on all of them (and we could do it // with one SELECT instead of 3)? useBonuses = action.GetUseBonusesAsync(this.Context.Guild.Id); disableBuzzQueue = action.GetDisabledBuzzQueueAsync(this.Context.Guild.Id); readerRolePrefix = action.GetReaderRolePrefixAsync(this.Context.Guild.Id); teamRolePrefix = action.GetTeamRolePrefixAsync(this.Context.Guild.Id); await Task.WhenAll(useBonuses, disableBuzzQueue, readerRolePrefix, teamRolePrefix); } Logger.Information($"getDefaultFormat called in guild {this.Context.Guild.Id} by user {this.Context.User.Id}"); EmbedBuilder builder = new EmbedBuilder() { Title = "Default Format", Description = "The default settings for games in this server" }; builder.AddField("Require scoring bonuses?", useBonuses.Result ? "Yes" : "No"); builder.AddField("Queue buzzes?", disableBuzzQueue.Result ? "No" : "Yes"); builder.AddField( "Reader role prefix?", readerRolePrefix.Result == null ? "None set" : @$ "Yes: " "{readerRolePrefix.Result}" ""); builder.AddField( "Team role prefix?", teamRolePrefix.Result == null ? "None set" : @$ "Yes: " "{teamRolePrefix.Result}" ""); await this.Context.Channel.SendMessageAsync(embed : builder.Build()); }
private void ActionRecord(int rowHandle, DatabaseAction action) { var value = OptionsGrid.GridView.GetRowCellValue(rowHandle, OptionsGrid.DataKeyName); var paramInt = 0; var paramString = string.Empty; var paramGuid = Guid.Empty; var paramDateTime = DateTime.Now; if (value is int) { paramInt = (int)value; } else if (value is string) { paramString = (string)value; } else if (value is Guid) { paramGuid = (Guid)value; } else if (value is DateTime) { paramDateTime = (DateTime)value; } var e = new ActionRecordEventArgs(paramInt, paramString, paramGuid, paramDateTime, action); DictionaryManager.ActionRecord(ObjectName, e.ParamInt, e.ParamString, e.ParamDateTime, e.ParamGuid, 0, string.Empty, DateTimeHelper.MinDate, Guid.Empty, e.Action, BaseGlobalVariable.UserID, IsOnline); }
public IHttpActionResult PutProof(string id, List <Proof> proof) { try { var empid = DatabaseAction.GetEmployeeID(id); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } foreach (var vp in proof) { db.Entry(vp).State = EntityState.Modified; } db.SaveChanges(); return(Ok("Proof Details Updated Successfully")); } catch (Exception ex) { LogFile.WriteLog(ex); return(BadRequest()); } }
public IHttpActionResult GetProof(string id) { try { var empId = DatabaseAction.GetEmployeeID(id); if (empId != null) { var listOfProof = db.Proofs.Where(x => x.Employee_id == empId).Select(emp => new { Proof_id = emp.Proof_id, Employee_id = emp.Employee_id, ProofCode = emp.ProofCode, ProofName = emp.ProofName, ProofId = emp.ProofId, }); return(Ok(listOfProof.ToList())); } else { return(BadRequest("Not Found")); } } catch (Exception ex) { LogFile.WriteLog(ex); return(BadRequest()); } }
public IHttpActionResult GetAttendance(string id) { try { var empId = DatabaseAction.GetEmployeeID(id); if (empId != null) { var listOfEducations = db.Educations.Where(x => x.Employee_id == empId).Select(edu => new { Education_id = edu.Education_id, Employee_id = edu.Employee_id, Course = edu.Course, CourseCode = edu.CourseCode, Institute = edu.Institute, GradePoint = edu.GradePoint, From = edu.From, To = edu.To, YearOfPassing = edu.YearOfPassing }); return(Ok(listOfEducations.ToList())); } else { return(BadRequest("Not Found")); } } catch (Exception ex) { LogFile.WriteLog(ex); return(BadRequest()); } }
public async Task PairChannelsAsync(ITextChannel textChannel, string voiceChannelName) { if (textChannel == null || voiceChannelName == null) { Logger.Information($"Null text channel or voice channel name passed in to PairChannels"); return; } IReadOnlyCollection <IVoiceChannel> voiceChannels = await this.Context.Guild.GetVoiceChannelsAsync(); IVoiceChannel voiceChannel = voiceChannels .FirstOrDefault(channel => channel.Name.Trim().Equals( voiceChannelName.Trim(), StringComparison.InvariantCultureIgnoreCase)); if (voiceChannel == null) { Logger.Information("Could not find voice channel with the given name"); await this.Context.Channel.SendMessageAsync("Cannot find a voice channel with that name"); return; } using (DatabaseAction action = this.DatabaseActionFactory.Create()) { await action.PairChannelsAsync(this.Context.Guild.Id, textChannel.Id, voiceChannel.Id); } Logger.Information( $"Channels {textChannel.Id} and {voiceChannel.Id} paired successfully by user {this.Context.User.Id}"); await this.Context.Channel.SendMessageAsync("Text and voice channel paired successfully"); }
public DatabaseAction SaveQueue <T>(T entity) where T : class, IEntity { DatabaseAction databaseAction = DatabaseAction.Failed; try { var e = entity as Entity; if (!e.Id.HasValue) { UpdateChildModels(entity, 0); GetDatabase().Set <T>().Add(entity); databaseAction = DatabaseAction.Inserted; } else { UpdateChildModels(entity, 0); GetDatabase().Entry(entity).State = EntityState.Modified; databaseAction = DatabaseAction.Updated; } } catch (Exception ex) { _logger.LogError(ex.Message); } return(databaseAction); }
public DynDatabaseRequest Process(dynamic args, dynamic query, DatabaseAction dbAction) { // Read basic parameters var path = (string)args.path ?? ""; // null paths aren't valid var databaseId = (string)args.dbid; // database ID is required! var authItem = (string)query.auth; // Create request shell // Add trailing slash if (path.Length > 1 && !path.EndsWith("/", StringComparison.Ordinal)) { path += "/"; } var dbRequest = new DynDatabaseRequest { AuthToken = authItem, Path = path, DatabaseId = databaseId, Valid = databaseId != null, State = PermissionState.Denied, RequestedAction = dbAction }; return(ValidateAccess(dbRequest)); }
public void UpdateMethodTest() { //Arrange string change = "David"; int opt = 1; string expected = "David Alvarez"; string actual = ""; //Act var people = DatabaseAction.Search(1, "Joann"); Person person = new Person(); foreach (Person p in people) { person = p; } DatabaseAction.Edit(ref opt, person, change); var newPeople = DatabaseAction.Search(1, "David"); foreach (Person p1 in newPeople) { actual = p1.firstName + " " + p1.lastName; } //Assert Assert.AreEqual(expected, actual); }
public IHttpActionResult GetPreviousEmployment(string id) { try { var empId = DatabaseAction.GetEmployeeID(id); if (empId != null) { var listOfPreviousEmployment = db.PreviousEmployments.Where(x => x.Employee_id == empId).Select(emp => new { PreviousEmployment_id = emp.PreviousEmployment_id, Employee_id = emp.Employee_id, EmployerName = emp.EmployerName, StartDate = emp.StartDate, EndDate = emp.EndDate, Designation = emp.Designation, Salary = emp.Salary }); return(Ok(listOfPreviousEmployment.ToList())); } else { return(BadRequest("Not Found")); } } catch (Exception ex) { LogFile.WriteLog(ex); return(BadRequest()); } }
/// <summary> /// Add a database error log /// </summary> /// <param name="objectName">table or view name</param> /// <param name="dbAction">either retrieve, update, delete</param> /// <param name="ex"></param> public static void AddDatabaseError(string objectName, DatabaseAction dbAction, Exception ex) { string logMessage = string.Empty; switch (dbAction) { case DatabaseAction.Select: logMessage = "Error occurred when retrieve data from table " + objectName; break; case DatabaseAction.Insert: logMessage = "Error occurred when insert data to table " + objectName; break; case DatabaseAction.Update: logMessage = "Error occurred when update data to table " + objectName; break; case DatabaseAction.Delete: logMessage = "Error occurred when delete data from table " + objectName; break; } AddError(logMessage, ex); }
private void file_TagAdded(FileWithTags sender, FileWithTags.FileWithTagsEventArgs e) { // Set the action of the database this.currentAction = DatabaseAction.AddingTag; // If it's the first tag of the file, remove the Empty tag from the database if (sender.Tags.Count == 1) // After the tag was added this.removeTag(""); // Add the tag this.addTag(e.Tag.Value); // Set the ending of the action this.currentAction = DatabaseAction.Idle; // Raise the DatabaseChange event this.raiseEvent(DatabaseAction.AddingTag, sender, e.Tag); }
private void raiseEvent(DatabaseAction action, FileWithTags file, FileTag tag) { TagFilesDatabaseEventArgs e = new TagFilesDatabaseEventArgs(file, tag); if (action == DatabaseAction.AddingTag) { if (this.TagAdded != null) this.TagAdded(this, e); } else if (action == DatabaseAction.RemovingTag) { if (this.TagRemoved != null) this.TagRemoved(this, e); } else if (action == DatabaseAction.RemovingFile) { if (this.FileRemoved != null) this.FileRemoved(this, e); } else if (action == DatabaseAction.AddingFile) { if (this.FileAdded != null) this.FileAdded(this, e); } }
// A file from the list of files notifies that one of its tags has been removed or that a new tag has been added private void file_TagRemoved(FileWithTags sender, FileWithTags.FileWithTagsEventArgs e) { // Set the action of the database this.currentAction = DatabaseAction.RemovingTag; // Remove the tag this.removeTag(e.Tag.Value); // If no more tags remains, add to the database the Empty tag if (sender.Tags.Count == 0) { this.addTag(""); } // Set the ending of the action this.currentAction = DatabaseAction.Idle; // Raise the DatabaseChange event this.raiseEvent(DatabaseAction.RemovingTag, sender, e.Tag); }
// ********************************************************************************* // #endregion #region Constructor /// <summary> /// Constrauctor: Initialize new instance of "TagFilesDatabase" /// </summary> public TagFilesDatabase() { this.files = new RaisingEventsList<FileWithTags>(); this.files.ItemAdded += new RaisingEventsList<FileWithTags>.RaisingEventsListEventsHandler(files_ItemAdded); this.files.ItemRemoved += new RaisingEventsList<FileWithTags>.RaisingEventsListEventsHandler(files_ItemRemoved); this.tags = new RaisingEventsList<FileTag>(); this.tags.ItemAdding += new RaisingEventsList<FileTag>.RaisingEventsListEventsHandler(tags_ItemAdding); this.tags.ItemAdded += new RaisingEventsList<FileTag>.RaisingEventsListEventsHandler(tags_ItemAdded); this.tags.ItemRemoving += new RaisingEventsList<FileTag>.RaisingEventsListEventsHandler(tags_ItemRemoving); this.tags.ItemRemoved += new RaisingEventsList<FileTag>.RaisingEventsListEventsHandler(tags_ItemRemoved); this.counters = new List<int>(); this.currentAction = DatabaseAction.Idle; this.groupsNames.Add("ללא קבוצה"); this.groupsKeys.Add("*"); }
private void files_ItemAdded(RaisingEventsList<FileWithTags> sender, RaisingEventsList<FileWithTags>.RaisingEventsListEventArgs e) { // Set the action of the database this.currentAction = DatabaseAction.AddingFile; // Add the file's tags FileWithTags file = e.Item; foreach (FileTag tag in file.Tags) { this.addTag(tag.Value); } // If the file has no tags, add the Empty tag if (file.Tags.Count == 0) { this.addTag(""); } // Set the ending of the current action this.currentAction = DatabaseAction.Idle; // Register to the file's events e.Item.TagAdded += new FileWithTags.FileWithTagsEventHandler(this.file_TagAdded); e.Item.TagRemoved += new FileWithTags.FileWithTagsEventHandler(this.file_TagRemoved); // Raise the DatabaseChange event this.raiseEvent(DatabaseAction.AddingFile, file, null); }