示例#1
0
        /// <summary>
        /// Construct an <see cref="InstanceManager"/>
        /// </summary>
        /// <param name="instanceFactory">The value of <see cref="instanceFactory"/></param>
        /// <param name="ioManager">The value of <paramref name="ioManager"/></param>
        /// <param name="databaseContextFactory">The value of <paramref name="databaseContextFactory"/></param>
        /// <param name="assemblyInformationProvider">The value of <see cref="assemblyInformationProvider"/></param>
        /// <param name="jobManager">The value of <see cref="jobManager"/></param>
        /// <param name="serverControl">The value of <see cref="serverControl"/></param>
        /// <param name="systemIdentityFactory">The value of <see cref="systemIdentityFactory"/>.</param>
        /// <param name="asyncDelayer">The value of <see cref="asyncDelayer"/>.</param>
        /// <param name="generalConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the value of <see cref="generalConfiguration"/>.</param>
        /// <param name="logger">The value of <see cref="logger"/></param>
        public InstanceManager(
            IInstanceFactory instanceFactory,
            IIOManager ioManager,
            IDatabaseContextFactory databaseContextFactory,
            IAssemblyInformationProvider assemblyInformationProvider,
            IJobManager jobManager,
            IServerControl serverControl,
            ISystemIdentityFactory systemIdentityFactory,
            IAsyncDelayer asyncDelayer,
            IOptions <GeneralConfiguration> generalConfigurationOptions,
            ILogger <InstanceManager> logger)
        {
            this.instanceFactory             = instanceFactory ?? throw new ArgumentNullException(nameof(instanceFactory));
            this.ioManager                   = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
            this.databaseContextFactory      = databaseContextFactory ?? throw new ArgumentNullException(nameof(databaseContextFactory));
            this.assemblyInformationProvider = assemblyInformationProvider ?? throw new ArgumentNullException(nameof(assemblyInformationProvider));
            this.jobManager                  = jobManager ?? throw new ArgumentNullException(nameof(jobManager));
            this.serverControl               = serverControl ?? throw new ArgumentNullException(nameof(serverControl));
            this.systemIdentityFactory       = systemIdentityFactory ?? throw new ArgumentNullException(nameof(systemIdentityFactory));
            this.asyncDelayer                = asyncDelayer ?? throw new ArgumentNullException(nameof(asyncDelayer));
            generalConfiguration             = generalConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(generalConfigurationOptions));
            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));

            serverControl.RegisterForRestart(this);

            instances      = new Dictionary <long, IInstance>();
            bridgeHandlers = new Dictionary <string, IBridgeHandler>();
            readyTcs       = new TaskCompletionSource <object>();
        }
示例#2
0
 public LogFile()
 {
     this.iOManager   = new IoManager(currentDirectory, currentFile);
     this.currentPath = this.iOManager.GetCurrentPath();
     this.iOManager.EnsurePathAndFileExistance();
     this.Path = currentPath + currentDirectory + currentFile;
 }
示例#3
0
        public MainWindowViewModel(IPDFManager pdfManager,
                                   IIOManager ioManager,
                                   IFileNameManager fileNameManager,
                                   IDataManager dataManager,
                                   IDataConnector <IVOAType> dataConnector,
                                   ICSVManager csvManager
                                   )
        {
            mainWindow           = dataManager.MainWindow;
            this.pdfManager      = pdfManager;
            this.ioManager       = ioManager;
            this.fileNameManager = fileNameManager;
            this.dataManager     = dataManager;
            this.dataConnector   = dataConnector;
            this.csvManager      = csvManager;

#if DEBUG
            TemplatePath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;

            TemplatePath = Path.GetFullPath(Path.Combine(TemplatePath, @"..\"));

            TemplatePath += @"masts_dvr_tool.Tests\StubForms\mockForm.pdf";
#endif

            Prefix            = "VOA";
            EncryptionLabel   = "Encryption?";
            EncryptionEnabled = true;
        }
示例#4
0
 public LogFile()
 {
     this.IOManager   = new IOManager(CurrentDirectory, CurrentFile);
     this.currentPath = this.IOManager.GetCurrentPath();
     this.IOManager.EnsureDirectoryAndFileExists();
     this.Path = System.IO.Path.Combine(this.currentPath + CurrentDirectory + CurrentFile);
 }
示例#5
0
 public LogFile()
 {
     this.IOManager   = new IOManager(currentDirectory, currentFile);
     this.currentPath = this.IOManager.GetCurrentPath();
     this.IOManager.EnsureDirectoryAndFileExists();
     this.Path = currentPath + currentDirectory + currentFile;
 }
        /// <summary>
        /// Construct an <see cref="InstanceManager"/>
        /// </summary>
        /// <param name="instanceFactory">The value of <see cref="instanceFactory"/></param>
        /// <param name="ioManager">The value of <paramref name="ioManager"/></param>
        /// <param name="databaseContextFactory">The value of <paramref name="databaseContextFactory"/></param>
        /// <param name="application">The value of <see cref="application"/></param>
        /// <param name="jobManager">The value of <see cref="jobManager"/></param>
        /// <param name="serverControl">The <see cref="IServerControl"/> for the <see cref="InstanceManager"/></param>
        /// <param name="logger">The value of <see cref="logger"/></param>
        public InstanceManager(IInstanceFactory instanceFactory, IIOManager ioManager, IDatabaseContextFactory databaseContextFactory, IApplication application, IJobManager jobManager, IServerControl serverControl, ILogger <InstanceManager> logger)
        {
            this.instanceFactory        = instanceFactory ?? throw new ArgumentNullException(nameof(instanceFactory));
            this.ioManager              = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
            this.databaseContextFactory = databaseContextFactory ?? throw new ArgumentNullException(nameof(databaseContextFactory));
            this.application            = application ?? throw new ArgumentNullException(nameof(application));
            this.jobManager             = jobManager ?? throw new ArgumentNullException(nameof(jobManager));

            if (serverControl == null)
            {
                throw new ArgumentNullException(nameof(serverControl));
            }

            shutdownCancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = shutdownCancellationTokenSource.Token;

            serverControl.RegisterForRestart(() =>
            {
                lock (this)
                    shutdownTasks.AddRange(instances.Select(x => x.Value.Chat.SendBroadcast("TGS: Restart requested...", cancellationToken)));
            });

            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));

            instances     = new Dictionary <long, IInstance>();
            shutdownTasks = new List <Task>();
        }
