示例#1
0
 public SoilSampleProcessor(List <string> filePaths)
 {
     foreach (var path in filePaths)
     {
         FilePaths.Add(Path.GetFullPath(path));
     }
 }
示例#2
0
        public async Task AddFilePathsAsync(IEnumerable <string> paths)
        {
            CanProcessing.Value = false;

            await Task.Run(() =>
            {
                foreach (var path in paths)
                {
                    CancellationToken.ThrowIfCancellationRequested();

                    if (FilePaths.Contains(path) || !File.Exists(path))
                    {
                        continue;
                    }

                    try
                    {
                        using (var bmp = new Bitmap(path))
                        { }
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    FilePaths.AddOnScheduler(path);
                }
            }, CancellationToken);

            CanProcessing.Value = true;
        }
示例#3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GameApplication"/> class.</summary>
        /// <remarks><para>
        /// This constructor performs the following actions:
        /// </para><list type="bullet"><item>
        /// Call <see cref="ApplicationUtility.CheckSingleInstance"/> to make sure that the current
        /// user is not already running another instance of the <see cref="GameApplication"/>.
        /// </item><item>
        /// Call <see cref="FilePaths.CheckUserFolders"/> to make sure that the current user has
        /// write permission in the directories that hold user-specific data.
        /// </item><item>
        /// Attach a handler to the <see cref="Application.DispatcherUnhandledException"/> event
        /// that calls <see cref="ApplicationUtility.OnUnhandledException"/>.
        /// </item><item>
        /// Create a global instance of the <see cref="ApplicationOptions"/> class and load the
        /// current user settings.</item></list></remarks>

        public GameApplication()
        {
            // make sure this is the only instance
            if (!ApplicationUtility.CheckSingleInstance())
            {
                Application.Current.Shutdown(-1);
                return;
            }

            // make sure we can create user files
            if (!FilePaths.CheckUserFolders())
            {
                Application.Current.Shutdown(-2);
                return;
            }

            // hook up custom exception handler
            Application.Current.DispatcherUnhandledException += OnUnhandledException;

            // read user settings from Hexkit Game options file
            ApplicationOptions options = ApplicationOptions.CreateInstance();

            // select user-defined display theme, if any
            if (options.View.Theme != DefaultTheme.System)
            {
                DefaultThemeSetter.Select(options.View.Theme);
            }
        }
示例#4
0
        /// <summary>
        /// Shows a <see cref="FileDialogs.SaveSectionDialog"/> allowing the user to enter or select
        /// an <see cref="AreaSection"/> file to save the current <see cref="WorldState"/> to.
        /// </summary>
        /// <param name="file">
        /// The file initially selected in the dialog.</param>
        /// <remarks><para>
        /// The specified <paramref name="file"/> may be a null reference or an empty string to
        /// indicate that no file should be initially selected. Otherwise, any directory prefix it
        /// contains overrides the specified <paramref name="file"/>. Files without an absolute path
        /// are interpreted as relative to the <see cref="ScenarioSection.Areas"/> section folder.
        /// </para><para>
        /// <b>SaveAreas</b> attempts to create a new <see cref="AreaSection"/> object from the <see
        /// cref="WorldState"/> of the current session, using the latter's <see
        /// cref="WorldState.CreateAreaSection"/> method, and then invokes <see
        /// cref="ScenarioElement.Save"/> on the new <see cref="AreaSection"/> object. If either
        /// operation fails, an error message is shown but no exception is thrown.</para></remarks>

        public static void SaveAreas(string file)
        {
            // abort if no world state to save
            if (Session.Instance == null)
            {
                return;
            }

            // let user select file path for Areas section
            RootedPath path = FilePaths.GetSectionFile(ScenarioSection.Areas, file);

            path = FileDialogs.SaveSectionDialog(ScenarioSection.Areas, path.AbsolutePath);
            if (path.IsEmpty)
            {
                return;
            }

            try {
                // create Areas section from world state
                AreaSection areas = Session.Instance.WorldState.CreateAreaSection(0, 0, 0, 0);
                areas.Save(path.AbsolutePath);
            }
            catch (Exception e) {
                string message = String.Format(ApplicationInfo.Culture,
                                               Global.Strings.DialogSectionSaveError, path.AbsolutePath);

                MessageDialog.Show(MainWindow.Instance, message,
                                   Global.Strings.TitleSectionError, e, MessageBoxButton.OK, Images.Error);
            }
        }
示例#5
0
        public RealtyManager(DatabaseInterface dbInterface)
        {
            DbInterface = dbInterface;

            var byNameFile = new FilePaths
            {
                FileBlockData =
                    "../../../SystemCore/data/ByNameAndReg/blocks.txt",
                FileOverflowFile =
                    "../../../SystemCore/data/ByNameAndReg/overflow.txt",
                FileTreeData =
                    "../../../SystemCore/data/ByNameAndReg/configuration.txt"
            };

            DhRealtyByNameAndRegNumber = new DynHash <RealtyByCadAndRegNumber>(byNameFile, DefaultBlockFactor, DefaultOverflowBlockFactor);
            var byId = new FilePaths
            {
                FileBlockData    = "../../../SystemCore/data/ById/blocks.txt",
                FileOverflowFile = "../../../SystemCore/data/ById/overflow.txt",
                FileTreeData     = "../../../SystemCore/data/ById/configuration.txt"
            };

            DhRealtyById = new DynHash <RealtyById>(byId, DefaultBlockFactor, DefaultOverflowBlockFactor);

            var rafBlockFile = "../../../SystemCore/data/Raf/blocks.txt";
            var rafConfFile  = "../../../SystemCore/data/Raf/configuration.txt";

            RafRealties = new RandomAccessFile <Realty>(rafBlockFile, rafConfFile, DefaultBlockFactor);
        }
示例#6
0
        /// <summary>
        /// this method read inventory details from java script object notation file
        /// and display it.
        /// </summary>
        public void PrintTotalData()
        {
            try
            {
                //// Reads the file
                Inventory inventoryDetails = new Inventory();

                ////Instance of the File path to get json fule path
                FilePaths filePath = new FilePaths();

                ////creating list of type inventory structure to store read data into list
                List <InventoryStructure> items = inventoryDetails.ReadFile(filePath.InventoryProducts);

                ////Print the data format
                Console.WriteLine("Name\t\tWeight\t\tPricePerKg\tTotalAmount");
                foreach (var item in items)
                {
                    ////Print the details with total cost
                    Console.WriteLine("{0}" + "\t\t" + "{1}" + "\t\t" + "{2}" + "\t\t" + "{3}", item.Name, item.Weight, item.PricePerKg, item.PricePerKg * item.Weight);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
示例#7
0
        /// <summary> GZip processing entry point </summary>
        /// <param name="args"> Console input </param>
        public void Run(string[] args)
        {
            Guard.NotNull(args, $"{nameof(args)}");
            Guard.True(args.Length > 0, $"{Resources.MainInputParametersEmpty}");

            // Check input and prepare initial params for processing start
            OperationType operationType;

            if (!operations.TryGetValue(args[0], out operationType))
            {
                Console.WriteLine(Resources.MainWrongOperationMessage);
                return;
            }

            var pathParams = new FilePaths
            {
                InputFilePath  = args[1],
                OutputFilePath = args[2]
            };

            Console.WriteLine(Resources.MainProcessStartedMessage, DateTime.Now);

            Log.Information(
                $"File processing started input file {pathParams.InputFilePath}, output file {pathParams.OutputFilePath}, operation {args[0]}");

            // Execute processing
            ProcessFile(pathParams, operationType);

            Log.Information("File processing finished.");
            Console.WriteLine(Resources.MainProcessFinishedMessage, DateTime.Now);
        }
        private void GenerateAllModels()
        {
            if (FilePaths == null)
            {
                System.Windows.MessageBox.Show("You have not selected any schematics!", "Files not found!", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            foreach (string path in FilePaths)
            {
                List <String> blockNames3D = GetBlockNames3D(path);

                if (blockNames3D.Count != 0)
                {
                    GenerateModelFile(blockNames3D, Path.GetFileNameWithoutExtension(path));
                }
            }

            // Copy RP dependencies to output
            Copy(@"Resources/textures/schematic_to_model", TextureExportPath);
            File.Copy(@"Resources/pack.mcmeta", RootPath + "\\pack.mcmeta", true);

            if (IncludeStickBool.IsChecked.Value)
            {
                File.Copy(@"Resources/models/item/stick.json", ItemExportPath + "stick.json", false);
            }

            // Report all converted files to user
            string report = string.Join(Environment.NewLine, FilePaths.Select(array => string.Join("\n", Path.GetFileNameWithoutExtension(array))));

            System.Windows.MessageBox.Show("Successfully converted the following schematics:\n\n" + report, "Success!", MessageBoxButton.OK, MessageBoxImage.Information);

            Process.Start(ExportPath);
        }
示例#9
0
        /// <summary>
        /// Request a element from a given url
        /// </summary>
        /// <param name="url"></param>
        /// <param name="checksum"></param>
        /// <param name="ignoreCaching"></param>
        /// <param name="inTargetFile"></param>
        /// <returns></returns>
        public async Task <StorageFile> requestAsync(string url, string checksum, IonContent content, bool ignoreCaching)
        {
            string targetPath  = "other";
            string contentType = content.type;

            switch (contentType)
            {
            case IonConstants.ImageContentIdentifier:
            {
                targetPath = FilePaths.getMediaFilePath(url, _config);
                break;
            }

            case IonConstants.FileContentIdentifier:
            {
                targetPath = FilePaths.getMediaFilePath(url, _config);
                break;
            }

            case IonConstants.MediaContentIdentifier:
            {
                targetPath = FilePaths.getMediaFilePath(url, _config);
                break;
            }
            }

            return(await requestAsync(url, targetPath, checksum, ignoreCaching));
        }
    public async Task Run()
    {
        try
        {
            string PageResponse = await RequestCurrentStatus();

            if (PageResponse != null)
            {
                Player DownloadInfo = Player.RetrievePlayer(PageResponse);
                if (DownloadInfo.Quality == Quality.NotFound)
                {
                    return;
                }

                string Title       = ScrapeBit.FirstFrom(PageResponse, TITLE);
                string Path        = FilePaths.GetLivestreamsPath(FileName.Purify($"{Title} [{DateTime.Now.Ticks.GetHashCode()}].mp4"));
                string Description = ScrapeBit.FirstFrom(PageResponse, DESCRIPTION);


                Console.WriteLine($"Found Livestream with Title: {Title} and Quality: {DownloadInfo.Quality}");
                await Download(DownloadInfo.Url, Path);

                var Upload = new Youtube(FilePaths.SecretsFile);
                await Upload.Init();

                _ = Upload.UploadWithRetry(new YoutubeUpload()
                {
                    LivestreamPath = Path, Title = Title, Description = Description, ThumbnailPath = null
                }, TimeSpan.FromHours(3));
            }
        }

        catch (Exception x) { Console.WriteLine($"Error in Check loop, Exception occurred: {x.Message}, please restart"); }
    }
示例#11
0
        public void When_CreateEmpty_Expect_Empty()
        {
            FilePaths fp = new FilePaths();

            Assert.AreEqual(fp.inFile, "");
            Assert.AreEqual(fp.outFile, "");
        }
示例#12
0
        public void When_CreateExplicit_Expect_Explicit()
        {
            FilePaths fp = new FilePaths("inFile", "outFile");

            Assert.AreEqual(fp.inFile, "inFile");
            Assert.AreEqual(fp.outFile, "outFile");
        }
示例#13
0
        private async Task AddDocumentToFileSystemAndDb(int id, MultipartMemoryStreamProvider provider)
        {
            for (int i = 0; i < provider.Contents.Count - 1; i++)
            {
                var file = provider.Contents[i];

                if (file.Headers.ContentDisposition.FileName != null)
                {
                    var dir = FilePaths.WriteSupportingDoc + FilePaths.FolderFromUniqueId(id);
                    if (!System.IO.Directory.Exists(dir))
                    {
                        System.IO.Directory.CreateDirectory(dir);
                    }

                    // For an unknown reason, the FileName has an extra '\' everywhere, that's why it's replaced with string.Empty
                    var writePath = dir + file.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);

                    var dataStream = await file.ReadAsByteArrayAsync();

                    using (var saveFile = File.OpenWrite(writePath))
                    {
                        await saveFile.WriteAsync(dataStream, 0, dataStream.Length);
                    }

                    var dateModified = await FileDates.StreamToString(provider.Contents[i + 1]);
                    await AddFileReferenceToDatabase(id, dateModified, writePath);
                }
            }
        }
示例#14
0
 private Task ClearAsync()
 {
     return(Task.Run(() =>
     {
         FilePaths.ClearOnScheduler();
     }, CancellationToken));
 }
示例#15
0
        public override void GetContainer(TransactionContainerAbstract container, string filePath)
        {
            if (!FilePaths.Contains(filePath))
            {
                FilePaths.Add(filePath);
            }
            else
            {
                throw new Exception("This file has already been loaded");
            }

            container.Clear();

            foreach (var currentPath in FilePaths)
            {
                var lines = File.ReadLines(currentPath);

                foreach (string s in lines)
                {
                    string[] split = s.Split(',');

                    if (split.Length != AttributeNumber)
                    {
                        throw new Exception("Column number mismatch");
                    }

                    container.AddTransaction(long.Parse(split[0]),
                                             DateTime.ParseExact(split[1], "HH:mm:ss", CultureInfo.InvariantCulture),
                                             split[4],
                                             double.Parse(split[5], CultureInfo.InvariantCulture),
                                             double.Parse(split[7], CultureInfo.InvariantCulture),
                                             split[15] == "B" ? true : false);
                }
            }
        }
        private void DeleteItem(object filenameitem)
        {
            FileNameItem fni = filenameitem as FileNameItem;

            Mementor.ElementRemove(FilePaths, fni);
            FilePaths.Remove(fni);
        }
示例#17
0
        public void ProcessFileTest_WorksFine()
        {
            // arrange
            var pathParams = new FilePaths
            {
                InputFilePath  = "input",
                OutputFilePath = "output"
            };
            var operationType = OperationType.Compress;
            var operation     = new Mock <CompressionOperation>(null, null, null);

            // expectations
            operationFactory.Setup(_ => _.Create(operationType))
            .Returns(operation.Object);

            taskManager.Setup(_ => _.CreateTasks(pathParams, operation.Object))
            .Verifiable();

            threadManager.Setup(_ => _.ExecuteInParallel(taskManager.Object, It.IsAny <Action <Exception> >()));

            // act
            target.ProcessFile(pathParams, operationType);

            // assert
            operationFactory.VerifyAll();
            taskManager.VerifyAll();
            threadManager.VerifyAll();
        }
        public List <string> ReadDB(FilePaths fp)
        {
            List <string> DBStringList = new List <string>();

            try
            {
                string dirPath  = Path.Combine(Directory.GetCurrentDirectory(), "DataBase");
                string filePath = GetFilePath(fp);



                // Open the stream and read it back.
                using (StreamReader sr = File.OpenText(filePath))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        DBStringList.Add(s);
                    }

                    return(DBStringList);
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(DBStringList);
            }
        }
示例#19
0
        public Configruation()
        {
            path = FilePaths.getFolderPath("atw_drinkinggame.config");

            Settings = new DrinkingSettings();
            Debug.Log(path);
        }
示例#20
0
    /// <summary>
    /// Creates Templates for new Letter Types (Default Schema Employee.xml)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lnkCreate_onclick(Object sender, EventArgs e)
    {
        clearMessages();
        string _fpath = "";

        _fpath = FilePaths.getFilePath("Schema");
        _fpath = _fpath.Replace("%20", " ");
        lnkInstall.Attributes.Add("onclick", "InstallDocSchema('" + _fpath + "','" + "EBAnamespace" + "')");

        int _seq = 0;
        ClientScriptManager cs = Page.ClientScript;

        try
        {
            if (!cs.IsClientScriptBlockRegistered(_seq + "CreateFile"))
            {
                cs.RegisterClientScriptBlock(typeof(Page), _seq + "CreateFile", "InstallDocSchema('" + _fpath + "','" + "EBAnamespace" + "')", true);
            }
        }
        catch (Exception ex)
        {
            errorDiv1.Visible      = true;
            lblErrorTemplates.Text = "Error Creating File - " + ex.Message;
        }
    }
        private string GetFilePath(FilePaths fp)
        {
            string dirPath      = Path.Combine(Directory.GetCurrentDirectory(), "DataBase");
            string resultString = "";

            switch (fp)
            {
            case FilePaths.Folder:
                resultString = dirPath;
                break;

            case FilePaths.Reservation:
                resultString = Path.Combine(dirPath, "Rudimentary_Reservation_DB.csv");
                break;

            case FilePaths.Table:
                resultString = Path.Combine(dirPath, "Rudimentary_Table_DB.csv");
                break;

            case FilePaths.Guest:
                resultString = Path.Combine(dirPath, "Rudimentary_Guest_DB.csv");
                break;

            default:
                throw new Exception($"Unknown Enumerate value detected: {fp}");
            }
            return(resultString);
        }
示例#22
0
        /// <summary>
        /// Gets a index from isolated storage of the device. Returns null, if the index isn't found
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="requestURL"></param>
        /// <param name="collectionIdentifier"></param>
        /// <returns>The index file or null, if the index file isn't found</returns>
        public static async Task <T> getIndexAsync <T>(string requestURL, IonConfig config) where T : CacheIndex
        {
            try
            {
                // Generate filePath for index
                string filePath = FilePaths.getCacheIndicesFolderPath(config) + FilePaths.getFileName(requestURL) + IonConstants.JsonFileExtension;

                T cacheIndex = null;
                using (await fileLocks.ObtainLock(filePath).LockAsync().ConfigureAwait(false))
                {
                    // Create file or use existing file
                    StorageFile file = await _localFolder.CreateFileAsync(filePath, CreationCollisionOption.OpenIfExists);

                    // Read content of the file
                    string content = await FileIO.ReadTextAsync(file);

                    // Deserialize cache index
                    cacheIndex = JsonConvert.DeserializeObject <T>(content);
                }

                fileLocks.ReleaseLock(filePath);

                return(cacheIndex);
            }
            catch (Exception e)
            {
                IonLogging.log("Error loading cacheIndex " + requestURL + " from isolated storage: " + e.Message, IonLogMessageTypes.ERROR);
                return(null);
            }
        }
示例#23
0
        /// <summary>
        /// Loads a collection from the isolated storage folder
        /// </summary>
        /// <param name="collectionIdentifier"></param>
        /// <returns>The collection or null, if the collection isn't found</returns>
        public static async Task <IonCollection> loadCollectionFromIsolatedStorageAsync(IonConfig config)
        {
            try
            {
                // Generate filePath for collection
                string filePath = FilePaths.getCollectionFolderPath(config) + config.collectionIdentifier + IonConstants.JsonFileExtension;

                IonCollection collection = null;
                using (await fileLocks.ObtainLock(filePath).LockAsync().ConfigureAwait(false))
                {
                    // Open file
                    StorageFile file = await _localFolder.GetFileAsync(filePath);

                    // Extract content
                    string content = await FileIO.ReadTextAsync(file);

                    // Deserialize collection
                    collection = JsonConvert.DeserializeObject <IonCollection>(content);
                }

                fileLocks.ReleaseLock(filePath);

                return(collection);
            }

            catch (Exception e)
            {
                IonLogging.log("Error loading collection " + config.collectionIdentifier + " from isolated storeage. Message: " + e.Message, IonLogMessageTypes.ERROR);
                return(null);
            }
        }
示例#24
0
        /// <summary>
        /// Saves a page to the isolated storage folder
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static async Task savePageToIsolatedStorageAsync(IonPage page, IonConfig config)
        {
            try
            {
                // Generate filePath for page
                string filePath = FilePaths.getPagesFolderPath(config) + page.identifier + IonConstants.JsonFileExtension;

                using (await fileLocks.ObtainLock(filePath).LockAsync().ConfigureAwait(false))
                {
                    // Create file or use existing file
                    StorageFile file = await _localFolder.CreateFileAsync(filePath, CreationCollisionOption.ReplaceExisting);

                    // Serialize collection
                    string pageSerialized = JsonConvert.SerializeObject(page);

                    // Write serialzed collection to file
                    await FileIO.WriteTextAsync(file, pageSerialized);
                }

                fileLocks.ReleaseLock(filePath);
            }

            catch (Exception e)
            {
                IonLogging.log("Error saving page to isolated storage: " + e.Message, IonLogMessageTypes.ERROR);
            }
        }
示例#25
0
        /// <summary>
        /// Saves a index file to the isolated storage on the device
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="requestURL"></param>
        /// <param name="cacheIndex"></param>
        /// <param name="collectionIdentifier"></param>
        /// <returns></returns>
        public static async Task saveIndexAsync <T>(string requestURL, T cacheIndex, IonConfig config) where T : CacheIndex
        {
            try
            {
                // Generate filePath for index
                string filePath = FilePaths.getCacheIndicesFolderPath(config) + FilePaths.getFileName(requestURL) + IonConstants.JsonFileExtension;

                using (await fileLocks.ObtainLock(filePath).LockAsync().ConfigureAwait(false))
                {
                    // Open an existing file or create a new one
                    StorageFile file = await _localFolder.CreateFileAsync(filePath, CreationCollisionOption.ReplaceExisting);

                    // Serialize cache índex
                    string cacheIndexSerialized = JsonConvert.SerializeObject(cacheIndex);

                    // Write serialzed collection to file
                    await FileIO.WriteTextAsync(file, cacheIndexSerialized);
                }

                fileLocks.ReleaseLock(filePath);
            }

            catch (Exception e)
            {
                IonLogging.log("Error saving cacheIndex to isolated storage. Message: " + e.Message, IonLogMessageTypes.ERROR);
            }
        }
示例#26
0
//	static private void AddFSLineHeader(string stringToAdd) {
//		// If this ISN'T the first line in fs, then add a line break. (We don't want a line break to start the file off.)
//		if (fs.IndexOf("\n") != -1) {
//			fs += "\n";
//		}
//		AddFSLine(stringToAdd);
//	}

    static private void SaveRoomFileFromStringArray(int worldIndex, string roomKey, string[] roomFileArray)
    {
        // Otherwise, SAVE! :D
        string filePath = FilePaths.RoomFile(worldIndex, roomKey);

        try {
            StreamWriter sr = File.CreateText(filePath);
            foreach (string lineString in roomFileArray)
            {
                sr.WriteLine(lineString);
            }
            sr.Close();
            Debug.Log("SAVED ROOM " + roomKey);

            GameManagers.Instance.EventManager.OnEditorSaveRoom();

            //// Reload the text file right away!! (Otherwise, we'll have to ALT + TAB out of Unity and back in for it to be refreshed.)
            //#if UNITY_EDITOR
            //UnityEditor.AssetDatabase.ImportAsset(filePath);
            //#endif
        }
        catch (Exception e) {
            Debug.LogError("Error saving a room to a text file: " + roomKey + ". Save location: " + filePath + ". Error string: " + e.ToString());
        }

//		// Finally! Delete the saved snapshot of this room completely! If we don't, a number of odd behaviors can occur from the data conflict. One notable effect is when changing posGlobal: carts' joints will be all wonky (because they were saved in a different part of the world).
//		GameplaySnapshotController.DeleteRoomSnapshotFromSaveStorage (WorldIndex, roomKey);
//		// Also delete the saved snapshot of the player if it's in this exact room.
//		GameplaySnapshotController.DeletePlayerDataSnapshotFromSaveStorageIfInRoomStatic (WorldIndex, roomKey);
    }
示例#27
0
 public ImageViewModelBase(FilePaths filePaths)
 {
     FilePaths           = filePaths;
     IsListEnabled       = true;
     StatusBarVisibility = Visibility.Hidden;
     // _loadFile = new Load(load);
 }
示例#28
0
 private void TryAddFilePathToList(string filePath)
 {
     if (!string.IsNullOrWhiteSpace(filePath))
     {
         FilePaths.Add(filePath);
     }
 }
示例#29
0
        /// <summary>
        /// Ends the turn for the <see cref="WorldState.ActiveFaction"/>, which must be controlled
        /// by a local human player, and activates subsequent factions.</summary>
        /// <exception cref="PropertyValueException">
        /// The current session <see cref="Session.State"/> is not <see cref="SessionState.Human"/>.
        /// </exception>
        /// <remarks><para>
        /// <b>EndTurn</b> should be called whenever a local human player wishes to end his turn.
        /// This method performs the following actions:
        /// </para><list type="number"><item>
        /// Save the current <see cref="Session.WorldState"/> to the predefined <see
        /// cref="SessionFileType.Auto"/> session file.
        /// </item><item>
        /// Issue an <see cref="EndTurnCommand"/> for the <see cref="WorldState.ActiveFaction"/>.
        /// </item><item>
        /// Call <see cref="Session.Dispatch"/> on the current <see cref="Session"/> to dispatch the
        /// game to the player controlling the faction that was activated in the previous step.
        /// </item></list><para>
        /// <b>EndTurn</b> calls <see cref="Session.Close"/> without confirmation if an error
        /// occurred, or if a faction controlled by a remote human player was activated.
        /// </para></remarks>

        public static void EndTurn()
        {
            CheckSessionState();
            Session session = Session.Instance;

            // autosave game before executing command
            string path = FilePaths.GetSessionFile(SessionFileType.Auto).AbsolutePath;

            session.Save(ref path, false);

            AsyncAction.BeginRun(delegate {
                Action postAction;

                // issue EndTurn command and dispatch game to next player
                if (session.Executor.ExecuteEndTurn(session.WorldState))
                {
                    postAction = session.Dispatch;
                }
                else
                {
                    postAction = () => Session.Close(false);
                }

                AsyncAction.BeginInvoke(delegate { postAction(); AsyncAction.EndRun(); });
            });
        }
示例#30
0
 private DefaultFileCacheDependency(params string[] paths) : this()
 {
     foreach (var path in paths)
     {
         FilePaths.Add(path);
     }
 }
示例#31
0
        /// <summary>
        /// Performs a full bootstrap by reading the uml classes 
        /// </summary>
        /// <param name="filePaths">Paths storing the uml</param>
        /// <param name="workspace">The workspace to which the extents will be aded</param>
        /// <param name="dataLayerLogic">The datalayerlogic being used to add the </param>
        /// <param name="dataLayer">The datalayer to which the new extents will be added</param>
        /// <returns></returns>
        public static Bootstrapper PerformFullBootstrap(FilePaths filePaths, Workspace<IExtent> workspace,
            IDataLayerLogic dataLayerLogic, IDataLayer dataLayer)
        {
            if (workspace == null) throw new ArgumentNullException(nameof(workspace));
            if (dataLayerLogic == null) throw new ArgumentNullException(nameof(dataLayerLogic));
            if (dataLayer == null) throw new ArgumentNullException(nameof(dataLayer));

            var strapper = PerformFullBootstrap(filePaths, dataLayerLogic, dataLayer);

            workspace.AddExtent(strapper.MofInfrastructure);
            workspace.AddExtent(strapper.UmlInfrastructure);
            workspace.AddExtent(strapper.PrimitiveInfrastructure);
            return strapper;
        }
示例#32
0
        /// <summary>
        ///     Performs a full bootstrap by reading in the uml class
        /// </summary>
        /// <param name="paths">Paths storing the uml information</param>
        /// <param name="dataLayerLogic">The datalayer logic to be used</param>
        /// <param name="dataLayer">The datalayer to be filled before the bootstrap itself</param>
        /// <returns>The instance of the bootstrapper</returns>
        public static Bootstrapper PerformFullBootstrap(
            FilePaths paths,
            IDataLayerLogic dataLayerLogic,
            IDataLayer dataLayer)
        {
            var factory = new MofFactory();
            var umlExtent = new MofUriExtent("datenmeister:///uml");
            var mofExtent = new MofUriExtent("datenmeister:///mof");
            var primitiveExtent = new MofUriExtent("datenmeister:///prototypes");
            var loader = new SimpleLoader(factory);
            loader.Load(primitiveExtent, paths.PathPrimitive);
            loader.Load(umlExtent, paths.PathUml);
            loader.Load(mofExtent, paths.PathMof);

            // Assigns the extents to the datalayer
            if (dataLayer != null && dataLayerLogic != null)
            {
                dataLayerLogic.AssignToDataLayer(mofExtent, dataLayer);
                dataLayerLogic.AssignToDataLayer(umlExtent, dataLayer);
                dataLayerLogic.AssignToDataLayer(primitiveExtent, dataLayer);
                dataLayerLogic.Create<FillTheMOF, _MOF>(dataLayer);
                dataLayerLogic.Create<FillTheUML, _UML>(dataLayer);
                dataLayerLogic.Create<FillThePrimitiveTypes, _PrimitiveTypes>(dataLayer);

                var dmml = new DmML();
                UmlToDmMLConverter.Convert(dataLayerLogic.Get<_UML>(dataLayer), dmml);
                dataLayerLogic.Set(dataLayer, dmml);
            }
            else
            {
                // To support the creation of _MOF and _UML, we need to have datalayers and their logic
                throw new InvalidOperationException("datalayers or dataLayerLogic is null");
            }

            // Now do the bootstrap
            var bootStrapper = new Bootstrapper(primitiveExtent, umlExtent, mofExtent, dataLayerLogic);
            bootStrapper.Strap();
            return bootStrapper;
        }