protected void ExecuteTest(TestLogic testLogic) { //Setup Generic Database var resourceManager = _serviceResolver.GetService <IResourceManager>(); File.WriteAllBytes($"BBSGEN.DB", resourceManager.GetResource("MBBSEmu.Assets.BBSGEN.DB").ToArray()); File.WriteAllBytes($"BBSUSR.DB", resourceManager.GetResource("MBBSEmu.Assets.BBSUSR.DB").ToArray()); CopyModuleToTempPath(ResourceManager.GetTestResourceManager()); //Setup and Run Host with only the MBBSEMU module var host = _serviceResolver.GetService <IMbbsHost>(); var moduleConfigurations = new List <ModuleConfiguration> { new ModuleConfiguration { ModuleIdentifier = "MBBSEMU", ModulePath = _modulePath, MenuOptionKey = null } }; host.Start(moduleConfigurations); _session = new TestSession(host); host.AddSession(_session); testLogic(_session, host); host.Stop(); host.WaitForShutdown(); }
protected void ExecuteTest(TestLogic testLogic) { ServiceResolver serviceResolver = new ServiceResolver(ServiceResolver.GetTestDefaults()); //Setup Generic Database var resourceManager = serviceResolver.GetService <IResourceManager>(); File.WriteAllBytes($"BBSGEN.DAT", resourceManager.GetResource("MBBSEmu.Assets.BBSGEN.VIR").ToArray()); CopyModuleToTempPath(ResourceManager.GetTestResourceManager()); var modules = new List <MbbsModule> { new MbbsModule(serviceResolver.GetService <IFileUtility>(), serviceResolver.GetService <ILogger>(), "MBBSEMU", _modulePath) }; //Setup and Run Host var host = serviceResolver.GetService <IMbbsHost>(); foreach (var m in modules) { host.AddModule(m); } host.Start(); _session = new TestSession(host); host.AddSession(_session); testLogic(_session); host.Stop(); host.WaitForShutdown(); }
public void BTRIEVE_EXE() { var stdoutStream = new MemoryStream(); var stdout = new TextWriterStream(new StreamWriter(stdoutStream)); CopyModuleToTempPath(ResourceManager.GetTestResourceManager()); ExeRuntime exeRuntime = new ExeRuntime( new MZFile(Path.Combine(_modulePath, _runtimeFiles[0])), _serviceResolver.GetService <IClock>(), _serviceResolver.GetService <ILogger>(), _serviceResolver.GetService <IFileUtility>(), _modulePath, null, new TextReaderStream(Console.In), stdout, stdout); exeRuntime.Load(new string[] { Path.Combine(_modulePath, _runtimeFiles[1]) }); exeRuntime.Run(); stdout.Flush(); stdoutStream.Seek(0, SeekOrigin.Begin); var output = Encoding.ASCII.GetString(stdoutStream.ToArray()); output.Should().Be(GetExpectedOutput(Path.Combine(_modulePath, _runtimeFiles[1]))); }
public MBBSEmuIntegrationTestBase() { _serviceResolver = new ServiceResolver(SessionBuilder.ForTest($"MBBSDb_{RANDOM.Next()}")); _serviceResolver.GetService <IAccountRepository>().Reset("sysop"); _serviceResolver.GetService <IAccountKeyRepository>().Reset(); Directory.CreateDirectory(_modulePath); }
/// <summary> /// Performs a Database Reset /// /// Deletes the Accounts Table and sets up a new SYSOP and GUEST user /// </summary> private void DatabaseReset() { _logger.Info("Resetting Database..."); var acct = _serviceResolver.GetService <IAccountRepository>(); if (acct.TableExists()) { acct.DropTable(); } acct.CreateTable(); if (string.IsNullOrEmpty(_newSysopPassword)) { var bPasswordMatch = false; while (!bPasswordMatch) { Console.Write("Enter New Sysop Password: "******"Re-Enter New Sysop Password: "******"Password mismatch, please tray again."); } } } var sysopUserId = acct.InsertAccount("sysop", _newSysopPassword, "*****@*****.**"); var guestUserId = acct.InsertAccount("guest", "guest", "*****@*****.**"); var keys = _serviceResolver.GetService <IAccountKeyRepository>(); if (keys.TableExists()) { keys.DropTable(); } keys.CreateTable(); //Keys for SYSOP keys.InsertAccountKey(sysopUserId, "DEMO"); keys.InsertAccountKey(sysopUserId, "NORMAL"); keys.InsertAccountKey(sysopUserId, "SUPER"); keys.InsertAccountKey(sysopUserId, "SYSOP"); //Keys for GUEST keys.InsertAccountKey(guestUserId, "DEMO"); keys.InsertAccountKey(guestUserId, "NORMAL"); _logger.Info("Database Reset!"); }
public Int21h_Tests() { var streamWriter = new StreamWriter(_consoleOutput) { AutoFlush = true }; _serviceResolver = new ServiceResolver(_fakeClock); _memory = new RealModeMemoryCore(_serviceResolver.GetService <ILogger>()); _int21 = new Int21h(_registers, _memory, _fakeClock, _serviceResolver.GetService <ILogger>(), _serviceResolver.GetService <IFileUtility>(), new TextReaderStream(new StreamReader(_consoleInput)), new TextWriterStream(streamWriter), new TextWriterStream(streamWriter)); }
private void Run(string[] args) { var serviceResolver = new ServiceResolver(); var logger = serviceResolver.GetService <ILogger>(); if (args.Length == 0) { Console.WriteLine("Usage: MBBSDatabase [view|convert] [files]"); } var convert = (args[0] == "convert"); foreach (string s in args.Skip(1)) { BtrieveFile file = new BtrieveFile(); try { file.LoadFile(logger, s); if (convert) { using var processor = new BtrieveFileProcessor(); processor.CreateSqliteDB(Path.ChangeExtension(s, ".DB"), file); } } catch (Exception e) { logger.Error(e, $"Failed to load Btrieve file {s}: {e.Message}\n{e.StackTrace}"); } } }
public async Task SampleRequestCache() { TestingResourcesHelper.PreapareTestingDirectory(ServiceResolver.GetService <IAppConfigurationService>()); var requestTestingService = ServiceResolver.GetService <IRequestService>() as RequestTestingService; //return match in progress requestTestingService.AddTestingRule( new System.Text.RegularExpressions.Regex("https://reqres.in/api/products/3"), RequestTestingService.RequestTestingServiceMode.ReturnPredefinedResult, new RequestResponseWrapper() { ResponseContent = TestingResourcesHelper.GetApiResoponses("Product3.json"), IsSuccess = true }); var queryCacheService = ServiceResolver.GetService <IQueryCacheService>() as AOEMatchDataProvider.Services.Default.QueryCacheService; //cast to specified service to get access for internal props queryCacheService.Load(); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(timeout); var requestResponseWrapper = await queryCacheService.GetOrUpdate(productRequest, cancellationTokenSource.Token, DateTime.UtcNow.AddYears(1000)); if (!requestResponseWrapper.IsSuccess) { Assert.Fail("Request failed"); } Assert.IsTrue(queryCacheService.Queries.CachedQueries.ContainsKey(productRequest), "Cache should exists"); var requestResponseWrapperFromCache = await queryCacheService.GetOrUpdate(productRequest, cancellationTokenSource.Token, DateTime.UtcNow.AddYears(1000)); Assert.AreEqual(requestResponseWrapper, requestResponseWrapperFromCache); }
public async Task TestMatchProcessingConnectionError() { var requestTestingService = ServiceResolver.GetService <IRequestService>() as RequestTestingService; var matchService = ServiceResolver.GetService <IMatchProcessingService>(); //return match in progress requestTestingService.AddTestingRule( new System.Text.RegularExpressions.Regex("https://aoe2.net/api/player/lastmatch?"), RequestTestingService.RequestTestingServiceMode.ThrowHttpError); var matchState = await matchService.TryUpdateCurrentMatch(); Assert.IsTrue(matchState == MatchUpdateStatus.ConnectionError); requestTestingService.ClearCustomRules(); //return match in progress requestTestingService.AddTestingRule( new System.Text.RegularExpressions.Regex("https://aoe2.net/api/player/lastmatch?"), RequestTestingService.RequestTestingServiceMode.ThrowTimedoutError); var timedOutMatchState = await matchService.TryUpdateCurrentMatch(); Assert.IsTrue(timedOutMatchState == MatchUpdateStatus.ConnectionError); requestTestingService.ClearCustomRules(); }
public void UsersTest() { var userService = serviceResolver.GetService <IUserService>(); (var found, var user) = userService.FindMatchingUser("*****@*****.**"); Assert.True(found); }
private void DataGrid_AddingNewItem(object sender, AddingNewItemEventArgs e) { e.NewItem = new RelationDescription() { UserId = ServiceResolver.GetService <IUserProvider>().GetUserId() }; }
private void DataGrid_AddingNewItem_1(object sender, AddingNewItemEventArgs e) { e.NewItem = new RelationAccountNumber() { UserId = ServiceResolver.GetService <IUserProvider>().GetUserId() }; }
public ClientChangeCommand(StateManager stateManager) : base(stateManager) { FolderService = ServiceResolver.GetService <IFolderService>(); EmailService = ServiceResolver.GetService <IEmailService>(); ContactService = ServiceResolver.GetService <IContactService>(); }
public TelnetSession(Socket telnetConnection) : base(telnetConnection.RemoteEndPoint.ToString()) { SessionType = EnumSessionType.Telnet; SendToClientMethod = Send; _host = ServiceResolver.GetService <IMbbsHost>(); _logger = ServiceResolver.GetService <ILogger>(); _telnetConnection = telnetConnection; _telnetConnection.ReceiveTimeout = (1000 * 60) * 5; //5 Minutes _telnetConnection.ReceiveBufferSize = socketReceiveBuffer.Length; _telnetConnection.Blocking = false; SessionState = EnumSessionState.Negotiating; _senderThread = new Thread(SendWorker); _senderThread.Start(); //Add this Session to the Host _host.AddSession(this); Send(ANSI_ERASE_DISPLAY); Send(ANSI_RESET_CURSOR); SessionState = EnumSessionState.Unauthenticated; ListenForData(); }
private void ResetCategoriesLinkPercentages(Transaction entity) { double totalPercentage = entity.CategoryLinks.Sum(b => b.Percentage); if (totalPercentage < 100) { CategoryTransactionLink categoryTransactionLink = new CategoryTransactionLink(); categoryTransactionLink.Percentage = 100 - totalPercentage; categoryTransactionLink.Transaction = entity; categoryTransactionLink.TransactionID = entity.ID; categoryTransactionLink.UserId = ServiceResolver.GetService <IUserProvider>().GetUserId(); entity.CategoryLinks.Add(categoryTransactionLink); } else if (totalPercentage > 100) { double hasToBeLess = totalPercentage - 100; var link = entity.CategoryLinks.Last(); while (link != null && entity.CategoryLinks.Sum(b => b.Percentage) > 100) { if (hasToBeLess > link.Percentage) { hasToBeLess -= link.Percentage; link.Percentage = 0; } else { link.Percentage -= hasToBeLess; } link = entity.CategoryLinks.Skip(entity.CategoryLinks.IndexOf(link) - 1).FirstOrDefault(); } } }
public void SaveCollectionStateTest() { var stateManager = new StateManager(ServiceResolver.GetService <IStateMachine>()); stateManager.UserDevice = new UserDevice() { DeviceId = "100" }; var syncKey = stateManager.GetNewSyncKey("0"); var collState = new CollectionState() { FolderId = "12321", Collections = new List <SyncItemState>() { new SyncItemState() { ServerId = "12334", HashKey = "3242342342" }, new SyncItemState() { ServerId = "12334", HashKey = "3242342342" } } }; stateManager.SaveCollectionState(syncKey, collState); var savedCollState = stateManager.LoadCollectionState(syncKey, collState.FolderId); }
protected override void Initialize(string xmlRequest) { if (string.IsNullOrWhiteSpace(xmlRequest)) { throw new InvalidRequestException("SendMail Request Content is Empty."); } var root = XDocument.Parse(xmlRequest).Root; this.ClientId = root.GetElementValueAsString(ComposeMailStrings.ClientId); var sourceEl = root.GetElement(ComposeMailStrings.Source); if (sourceEl != null) { this.Source = new Source() { FolderId = sourceEl.GetElementValueAsString(ComposeMailStrings.FolderId), ItemId = sourceEl.GetElementValueAsString(ComposeMailStrings.ItemId), LongId = sourceEl.GetElementValueAsString(ComposeMailStrings.LongId), InstanceId = sourceEl.GetElementValueAsString(ComposeMailStrings.InstanceId) }; } this.AccountId = root.GetElementValueAsString(ComposeMailStrings.AccountId); this.SaveInSentItems = root.HasChildElement(ComposeMailStrings.SaveInSentItems); var mimeString = root.GetElementValueAsString(ComposeMailStrings.Mime); mimeString = mimeString.Replace("\n", "\r\n"); this.Mime = Encoding.UTF8.GetBytes(mimeString); MailService = ServiceResolver.GetService <IEmailService>(); }
public static IAppBuilder UseDomainAssemblyResolver( this IAppBuilder app) { if (app == null) { throw new ArgumentNullException(nameof(app)); } var domainAssemblyResolver = ServiceResolver.GetService <DomainAssemblyResolver>(); if (domainAssemblyResolver == null) { throw new InvalidOperationException( "Serive collection could not resolve FolderWatchdog instance, Please configure service at Startup"); } OwinContext owinContext = new OwinContext(app.Properties); CancellationToken cancellationToken = owinContext.Get <CancellationToken>("host.OnAppDisposing"); if (cancellationToken == new CancellationToken()) { cancellationToken = owinContext.Get <CancellationToken>("server.OnDispose"); } if (cancellationToken == new CancellationToken()) { throw new InvalidOperationException("Current OWIN environment does not contain an instance of the `CancellationToken` class neither under `host.OnAppDisposing`, nor `server.OnDispose` key.\r\nPlease use another OWIN host or create an instance of the `DomainAssemblyResolver` class manually."); } cancellationToken.Register(new Action(domainAssemblyResolver.Dispose)); domainAssemblyResolver.Start(); return(app); }
protected override void Initialize(string xmlRequest) { if (string.IsNullOrWhiteSpace(xmlRequest)) { throw new InvalidRequestException("Ping Request Content is Empty."); } FolderService = ServiceResolver.GetService <IFolderService>(); EmailService = ServiceResolver.GetService <IEmailService>(); ContactService = ServiceResolver.GetService <IContactService>(); var root = XDocument.Parse(xmlRequest).Root; this.HeartbeatInterval = root.GetElementValueAsInt(PingStrings.HeartbeatInterval); var folderEls = root.GetDescendants(PingStrings.Folder); this.Folders = new List <PingRequestFolder>(folderEls.Count); foreach (var folderEl in folderEls) { var newFolder = new PingRequestFolder() { Id = folderEl.GetElementValueAsString(PingStrings.Id) }; var folderClass = folderEl.GetElementValueAsString(PingStrings.Class); newFolder.Class = (eFolderClass)Enum.Parse(typeof(eFolderClass), folderClass); this.Folders.Add(newFolder); } }
public void IncompleteUsersDataProcessingFromMatchData() { var responseRaw = TestingResourcesHelper.GetApiResoponses("MatchDetailsValid.json"); var processingService = ServiceResolver.GetService <IUserDataProcessingService>(); var stringResources = JsonConvert.DeserializeObject <AoeNetAPIStringResources>(TestingResourcesHelper.GetApiResoponses("ApiStringResources.json")); Match match = processingService.ProcessMatch(responseRaw, stringResources); Assert.AreEqual(match.Users.Count, 2, "Users in match count is incorrect"); //make sure other fields was processed as expected //test both players profile IDs Assert.IsNotNull(match.Users.First().UserGameProfileId, "Player[0] profile id wasn't processed"); Assert.IsNotNull(match.Users.Last().UserGameProfileId, "Player[1] profile id wasn't processed"); //test both players names Assert.IsNotNull(match.Users.First().Name, "Player[0] name wasn't processed"); Assert.IsNotNull(match.Users.Last().Name, "Player[1] name wasn't processed"); //validate color property (have to be set) Assert.IsNotNull(match.Users.First().Color, "Player[0] color is wasn't processed"); Assert.IsNotNull(match.Users.Last().Color, "Player[1] color is wasn't processed"); //validate user match types and match type Assert.AreEqual(match.MatchType, MatchType.RandomMap); Assert.AreEqual(match.Users.First().MatchType, MatchType.RandomMap); Assert.AreEqual(match.Users.Last().MatchType, MatchType.RandomMap); }
public async Task CacheLoad() { TestingResourcesHelper.PreapareTestingDirectory(ServiceResolver.GetService <IAppConfigurationService>()); TestingResourcesHelper.InjectCachedQueriesData(ServiceResolver.GetService <IAppConfigurationService>()); var storageService = ServiceResolver.GetService <IStorageService>(); storageService.Load(); var queryCacheService = ServiceResolver.GetService <IQueryCacheService>() as AOEMatchDataProvider.Services.Default.QueryCacheService; //cast to specified service to get access for internal fields/methods queryCacheService.Load(); Assert.IsTrue(queryCacheService.Queries.CachedQueries.ContainsKey(productRequest), "Cache should exists"); //CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(5000); //var requestResponseWrapper = await queryCacheService.GetOrUpdate(productRequest, cancellationTokenSource.Token, DateTime.UtcNow.AddDays(1)); //if (!requestResponseWrapper.IsSuccess) // Assert.Fail("Request failed"); //Assert.IsTrue(queryCacheService.Queries.CachedQueries.ContainsKey(productRequest), "Cache exists"); }
/// <summary> /// Performs a Database Reset /// /// Deletes the Accounts Table and sets up a new SYSOP and GUEST user /// </summary> private void DatabaseReset() { _logger.Info("Resetting Database..."); if (string.IsNullOrEmpty(_newSysopPassword)) { var bPasswordMatch = false; while (!bPasswordMatch) { Console.Write("Enter New Sysop Password: "******"Re-Enter New Sysop Password: "******"Password mismatch, please try again."); } } } var acct = _serviceResolver.GetService <IAccountRepository>(); acct.Reset(_newSysopPassword); var keys = _serviceResolver.GetService <IAccountKeyRepository>(); keys.Reset(); //Insert Into BBS Account Btrieve File var _accountBtrieve = _serviceResolver.GetService <IGlobalCache>().Get <BtrieveFileProcessor>("ACCBB-PROCESSOR"); _accountBtrieve.DeleteAll(); _accountBtrieve.Insert(new UserAccount { userid = Encoding.ASCII.GetBytes("sysop"), psword = Encoding.ASCII.GetBytes("<<HASHED>>") }.Data); _accountBtrieve.Insert(new UserAccount { userid = Encoding.ASCII.GetBytes("guest"), psword = Encoding.ASCII.GetBytes("<<HASHED>>") }.Data); _logger.Info("Database Reset!"); }
public void Initialize(UserDevice device, string xmlRequest) { StateManager = new StateManager(ServiceResolver.GetService <IStateMachine>()); StateManager.UserDevice = device; StateManager.Credential = device.Credential; Initialize(xmlRequest); }
private void DataGrid_AddingNewItem(object sender, AddingNewItemEventArgs e) { e.NewItem = new CategoryDescriptionPattern() { Percentage = 100, UserId = ServiceResolver.GetService <IUserProvider>().GetUserId() }; }
protected MajorbbsTestBase() { mbbsEmuMemoryCore = new MemoryCore(); mbbsEmuCpuRegisters = new CpuRegisters(); mbbsEmuCpuCore = new CpuCore(); mbbsModule = new MbbsModule(FileUtility.CreateForTest(), _serviceResolver.GetService <ILogger>(), null, string.Empty, mbbsEmuMemoryCore); majorbbs = new HostProcess.ExportedModules.Majorbbs( _serviceResolver.GetService <ILogger>(), _serviceResolver.GetService <IConfiguration>(), _serviceResolver.GetService <IFileUtility>(), _serviceResolver.GetService <IGlobalCache>(), mbbsModule, new PointerDictionary <Session.SessionBase>()); mbbsEmuCpuCore.Reset(mbbsEmuMemoryCore, mbbsEmuCpuRegisters, MajorbbsFunctionDelegate); }
public void OnException(ExceptionContext context) { var errorBr = new Br <string>(context.Exception.Message, -1, context.Exception.Message, stackTrance: context.Exception.StackTrace); context.Result = new JsonResult(errorBr); context.ExceptionHandled = true; IALogger logger = ServiceResolver.GetService <IALogger>(context); logger.Exception(context.Exception); }
protected override void InitializePropertyTrackers() { base.InitializePropertyTrackers(); this.AddPropertyTrackerAction(nameof(SelectedItem), (sender, args) => { if (SelectedItem != null) { ServiceResolver.GetService <INavigationService>().Navigate(new Uri(GlobalConstant.WINDOWS_QUESTION, UriKind.Relative)); } }); }
protected override void Initialize(string xmlRequest) { FolderService = ServiceResolver.GetService <IFolderService>(); if (string.IsNullOrWhiteSpace(xmlRequest)) { throw new InvalidRequestException("FolderCreate Request Content is Empty."); } var root = XDocument.Parse(xmlRequest).Root; this.SyncKey = root.GetElementValueAsString(FolderHierarchyStrings.SyncKey); }
private void AddCategoryToTransaction(object obj) { Transaction transaction = EditingItem.Result as Transaction; CategoryTransactionLink link = new CategoryTransactionLink(); link.TransactionID = transaction.ID; link.Transaction = transaction; link.CategoryID = SelectedCategory.ID; link.Category = SelectedCategory; link.UserId = ServiceResolver.GetService <IUserProvider>().GetUserId(); transaction.CategoryLinks.Add(link); LinkWrappers.Add(new CategoryTransactionLinkWrapper(transaction, link: link, percentage: 0, maxPercentage: 100 - EditingItem.Result.CategoryLinks.Where(c => c != link).Sum(c => c.Percentage), wrappers: LinkWrappers, links: transaction.CategoryLinks)); }
private protected static readonly byte[] NEW_LINE = { (byte)'\r', (byte)'\n' }; //Just easier to read private protected ExportedModuleBase(MbbsModule module, PointerDictionary <SessionBase> channelDictionary) { _logger = ServiceResolver.GetService <ILogger>(); _configuration = ServiceResolver.GetService <IConfiguration>(); _fileFinder = ServiceResolver.GetService <IFileUtility>(); _globalCache = ServiceResolver.GetService <IGlobalCache>(); Module = module; ChannelDictionary = channelDictionary; FilePointerDictionary = new PointerDictionary <FileStream>(1, int.MaxValue); McvPointerDictionary = new PointerDictionary <McvFile>(); BtrievePointerDictionaryNew = new Dictionary <IntPtr16, BtrieveFileProcessor>(); }