示例#7
0
 /// <summary>
 /// Construct a <see cref="InstanceController"/>
 /// </summary>
 /// <param name="databaseContext">The <see cref="IDatabaseContext"/> for the <see cref="ApiController"/></param>
 /// <param name="authenticationContextFactory">The <see cref="IAuthenticationContextFactory"/> for the <see cref="ApiController"/></param>
 /// <param name="jobManager">The value of <see cref="jobManager"/></param>
 /// <param name="instanceManager">The value of <see cref="instanceManager"/></param>
 /// <param name="ioManager">The value of <see cref="ioManager"/></param>
 /// <param name="application">The value of <see cref="application"/></param>
 /// <param name="logger">The <see cref="ILogger"/> for the <see cref="ApiController"/></param>
 public InstanceController(IDatabaseContext databaseContext, IAuthenticationContextFactory authenticationContextFactory, IJobManager jobManager, IInstanceManager instanceManager, IIOManager ioManager, IApplication application, ILogger <InstanceController> logger) : base(databaseContext, authenticationContextFactory, logger, false)
 {
     this.jobManager      = jobManager ?? throw new ArgumentNullException(nameof(jobManager));
     this.instanceManager = instanceManager ?? throw new ArgumentNullException(nameof(instanceManager));
     this.ioManager       = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
     this.application     = application ?? throw new ArgumentNullException(nameof(application));
 }
示例#8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Repository"/> class.
        /// </summary>
        /// <param name="libGitRepo">The value of <see cref="libGitRepo"/>.</param>
        /// <param name="commands">The value of <see cref="commands"/>.</param>
        /// <param name="ioMananger">The value of <see cref="ioMananger"/>.</param>
        /// <param name="eventConsumer">The value of <see cref="eventConsumer"/>.</param>
        /// <param name="credentialsProvider">The value of <see cref="credentialsProvider"/>.</param>
        /// <param name="gitRemoteFeaturesFactory">The <see cref="IGitRemoteFeaturesFactory"/> to provide the value of <see cref="gitRemoteFeatures"/>.</param>
        /// <param name="logger">The value of <see cref="logger"/>.</param>
        /// <param name="onDispose">The value if <see cref="onDispose"/>.</param>
        public Repository(
            LibGit2Sharp.IRepository libGitRepo,
            ILibGit2Commands commands,
            IIOManager ioMananger,
            IEventConsumer eventConsumer,
            ICredentialsProvider credentialsProvider,
            IGitRemoteFeaturesFactory gitRemoteFeaturesFactory,
            ILogger <Repository> logger,
            Action onDispose)
        {
            this.libGitRepo          = libGitRepo ?? throw new ArgumentNullException(nameof(libGitRepo));
            this.commands            = commands ?? throw new ArgumentNullException(nameof(commands));
            this.ioMananger          = ioMananger ?? throw new ArgumentNullException(nameof(ioMananger));
            this.eventConsumer       = eventConsumer ?? throw new ArgumentNullException(nameof(eventConsumer));
            this.credentialsProvider = credentialsProvider ?? throw new ArgumentNullException(nameof(credentialsProvider));
            if (gitRemoteFeaturesFactory == null)
            {
                throw new ArgumentNullException(nameof(gitRemoteFeaturesFactory));
            }

            this.logger    = logger ?? throw new ArgumentNullException(nameof(logger));
            this.onDispose = onDispose ?? throw new ArgumentNullException(nameof(onDispose));

            gitRemoteFeatures = gitRemoteFeaturesFactory.CreateGitRemoteFeatures(this);
        }
示例#9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InstanceManager"/> class.
        /// </summary>
        /// <param name="instanceFactory">The value of <see cref="instanceFactory"/>.</param>
        /// <param name="ioManager">The value of <paramref name="ioManager"/>.</param>
        /// <param name="databaseContextFactory">The value of <paramref name="databaseContextFactory"/>.</param>
        /// <param name="assemblyInformationProvider">The value of <see cref="assemblyInformationProvider"/>.</param>
        /// <param name="jobManager">The value of <see cref="jobManager"/>.</param>
        /// <param name="serverControl">The value of <see cref="serverControl"/>.</param>
        /// <param name="systemIdentityFactory">The value of <see cref="systemIdentityFactory"/>.</param>
        /// <param name="asyncDelayer">The value of <see cref="asyncDelayer"/>.</param>
        /// <param name="serverPortProvider">The value of <see cref="serverPortProvider"/>.</param>
        /// <param name="swarmService">The value of <see cref="swarmService"/>.</param>
        /// <param name="generalConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the value of <see cref="generalConfiguration"/>.</param>
        /// <param name="swarmConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the value of <see cref="swarmConfiguration"/>.</param>
        /// <param name="logger">The value of <see cref="logger"/>.</param>
        public InstanceManager(
            IInstanceFactory instanceFactory,
            IIOManager ioManager,
            IDatabaseContextFactory databaseContextFactory,
            IAssemblyInformationProvider assemblyInformationProvider,
            IJobManager jobManager,
            IServerControl serverControl,
            ISystemIdentityFactory systemIdentityFactory,
            IAsyncDelayer asyncDelayer,
            IServerPortProvider serverPortProvider,
            ISwarmService swarmService,
            IOptions <GeneralConfiguration> generalConfigurationOptions,
            IOptions <SwarmConfiguration> swarmConfigurationOptions,
            ILogger <InstanceManager> logger)
        {
            this.instanceFactory             = instanceFactory ?? throw new ArgumentNullException(nameof(instanceFactory));
            this.ioManager                   = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
            this.databaseContextFactory      = databaseContextFactory ?? throw new ArgumentNullException(nameof(databaseContextFactory));
            this.assemblyInformationProvider = assemblyInformationProvider ?? throw new ArgumentNullException(nameof(assemblyInformationProvider));
            this.jobManager                  = jobManager ?? throw new ArgumentNullException(nameof(jobManager));
            this.serverControl               = serverControl ?? throw new ArgumentNullException(nameof(serverControl));
            this.systemIdentityFactory       = systemIdentityFactory ?? throw new ArgumentNullException(nameof(systemIdentityFactory));
            this.asyncDelayer                = asyncDelayer ?? throw new ArgumentNullException(nameof(asyncDelayer));
            this.serverPortProvider          = serverPortProvider ?? throw new ArgumentNullException(nameof(serverPortProvider));
            this.swarmService                = swarmService ?? throw new ArgumentNullException(nameof(swarmService));
            generalConfiguration             = generalConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(generalConfigurationOptions));
            swarmConfiguration               = swarmConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(swarmConfigurationOptions));
            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));

            instances      = new Dictionary <long, InstanceContainer>();
            bridgeHandlers = new Dictionary <string, IBridgeHandler>();
            readyTcs       = new TaskCompletionSource <object>();
            instanceStateChangeSemaphore = new SemaphoreSlim(1);
        }
示例#10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AdministrationController"/> class.
 /// </summary>
 /// <param name="databaseContext">The <see cref="IDatabaseContext"/> for the <see cref="ApiController"/>.</param>
 /// <param name="authenticationContextFactory">The <see cref="IAuthenticationContextFactory"/> for the <see cref="ApiController"/>.</param>
 /// <param name="gitHubClientFactory">The value of <see cref="gitHubClientFactory"/>.</param>
 /// <param name="serverControl">The value of <see cref="serverControl"/>.</param>
 /// <param name="serverUpdater">The value of <see cref="serverUpdater"/>.</param>
 /// <param name="assemblyInformationProvider">The value of <see cref="assemblyInformationProvider"/>.</param>
 /// <param name="ioManager">The value of <see cref="ioManager"/>.</param>
 /// <param name="platformIdentifier">The value of <see cref="platformIdentifier"/>.</param>
 /// <param name="fileTransferService">The value of <see cref="fileTransferService"/>.</param>
 /// <param name="logger">The <see cref="ILogger"/> for the <see cref="ApiController"/>.</param>
 /// <param name="updatesConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing value of <see cref="updatesConfiguration"/>.</param>
 /// <param name="fileLoggingConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing value of <see cref="fileLoggingConfiguration"/>.</param>
 public AdministrationController(
     IDatabaseContext databaseContext,
     IAuthenticationContextFactory authenticationContextFactory,
     IGitHubClientFactory gitHubClientFactory,
     IServerControl serverControl,
     IServerUpdateInitiator serverUpdater,
     IAssemblyInformationProvider assemblyInformationProvider,
     IIOManager ioManager,
     IPlatformIdentifier platformIdentifier,
     IFileTransferTicketProvider fileTransferService,
     ILogger <AdministrationController> logger,
     IOptions <UpdatesConfiguration> updatesConfigurationOptions,
     IOptions <FileLoggingConfiguration> fileLoggingConfigurationOptions)
     : base(
         databaseContext,
         authenticationContextFactory,
         logger,
         true)
 {
     this.gitHubClientFactory         = gitHubClientFactory ?? throw new ArgumentNullException(nameof(gitHubClientFactory));
     this.serverControl               = serverControl ?? throw new ArgumentNullException(nameof(serverControl));
     this.serverUpdater               = serverUpdater ?? throw new ArgumentNullException(nameof(serverUpdater));
     this.assemblyInformationProvider = assemblyInformationProvider ?? throw new ArgumentNullException(nameof(assemblyInformationProvider));
     this.ioManager           = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
     this.platformIdentifier  = platformIdentifier ?? throw new ArgumentNullException(nameof(platformIdentifier));
     this.fileTransferService = fileTransferService ?? throw new ArgumentNullException(nameof(fileTransferService));
     updatesConfiguration     = updatesConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(updatesConfigurationOptions));
     fileLoggingConfiguration = fileLoggingConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(fileLoggingConfigurationOptions));
 }
示例#11
0
 public TicTacToeGame(IIOManager iOManager, Player playerX, Player playerO)
 {
     IOManager = iOManager;
     PlayerX   = playerX;
     PlayerO   = playerO;
     Board     = new Board();
 }
 /// <inheritdoc />
 protected override IWatchdog CreateNonExperimentalWatchdog(
     IChat chat,
     IDmbFactory dmbFactory,
     IReattachInfoHandler reattachInfoHandler,
     IEventConsumer eventConsumer,
     ISessionControllerFactory sessionControllerFactory,
     IIOManager ioManager,
     Api.Models.Instance instance,
     DreamDaemonSettings settings)
 => new WindowsWatchdog(
     chat,
     sessionControllerFactory,
     dmbFactory,
     reattachInfoHandler,
     DatabaseContextFactory,
     ByondTopicSender,
     eventConsumer,
     JobManager,
     ServerControl,
     AsyncDelayer,
     ioManager,
     symlinkFactory,
     LoggerFactory.CreateLogger <WindowsWatchdog>(),
     settings,
     instance,
     settings.AutoStart.Value);
        /// <summary>
        /// Gets the evaluated log <see cref="Directory"/>.
        /// </summary>
        /// <param name="ioManager">The <see cref="IIOManager"/> to use.</param>
        /// <param name="assemblyInformationProvider">The <see cref="IAssemblyInformationProvider"/> to use.</param>
        /// <param name="platformIdentifier">The <see cref="IPlatformIdentifier"/> to use</param>
        /// <returns>The evaluated log <see cref="Directory"/>.</returns>
        public string GetFullLogDirectory(
            IIOManager ioManager,
            IAssemblyInformationProvider assemblyInformationProvider,
            IPlatformIdentifier platformIdentifier)
        {
            if (ioManager == null)
            {
                throw new ArgumentNullException(nameof(ioManager));
            }
            if (assemblyInformationProvider == null)
            {
                throw new ArgumentNullException(nameof(assemblyInformationProvider));
            }
            if (platformIdentifier == null)
            {
                throw new ArgumentNullException(nameof(platformIdentifier));
            }

            var directoryToUse = platformIdentifier.IsWindows
                                ? Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) // C:/ProgramData
                                : "/var/log";                                                                // :pain:

            return(!String.IsNullOrEmpty(Directory)
                                ? Directory
                                : ioManager.ConcatPath(
                       directoryToUse,
                       assemblyInformationProvider.VersionPrefix));
        }
示例#14
0
 /// <summary>
 /// Construct a <see cref="InstanceController"/>
 /// </summary>
 /// <param name="databaseContext">The <see cref="IDatabaseContext"/> for the <see cref="ApiController"/></param>
 /// <param name="authenticationContextFactory">The <see cref="IAuthenticationContextFactory"/> for the <see cref="ApiController"/></param>
 /// <param name="jobManager">The value of <see cref="jobManager"/></param>
 /// <param name="instanceManager">The value of <see cref="instanceManager"/></param>
 /// <param name="ioManager">The value of <see cref="ioManager"/></param>
 /// <param name="platformIdentifier">The value of <see cref="platformIdentifier"/></param>
 /// <param name="portAllocator">The value of <see cref="IPortAllocator"/>.</param>
 /// <param name="generalConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the value of <see cref="generalConfiguration"/>.</param>
 /// <param name="swarmConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the value of <see cref="swarmConfiguration"/>.</param>
 /// <param name="logger">The <see cref="ILogger"/> for the <see cref="ApiController"/>.</param>
 public InstanceController(
     IDatabaseContext databaseContext,
     IAuthenticationContextFactory authenticationContextFactory,
     IJobManager jobManager,
     IInstanceManager instanceManager,
     IIOManager ioManager,
     IPortAllocator portAllocator,
     IPlatformIdentifier platformIdentifier,
     IOptions <GeneralConfiguration> generalConfigurationOptions,
     IOptions <SwarmConfiguration> swarmConfigurationOptions,
     ILogger <InstanceController> logger)
     : base(
         databaseContext,
         authenticationContextFactory,
         logger,
         true)
 {
     this.jobManager         = jobManager ?? throw new ArgumentNullException(nameof(jobManager));
     this.instanceManager    = instanceManager ?? throw new ArgumentNullException(nameof(instanceManager));
     this.ioManager          = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
     this.platformIdentifier = platformIdentifier ?? throw new ArgumentNullException(nameof(platformIdentifier));
     this.portAllocator      = portAllocator ?? throw new ArgumentNullException(nameof(portAllocator));
     generalConfiguration    = generalConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(generalConfigurationOptions));
     swarmConfiguration      = swarmConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(swarmConfigurationOptions));
 }
示例#15
0
        /// <summary>
        /// Construct a <see cref="Repository"/>
        /// </summary>
        /// <param name="libGitRepo">The value of <see cref="libGitRepo"/></param>
        /// <param name="commands">The value of <see cref="commands"/>.</param>
        /// <param name="ioMananger">The value of <see cref="ioMananger"/></param>
        /// <param name="eventConsumer">The value of <see cref="eventConsumer"/></param>
        /// <param name="credentialsProvider">The value of <see cref="credentialsProvider"/></param>
        /// <param name="logger">The value of <see cref="logger"/></param>
        /// <param name="onDispose">The value if <see cref="onDispose"/></param>
        public Repository(
            LibGit2Sharp.IRepository libGitRepo,
            ILibGit2Commands commands,
            IIOManager ioMananger,
            IEventConsumer eventConsumer,
            ICredentialsProvider credentialsProvider,
            ILogger <Repository> logger,
            Action onDispose)
        {
            this.libGitRepo          = libGitRepo ?? throw new ArgumentNullException(nameof(libGitRepo));
            this.commands            = commands ?? throw new ArgumentNullException(nameof(commands));
            this.ioMananger          = ioMananger ?? throw new ArgumentNullException(nameof(ioMananger));
            this.eventConsumer       = eventConsumer ?? throw new ArgumentNullException(nameof(eventConsumer));
            this.credentialsProvider = credentialsProvider ?? throw new ArgumentNullException(nameof(credentialsProvider));
            this.logger    = logger ?? throw new ArgumentNullException(nameof(logger));
            this.onDispose = onDispose ?? throw new ArgumentNullException(nameof(onDispose));

            IsGitHubRepository = Origin.Contains(GitHubUrl, StringComparison.InvariantCultureIgnoreCase);

            if (IsGitHubRepository)
            {
                GetRepositoryOwnerName(Origin, out var owner, out var name);
                GitHubOwner    = owner;
                GitHubRepoName = name;
            }
        }
示例#16
0
 /// <summary>
 /// Construct a <see cref="SessionControllerFactory"/>
 /// </summary>
 /// <param name="processExecutor">The value of <see cref="processExecutor"/></param>
 /// <param name="byond">The value of <see cref="byond"/></param>
 /// <param name="byondTopicSender">The value of <see cref="byondTopicSender"/></param>
 /// <param name="cryptographySuite">The value of <see cref="cryptographySuite"/></param>
 /// <param name="application">The value of <see cref="application"/></param>
 /// <param name="instance">The value of <see cref="instance"/></param>
 /// <param name="ioManager">The value of <see cref="ioManager"/></param>
 /// <param name="chat">The value of <see cref="chat"/></param>
 /// <param name="networkPromptReaper">The value of <see cref="networkPromptReaper"/></param>
 /// <param name="platformIdentifier">The value of <see cref="platformIdentifier"/></param>
 /// <param name="loggerFactory">The value of <see cref="loggerFactory"/></param>
 public SessionControllerFactory(
     IProcessExecutor processExecutor,
     IByondManager byond,
     IByondTopicSender byondTopicSender,
     ICryptographySuite cryptographySuite,
     IApplication application,
     IIOManager ioManager,
     IChat chat,
     INetworkPromptReaper networkPromptReaper,
     IPlatformIdentifier platformIdentifier,
     ILoggerFactory loggerFactory,
     Api.Models.Instance instance)
 {
     this.processExecutor   = processExecutor ?? throw new ArgumentNullException(nameof(processExecutor));
     this.byond             = byond ?? throw new ArgumentNullException(nameof(byond));
     this.byondTopicSender  = byondTopicSender ?? throw new ArgumentNullException(nameof(byondTopicSender));
     this.cryptographySuite = cryptographySuite ?? throw new ArgumentNullException(nameof(cryptographySuite));
     this.application       = application ?? throw new ArgumentNullException(nameof(application));
     this.instance          = instance ?? throw new ArgumentNullException(nameof(instance));
     this.ioManager         = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
     this.chat = chat ?? throw new ArgumentNullException(nameof(chat));
     this.networkPromptReaper = networkPromptReaper ?? throw new ArgumentNullException(nameof(networkPromptReaper));
     this.platformIdentifier  = platformIdentifier ?? throw new ArgumentNullException(nameof(platformIdentifier));
     this.loggerFactory       = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
 }
示例#17
0
 /// <summary>
 /// Construct a <see cref="Repository"/>
 /// </summary>
 /// <param name="gitHubConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the <see cref="GitHubConfiguration"/> to use for determining the <see cref="repositoryObject"/>'s path</param>
 /// <param name="_logger">The <see cref="ILogger"/> to use for setting up the <see cref="Repository"/></param>
 /// <param name="_ioManager">The value of <see cref="ioManager"/></param>
 public Repository(IOptions <GitHubConfiguration> gitHubConfigurationOptions, ILogger <Repository> _logger, IIOManager _ioManager)
 {
     logger = _logger ?? throw new ArgumentNullException(nameof(_logger));
     gitHubConfiguration = gitHubConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(gitHubConfigurationOptions));
     ioManager           = new ResolvingIOManager(_ioManager ?? throw new ArgumentNullException(nameof(_ioManager)), _ioManager.ConcatPath(Application.DataDirectory, RepositoriesDirectory));
     semaphore           = new SemaphoreSlim(1);
 }
示例#18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DmbProvider"/> class.
 /// </summary>
 /// <param name="compileJob">The value of <see cref="CompileJob"/>.</param>
 /// <param name="ioManager">The value of <see cref="ioManager"/>.</param>
 /// <param name="onDispose">The value of <see cref="onDispose"/>.</param>
 /// <param name="directoryAppend">The optional value of <see cref="directoryAppend"/>.</param>
 public DmbProvider(CompileJob compileJob, IIOManager ioManager, Action onDispose, string directoryAppend = null)
 {
     CompileJob           = compileJob ?? throw new ArgumentNullException(nameof(compileJob));
     this.ioManager       = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
     this.onDispose       = onDispose ?? throw new ArgumentNullException(nameof(onDispose));
     this.directoryAppend = directoryAppend ?? String.Empty;
 }
 /// <summary>
 /// Construct an <see cref="AdministrationController"/>
 /// </summary>
 /// <param name="databaseContext">The <see cref="IDatabaseContext"/> for the <see cref="ApiController"/></param>
 /// <param name="authenticationContextFactory">The <see cref="IAuthenticationContextFactory"/> for the <see cref="ApiController"/></param>
 /// <param name="gitHubClientFactory">The value of <see cref="gitHubClientFactory"/></param>
 /// <param name="serverUpdater">The value of <see cref="serverUpdater"/></param>
 /// <param name="application">The value of <see cref="application"/></param>
 /// <param name="ioManager">The value of <see cref="ioManager"/></param>
 /// <param name="platformIdentifier">The value of <see cref="platformIdentifier"/></param>
 /// <param name="logger">The <see cref="ILogger"/> for the <see cref="ApiController"/></param>
 /// <param name="updatesConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing value of <see cref="updatesConfiguration"/></param>
 /// <param name="generalConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing value of <see cref="generalConfiguration"/></param>
 public AdministrationController(
     IDatabaseContext databaseContext,
     IAuthenticationContextFactory authenticationContextFactory,
     IGitHubClientFactory gitHubClientFactory,
     IServerControl serverUpdater,
     IApplication application,
     IIOManager ioManager,
     IPlatformIdentifier platformIdentifier,
     ILogger <AdministrationController> logger,
     IOptions <UpdatesConfiguration> updatesConfigurationOptions,
     IOptions <GeneralConfiguration> generalConfigurationOptions)
     : base(
         databaseContext,
         authenticationContextFactory,
         logger,
         false,
         true)
 {
     this.gitHubClientFactory = gitHubClientFactory ?? throw new ArgumentNullException(nameof(gitHubClientFactory));
     this.serverUpdater       = serverUpdater ?? throw new ArgumentNullException(nameof(serverUpdater));
     this.application         = application ?? throw new ArgumentNullException(nameof(application));
     this.ioManager           = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
     this.platformIdentifier  = platformIdentifier ?? throw new ArgumentNullException(nameof(platformIdentifier));
     updatesConfiguration     = updatesConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(updatesConfigurationOptions));
     generalConfiguration     = generalConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(generalConfigurationOptions));
 }
 /// <summary>
 /// Construct a <see cref="RepositoryManager"/>
 /// </summary>
 /// <param name="repositorySettings">The value of <see cref="repositorySettings"/></param>
 /// <param name="ioManager">The value of <see cref="ioManager"/></param>
 /// <param name="eventConsumer">The value of <see cref="eventConsumer"/></param>
 public RepositoryManager(RepositorySettings repositorySettings, IIOManager ioManager, IEventConsumer eventConsumer)
 {
     this.repositorySettings = repositorySettings ?? throw new ArgumentNullException(nameof(repositorySettings));
     this.ioManager          = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
     this.eventConsumer      = eventConsumer ?? throw new ArgumentNullException(nameof(eventConsumer));
     semaphore = new SemaphoreSlim(1);
 }
示例#21
0
 /// <inheritdoc />
 public async Task <bool> ApplyUpdate(byte[] updateZipData, IIOManager ioManager, CancellationToken cancellationToken)
 {
     if (updatePath == null)
     {
         return(false);
     }
     using (await SemaphoreSlimContext.Lock(semaphore, cancellationToken).ConfigureAwait(false))
     {
         if (updated)
         {
             throw new InvalidOperationException("ApplyUpdate has already been called!");
         }
         updated = true;
         try
         {
             await ioManager.ZipToDirectory(updatePath, updateZipData, cancellationToken).ConfigureAwait(false);
         }
         catch
         {
             try
             {
                 //important to not leave this directory around if possible
                 await ioManager.DeleteDirectory(updatePath, default).ConfigureAwait(false);
             }
             catch { }
             updated = false;
             throw;
         }
         Restart();
         return(true);
     }
 }
示例#22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DreamMaker"/> class.
        /// </summary>
        /// <param name="byond">The value of <see cref="byond"/>.</param>
        /// <param name="ioManager">The value of <see cref="ioManager"/>.</param>
        /// <param name="configuration">The value of <see cref="configuration"/>.</param>
        /// <param name="sessionControllerFactory">The value of <see cref="sessionControllerFactory"/>.</param>
        /// <param name="eventConsumer">The value of <see cref="eventConsumer"/>.</param>
        /// <param name="chatManager">The value of <see cref="chatManager"/>.</param>
        /// <param name="processExecutor">The value of <see cref="processExecutor"/>.</param>
        /// <param name="compileJobConsumer">The value of <see cref="compileJobConsumer"/>.</param>
        /// <param name="repositoryManager">The value of <see cref="repositoryManager"/>.</param>
        /// <param name="remoteDeploymentManagerFactory">The value of <see cref="remoteDeploymentManagerFactory"/>.</param>
        /// <param name="logger">The value of <see cref="logger"/>.</param>
        /// <param name="metadata">The value of <see cref="metadata"/>.</param>
        public DreamMaker(
            IByondManager byond,
            IIOManager ioManager,
            StaticFiles.IConfiguration configuration,
            ISessionControllerFactory sessionControllerFactory,
            IEventConsumer eventConsumer,
            IChatManager chatManager,
            IProcessExecutor processExecutor,
            ICompileJobSink compileJobConsumer,
            IRepositoryManager repositoryManager,
            IRemoteDeploymentManagerFactory remoteDeploymentManagerFactory,
            ILogger <DreamMaker> logger,
            Api.Models.Instance metadata)
        {
            this.byond                          = byond ?? throw new ArgumentNullException(nameof(byond));
            this.ioManager                      = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
            this.configuration                  = configuration ?? throw new ArgumentNullException(nameof(configuration));
            this.sessionControllerFactory       = sessionControllerFactory ?? throw new ArgumentNullException(nameof(sessionControllerFactory));
            this.eventConsumer                  = eventConsumer ?? throw new ArgumentNullException(nameof(eventConsumer));
            this.chatManager                    = chatManager ?? throw new ArgumentNullException(nameof(chatManager));
            this.processExecutor                = processExecutor ?? throw new ArgumentNullException(nameof(processExecutor));
            this.compileJobConsumer             = compileJobConsumer ?? throw new ArgumentNullException(nameof(compileJobConsumer));
            this.repositoryManager              = repositoryManager ?? throw new ArgumentNullException(nameof(repositoryManager));
            this.remoteDeploymentManagerFactory = remoteDeploymentManagerFactory ?? throw new ArgumentNullException(nameof(remoteDeploymentManagerFactory));
            this.logger                         = logger ?? throw new ArgumentNullException(nameof(logger));
            this.metadata                       = metadata ?? throw new ArgumentNullException(nameof(metadata));

            deploymentLock = new object();
        }
示例#23
0
        /// <summary>
        /// Construct an <see cref="CommContext"/>
        /// </summary>
        /// <param name="ioManager">The value of <see cref="ioManager"/></param>
        /// <param name="logger">The value of <see cref="logger"/></param>
        /// <param name="directory">The path to watch</param>
        /// <param name="filter">The filter to watch for</param>
        public CommContext(IIOManager ioManager, ILogger <CommContext> logger, string directory, string filter)
        {
            this.ioManager = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
            this.logger    = logger ?? throw new ArgumentNullException(nameof(logger));

            directory = ioManager.ResolvePath(directory) ?? throw new ArgumentNullException(nameof(directory));
            if (filter == null)
            {
                throw new ArgumentNullException(nameof(filter));
            }

            fileSystemWatcher = new FileSystemWatcher(directory, filter)
            {
                EnableRaisingEvents   = true,
                IncludeSubdirectories = false,
                NotifyFilter          = NotifyFilters.LastWrite
            };

            fileSystemWatcher.Created += HandleWrite;
            fileSystemWatcher.Changed += HandleWrite;

            cancellationTokenSource = new CancellationTokenSource();
            cancellationToken       = cancellationTokenSource.Token;
            disposed = false;
        }
示例#24
0
 /// <summary>
 /// Construct a <see cref="ChatFactory"/>
 /// </summary>
 /// <param name="ioManager">The value of <see cref="ioManager"/></param>
 /// <param name="loggerFactory">The value of <see cref="loggerFactory"/></param>
 /// <param name="commandFactory">The value of <see cref="commandFactory"/></param>
 /// <param name="providerFactory">The value of <see cref="providerFactory"/></param>
 public ChatFactory(IIOManager ioManager, ILoggerFactory loggerFactory, ICommandFactory commandFactory, IProviderFactory providerFactory)
 {
     this.ioManager       = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
     this.loggerFactory   = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
     this.commandFactory  = commandFactory ?? throw new ArgumentNullException(nameof(commandFactory));
     this.providerFactory = providerFactory ?? throw new ArgumentNullException(nameof(providerFactory));
 }
示例#25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BasicWatchdog"/> <see langword="class"/>.
 /// </summary>
 /// <param name="chat">The <see cref="IChatManager"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="sessionControllerFactory">The <see cref="ISessionControllerFactory"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="dmbFactory">The <see cref="IDmbFactory"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="sessionPersistor">The <see cref="ISessionPersistor"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="jobManager">The <see cref="IJobManager"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="serverControl">The <see cref="IServerControl"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="asyncDelayer">The <see cref="IAsyncDelayer"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="diagnosticsIOManager">The <see cref="IIOManager"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="eventConsumer">The <see cref="IEventConsumer"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="remoteDeploymentManagerFactory">The <see cref="IRemoteDeploymentManagerFactory"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="logger">The <see cref="ILogger"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="initialLaunchParameters">The <see cref="DreamDaemonLaunchParameters"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="instance">The <see cref="Api.Models.Instance"/> for the <see cref="WatchdogBase"/>.</param>
 /// <param name="autoStart">The autostart value for the <see cref="WatchdogBase"/>.</param>
 public BasicWatchdog(
     IChatManager chat,
     ISessionControllerFactory sessionControllerFactory,
     IDmbFactory dmbFactory,
     ISessionPersistor sessionPersistor,
     IJobManager jobManager,
     IServerControl serverControl,
     IAsyncDelayer asyncDelayer,
     IIOManager diagnosticsIOManager,
     IEventConsumer eventConsumer,
     IRemoteDeploymentManagerFactory remoteDeploymentManagerFactory,
     ILogger <BasicWatchdog> logger,
     DreamDaemonLaunchParameters initialLaunchParameters,
     Api.Models.Instance instance,
     bool autoStart)
     : base(
         chat,
         sessionControllerFactory,
         dmbFactory,
         sessionPersistor,
         jobManager,
         serverControl,
         asyncDelayer,
         diagnosticsIOManager,
         eventConsumer,
         remoteDeploymentManagerFactory,
         logger,
         initialLaunchParameters,
         instance,
         autoStart)
 {
 }
示例#26
0
        /// <summary>
        /// Construct a <see cref="ChatManager"/>
        /// </summary>
        /// <param name="providerFactory">The value of <see cref="providerFactory"/></param>
        /// <param name="ioManager">The value of <see cref="ioManager"/></param>
        /// <param name="commandFactory">The value of <see cref="commandFactory"/></param>
        /// <param name="serverControl">The <see cref="IServerControl"/> to populate <see cref="restartRegistration"/> with</param>
        /// <param name="asyncDelayer">The value of <see cref="asyncDelayer"/></param>
        /// <param name="loggerFactory">The value of <see cref="loggerFactory"/></param>
        /// <param name="logger">The value of <see cref="logger"/></param>
        /// <param name="initialChatBots">The <see cref="IEnumerable{T}"/> used to populate <see cref="activeChatBots"/></param>
        public ChatManager(IProviderFactory providerFactory, IIOManager ioManager, ICommandFactory commandFactory, IServerControl serverControl, IAsyncDelayer asyncDelayer, ILoggerFactory loggerFactory, ILogger <ChatManager> logger, IEnumerable <Models.ChatBot> initialChatBots)
        {
            this.providerFactory = providerFactory ?? throw new ArgumentNullException(nameof(providerFactory));
            this.ioManager       = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
            this.commandFactory  = commandFactory ?? throw new ArgumentNullException(nameof(commandFactory));
            if (serverControl == null)
            {
                throw new ArgumentNullException(nameof(serverControl));
            }
            this.asyncDelayer  = asyncDelayer ?? throw new ArgumentNullException(nameof(asyncDelayer));
            this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
            this.logger        = logger ?? throw new ArgumentNullException(nameof(logger));
            activeChatBots     = initialChatBots?.ToList() ?? throw new ArgumentNullException(nameof(initialChatBots));

            restartRegistration = serverControl.RegisterForRestart(this);

            synchronizationLock = new object();

            builtinCommands    = new Dictionary <string, ICommand>();
            providers          = new Dictionary <long, IProvider>();
            mappedChannels     = new Dictionary <ulong, ChannelMapping>();
            trackingContexts   = new List <IChatTrackingContext>();
            handlerCts         = new CancellationTokenSource();
            connectionsUpdated = new TaskCompletionSource <object>();
            channelIdCounter   = 1;
        }
        /// <inheritdoc />
        public IWatchdog CreateWatchdog(
            IChat chat,
            IDmbFactory dmbFactory,
            IReattachInfoHandler reattachInfoHandler,
            IEventConsumer eventConsumer,
            ISessionControllerFactory sessionControllerFactory,
            IIOManager ioManager,
            Api.Models.Instance instance,
            DreamDaemonSettings settings)
        {
            if (GeneralConfiguration.UseExperimentalWatchdog)
            {
                return(new ExperimentalWatchdog(
                           chat,
                           sessionControllerFactory,
                           dmbFactory,
                           reattachInfoHandler,
                           DatabaseContextFactory,
                           ByondTopicSender,
                           eventConsumer,
                           JobManager,
                           ServerControl,
                           AsyncDelayer,
                           LoggerFactory.CreateLogger <ExperimentalWatchdog>(),
                           settings,
                           instance,
                           settings.AutoStart.Value));
            }

            return(CreateNonExperimentalWatchdog(chat, dmbFactory, reattachInfoHandler, eventConsumer, sessionControllerFactory, ioManager, instance, settings));
        }
示例#28
0
 public LogFile()
 {
     this.IOManager   = new IOManager(CURRENT_DIRECTORY, CURRENT_FILE);
     this.currentPath = this.IOManager.GetCurrentPath();
     this.IOManager.EnsureDirectoryAndFileExist();
     this.Path = currentPath + CURRENT_DIRECTORY + CURRENT_FILE;
 }
 /// <summary>
 /// Construct a <see cref="ChangelogGeneratorModule"/>
 /// </summary>
 /// <param name="dataStoreFactory">The <see cref="IDataStoreFactory{TModule}"/> to create <see cref="dataStore"/> from</param>
 /// <param name="stringLocalizer">The value of <see cref="stringLocalizer"/></param>
 /// <param name="generalConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the value of <see cref="generalConfiguration"/></param>
 /// <param name="ioManager">The value of <see cref="ioManager"/></param>
 /// <param name="repository">The value of <see cref="repository"/></param>
 public ChangelogGeneratorModule(IDataStoreFactory <ChangelogGeneratorModule> dataStoreFactory, IStringLocalizer <ChangelogGeneratorModule> stringLocalizer, IOptions <GeneralConfiguration> generalConfigurationOptions, IIOManager ioManager, IRepository repository)
 {
     this.stringLocalizer = stringLocalizer ?? throw new ArgumentNullException(nameof(stringLocalizer));
     this.ioManager       = ioManager ?? throw new ArgumentNullException(nameof(ioManager));
     this.repository      = repository ?? throw new ArgumentNullException(nameof(repository));
     generalConfiguration = generalConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(generalConfigurationOptions));
     dataStore            = dataStoreFactory?.CreateDataStore(this) ?? throw new ArgumentNullException(nameof(dataStoreFactory));
 }
 /// <summary>
 /// Construct a <see cref="LocalRepositoryManager"/>
 /// </summary>
 /// <param name="ioManager">The value of <see cref="ioManager"/></param>
 /// <param name="localRepositoryFactory">The value of <see cref="localRepositoryFactory"/></param>
 /// <param name="repositoryOperations">The value of <see cref="repositoryOperations"/></param>
 /// <param name="logger">The value of <see cref="logger"/></param>
 public LocalRepositoryManager(IIOManager ioManager, ILocalRepositoryFactory localRepositoryFactory, IRepositoryOperations repositoryOperations, ILogger <LocalRepositoryManager> logger)
 {
     this.ioManager = new ResolvingIOManager(ioManager ?? throw new ArgumentNullException(nameof(ioManager)), "Repositories");
     this.localRepositoryFactory = localRepositoryFactory ?? throw new ArgumentNullException(nameof(localRepositoryFactory));
     this.repositoryOperations   = repositoryOperations ?? throw new ArgumentNullException(nameof(repositoryOperations));
     this.logger        = logger ?? throw new ArgumentNullException(nameof(logger));
     activeRepositories = new Dictionary <string, Task>();
 }
示例#31
0
        /// <summary>
        /// Starts the game loop.
        /// </summary>
        /// <param name="gridManager">The <see cref="GridManager" /> which handles the game.</param>
        /// <param name="ioManager">An object specifying how the I/O should be handled.</param>
        public static void Run(GridManager gridManager, IIOManager ioManager)
        {
            bool anotherGame;
            do
            {
                anotherGame = false;

                int playersCount = 2;
                string[] warriorCharacters = new string[playersCount];
                for (int i = 0; i < playersCount; i++)
                {
                    warriorCharacters[i] = ReadWarriorCharacter(ioManager, i);
                }

                gridManager.ArrangeGameObjects(warriorCharacters);
                ioManager.WriteLine(gridManager.DisplayGrid());

                int currentPlayerIndex = 0;
                while (true)
                {
                    MoveResult result;
                    do
                    {
                        result = MakeValidMove(gridManager, ioManager, currentPlayerIndex);

                        ioManager.WriteLine(gridManager.DisplayGrid(result));
                        if (result == MoveResult.DrawnBattle ||
                            result == MoveResult.Battle)
                        {
                            if (ReadAnotherGameResponse(ioManager) == "n")
                            {
                                return;
                            }
                            else
                            {
                                anotherGame = true;
                                break;
                            }
                        }

                    } while (result == MoveResult.MoreMoves);

                    if (anotherGame) break;

                    gridManager.RefreshWarriorsRemainingMoves();

                    if (result == MoveResult.NoMoreMoves)
                    {
                        currentPlayerIndex = (++currentPlayerIndex) % playersCount;
                    }
                }
            } while (anotherGame);
        }
示例#32
0
 /// <summary>
 /// For testing purposes only. Plays the game with I/O redirected to/from files.
 /// </summary>
 /// <param name="gridManager">The <see cref="GridManager" /> which handles the game.</param>
 /// <param name="ioManager">An object specifying how the I/O should be handled.</param>
 /// <param name="inputFilePath">The path of the input file.</param>
 /// <param name="outputFilePath">The path of the output file.</param>
 /// <example>
 /// This example shows how to call the <see cref="RunWithIORedirected(GridManager, string, string)"/> method.
 /// <code>
 /// class TestClass
 /// {
 ///     static void Main()
 ///     {
 ///         GridManager gridManager = new GridManager();
 ///         
 ///         RunWithIORedirected(
 ///             gridManager,
 ///             Path.Combine(Environment.CurrentDirectory, "SampleInput.in"),
 ///             Path.Combine(Environment.CurrentDirectory, "SampleOutput.out"));
 ///     }
 /// }
 /// </code>
 /// </example>
 public static void RunWithIORedirected(
     GridManager gridManager,
     IIOManager ioManager,
     string inputFilePath,
     string outputFilePath)
 {
     using (StreamReader reader = new StreamReader(inputFilePath))
     {
         using (StreamWriter writer = new StreamWriter(outputFilePath))
         {
             ioManager.SetIn(reader);
             ioManager.SetOut(writer);
             Run(gridManager, ioManager);
         }
     }
 }
示例#33
0
        /// <summary>
        /// Starts the game loop.
        /// </summary>
        /// <param name="gridManager">The <see cref="GridManager" /> which handles the game.</param>
        /// <param name="ioManager">An object specifying how the I/O should be handled.</param>
        public static void Run(GridManager gridManager, IIOManager ioManager)
        {
            ioManager.WriteLine(
                "\t\tBATTLESHIP by ANONYMOUS SOLUTIONS INC.{0}{0}" +
                "You are given a square {1}x{1} grid. The individual squares in the grid{0}" +
                "are identified by letter and number, e.g. A5. Several ships have been{0}" +
                "secretly arranged. Each ship occupies a number of consecutive squares{0}" +
                "on the grid, arranged either horizontally or vertically. The ships can{0}" +
                "touch each other and cannot overlap. The fleet consists of {2} ship(s).{0}" +
                "Your task is to sink them all.{0}",
                Environment.NewLine,
                GridManager.GridSize,
                gridManager.ShipsCount);

            ioManager.WriteLine(gridManager.DisplayShips(false));

            while (true)
            {
                ioManager.Write("Enter target square to shoot at: ");

                string command = ioManager.ReadLine();
                if (command == GridManager.BackdoorCommand)
                {
                    ioManager.WriteLine(gridManager.DisplayShips(true));
                }
                else
                {
                    ShotResult shotResult = gridManager.ShootTarget(command);

                    DisplayShotResult(gridManager, ioManager, shotResult);
                    if (shotResult == ShotResult.AllShipsSunk)
                    {
                        return;
                    }

                    ioManager.WriteLine(gridManager.DisplayShips(false));
                }
            }
        }
示例#34
0
 public BeursfuifData(IIOManager ioManager)
 {
     _ioManager = ioManager;
     LoadAllData();
 }
示例#35
0
 /// <summary>
 /// Displays a string depending on the specified ShotResult.
 /// </summary>
 /// <param name="gridManager">The <see cref="GridManager" /> which handles the game.</param>
 /// <param name="ioManager">An object specifying how the I/O should be handled.</param>
 /// <param name="value">The value to display.</param>
 public static void DisplayShotResult(GridManager gridManager, IIOManager ioManager, ShotResult value)
 {
     switch (value)
     {
         case ShotResult.Hit:
             {
                 ioManager.WriteLine("\t*** Hit ***");
                 break;
             }
         case ShotResult.ShipSunk:
             {
                 ioManager.WriteLine("\t*** Sunk ***");
                 break;
             }
         case ShotResult.AllShipsSunk:
             {
                 ioManager.WriteLine("Well done! You completed the game in {0} shots.", gridManager.ShotsCount);
                 break;
             }
         case ShotResult.Miss:
             {
                 ioManager.WriteLine("\t*** Miss ***");
                 break;
             }
         case ShotResult.Error:
             {
                 ioManager.WriteLine("\t*** Error ***");
                 break;
             }
         default:
             {
                 throw new BattleshipException("Unknown ShotResult.");
             }
     }
 }
示例#36
0
        private static string ReadAnotherGameResponse(IIOManager ioManager)
        {
            string anotherGameResponse;
            do
            {
                ioManager.Write("Do you want another game? (y/n)");
                anotherGameResponse = ioManager.ReadLine();

            } while (!Regex.IsMatch(anotherGameResponse, "^[yn]$"));
            return anotherGameResponse;
        }
示例#37
0
        private static MoveResult MakeValidMove(GridManager gridManager, IIOManager ioManager, int playerIndex)
        {
            MoveResult result;
            Direction direction;
            do
            {
                ioManager.Write(string.Format("{0}Player {1}, please make a move.", Environment.NewLine, playerIndex + 1));
                direction = ReadDirection(ioManager);

            } while ((result = gridManager.TryMove(direction, playerIndex)) == MoveResult.InvalidDirection);
            return result;
        }
示例#38
0
        private static string ReadWarriorCharacter(IIOManager ioManager, int playerIndex)
        {
            string character;
            do
            {
                ioManager.Write(string.Format("Player {0}, please select a warrior. Turtle, monkey or pigeon? (t/m/p)", playerIndex + 1));
                character = ioManager.ReadLine();

            } while (!Regex.IsMatch(character, "^[tmp]$"));
            return character;
        }
示例#39
0
 private static Direction ReadDirection(IIOManager ioManager)
 {
     ConsoleKeyInfo key;
     do
     {
         key = ioManager.ReadKey();
     } while (
         key.Key != ConsoleKey.LeftArrow &&
         key.Key != ConsoleKey.UpArrow &&
         key.Key != ConsoleKey.RightArrow &&
         key.Key != ConsoleKey.DownArrow);
     return GetDirection(key.Key);
 }