public void AddingNonExistingSectionWillCreateNew()
        {
            var project = CsProjects.SampleProjectSimple;
            var writer = new ProjectWriter(project);
            writer.AddFile(@"asd/qwe.txt", "ASDASD");

            var newProject = writer.GetXml();

            StringAssert.Contains("<ASDASD Include=\"asd\\qwe.txt\" />", newProject);
        }
        public void CanAddEmbeddedResourceFileInProject()
        {
            var project = CsProjects.SampleProjectSimple;
            var writer = new ProjectWriter(project);
            writer.AddEmbeddedResource("__test__");

            var newProject = writer.GetXml();

            StringAssert.Contains("<EmbeddedResource Include=\"__test__\" />", newProject);
        }
        public void CanAddCompileFileWithSlashInProjectAndItWillChangeToBackslash()
        {
            var project = CsProjects.SampleProjectSimple;
            var writer = new ProjectWriter(project);
            writer.AddCompile("__test__/asdasd");

            var newProject = writer.GetXml();

            StringAssert.Contains("<Compile Include=\"__test__\\asdasd\" />", newProject);
        }
        public void AddingDuplicatedFileWillMaintainTheLast()
        {
            var project = CsProjects.SampleProjectSimple;
            var writer = new ProjectWriter(project);
            writer.AddEmbeddedResource(@"Common\EnumerableExtensions.cs");

            var newProject = writer.GetXml();

            StringAssert.Contains("<Compile Include=\"Common\\EnumerableExtensions.cs\" />", newProject);
            StringAssert.DoesNotContain("<EmbeddedResource Include=\"Common\\EnumerableExtensions.cs\" />", newProject);
        }
Beispiel #5
0
        public void CanRemoveEnumerableExtensionsInProject()
        {
            var project = CsProjects.SampleProjectSimple;
            StringAssert.Contains("<Compile Include=\"Common\\EnumerableExtensions.cs\" />", project);

            var writer = new ProjectWriter(project);
            writer.RemoveFile(@"Common\EnumerableExtensions.cs");
            var newProject = writer.GetXml();

            StringAssert.DoesNotContain("<Compile Include=\"Common\\EnumerableExtensions.cs\" />", newProject);
        }
        public void AddingDuplicatedFileWontCreateNew()
        {
            var project = CsProjects.SampleProjectSimple;
            var writer = new ProjectWriter(project);
            writer.AddCompile(@"Common\EnumerableExtensions.cs");

            var newProject = writer.GetXml();

            Assert.AreEqual(
                newProject.IndexOf("Include=\"Common\\EnumerableExtensions.cs\" />"),
                newProject.LastIndexOf("Include=\"Common\\EnumerableExtensions.cs\" />"), "two occurrences");
        }
Beispiel #7
0
 public static void WriteMaxRoomIDs(ProjectWriter writer, int maxInstId, int maxTileId)
 {
     writer.Write(maxInstId);
     writer.Write(maxTileId);
 }
Beispiel #8
0
        public static void WriteGEX(ProjectWriter writer, string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (ProjectReader pr = new ProjectReader(fs))
                {
                    GEX gex = new GEX();
                    gex.Load(pr);

                    writer.Write(gex.Package.Version);
                    writer.Write(gex.Package.Name);
                    writer.Write(gex.Package.Folder);
                    writer.Write(gex.Package.Files.Count);
                    foreach (var file in gex.Package.Files)
                    {
                        writer.Write(file.Version);
                        writer.Write(file.FileName);
                        writer.Write((int)file.Kind);
                        writer.Write(file.Initialization);
                        writer.Write(file.Finalization);
                        writer.Write(file.Functions.Count);
                        int id = 0;
                        foreach (var func in file.Functions)
                        {
                            writer.Write(func.Version);
                            writer.Write(func.Name);
                            writer.Write(func.ExternalName);
                            writer.Write((int)func.Convention);
                            writer.Write(id); // ?????
                            writer.Write(func.Argc);
                            for (int i = 0; i < 17; i++)
                            {
                                writer.Write((int)func.ArgTypes[i]);
                            }
                            writer.Write((int)func.Return);
                            id++;
                        }
                    }
                    writer.Write(gex.Seed);

                    // Prepare DAT files...
                    MemoryStream ms = new MemoryStream();
                    for (int i = 0; i < gex.Package.Files.Count; i++)
                    {
                        if (gex.Package.Files[i].Kind == GEDFile.GEDFileKind.ActionLib)
                        {
                            continue;
                        }

                        byte[] zlibbed = ZlibStream.CompressBuffer(gex.RawDATs[i]);
                        byte[] size    = BitConverter.GetBytes(zlibbed.Length);
                        ms.Write(size);
                        ms.Write(zlibbed);
                    }
                    byte[] includes = ms.ToArray();
                    writer.Write(includes.Length);

                    // GMKrypt the data.
                    for (int i = 1; i < includes.Length; i++)
                    {
                        includes[i] = gex.GMKrypt[0][includes[i]];
                    }
                    writer.Write(includes);
                }
        }
        public async Task WritesDistinctConfigurations()
        {
            const string xml = @"
<Project DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""4.0"">
  <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" />
  <PropertyGroup>
    <VisualStudioVersion Condition=""'$(VisualStudioVersion)' == ''"">15.0</VisualStudioVersion>
    <OldToolsVersion>14.0</OldToolsVersion>
    <DslTargetsPath>..\SDK\v15.0\MSBuild\DSLTools</DslTargetsPath>
    <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
    <MinimumVisualStudioVersion>15.0</MinimumVisualStudioVersion>
  </PropertyGroup>
  <PropertyGroup>
    <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>
    <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>
    <ProjectGuid>{87161453-D71B-4ABB-BADB-1D0E621E8EA0}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Class1</RootNamespace>
    <AssemblyName>Class1</AssemblyName>
    <TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <TargetFrameworkProfile />
  </PropertyGroup>
  <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|x86' "">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
    <DocumentationFile>bin\Debug\Class1.xml</DocumentationFile>
    <RunCodeAnalysis>false</RunCodeAnalysis>
    <CodeAnalysisRuleSet>..\FxCop.Rules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|x64' "">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
    <DocumentationFile>bin\Release\Class1.xml</DocumentationFile>
    <RunCodeAnalysis>true</RunCodeAnalysis>
    <CodeAnalysisRuleSet>..\FxCop.Rules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x86'"">
    <OutputPath>bin\Release_CI\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <Optimize>true</Optimize>
    <DebugType>pdbonly</DebugType>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>..\FxCop.Rules.ruleset</CodeAnalysisRuleSet>
    <DocumentationFile>bin\Release_CI\Class1.xml</DocumentationFile>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <RunCodeAnalysis>true</RunCodeAnalysis>
  </PropertyGroup>
  <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x64'"">
    <OutputPath>bin\Release_CI\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <Optimize>true</Optimize>
    <DebugType>pdbonly</DebugType>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>..\FxCop.Rules.ruleset</CodeAnalysisRuleSet>
    <DocumentationFile>bin\Release_CI\Class1.xml</DocumentationFile>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <RunCodeAnalysis>true</RunCodeAnalysis>
  </PropertyGroup>
 </Project>";

            var project = await ParseAndTransform(xml).ConfigureAwait(false);

            Assert.AreEqual(2, project.Configurations.Count);
            Assert.AreEqual(1, project.Configurations.Count(x => x == "Debug"));
            Assert.AreEqual(1, project.Configurations.Count(x => x == "Release"));

            var writer  = new ProjectWriter();
            var xmlNode = writer.CreateXml(project);

            var generatedConfigurations = xmlNode.Element("PropertyGroup").Element("Configurations");

            Assert.IsNull(generatedConfigurations);
        }
Beispiel #10
0
 public void Save(ProjectWriter writer, GMProject proj)
 {
     writer.Write(Point);
     Event.Save(writer, proj);
 }
        public void Save(string fileName)
        {
            // StringWriter.Encoding always returns UTF16. We need it to return UTF8, so the
            // XmlDocument will write the UTF8 header.

            ItemGroups.Each(group => {
                var items = group.Items.ToArray();
                group.Element.RemoveAll();

                var orderedItems = items.OrderBy(x => x.Name).ThenBy(x => x.Include);
                orderedItems
                     .Each(item => group.AddNewItem(item.Name, item.Include));
            });

            var sw = new ProjectWriter(bom);
            sw.NewLine = newLine;
            doc.Save(sw);

            string content = sw.ToString();
            if (endsWithEmptyLine && !content.EndsWith(newLine))
                content += newLine;

            new FileSystem().WriteStringToFile(fileName, content);
        }
Beispiel #12
0
        /// <summary>
        /// This method updates a 'Project' object.
        /// </summary>
        /// <param name='List<PolymorphicObject>'>The 'Project' to update.
        /// <returns>A PolymorphicObject object with a value.
        internal PolymorphicObject UpdateProject(List <PolymorphicObject> parameters, DataConnector dataConnector)
        {
            // Initial Value
            PolymorphicObject returnObject = new PolymorphicObject();

            // locals
            Project project = null;

            // If the data connection is connected
            if ((dataConnector != null) && (dataConnector.Connected == true))
            {
                // Create Update StoredProcedure
                UpdateProjectStoredProcedure updateProjectProc = null;

                // verify the first parameters is a(n) 'Project'.
                if (parameters[0].ObjectValue as Project != null)
                {
                    // Create Project Parameter
                    project = (Project)parameters[0].ObjectValue;

                    // verify project exists
                    if (project != null)
                    {
                        // Now create updateProjectProc from ProjectWriter
                        // The DataWriter converts the 'Project'
                        // to the SqlParameter[] array needed to update a 'Project'.
                        updateProjectProc = ProjectWriter.CreateUpdateProjectStoredProcedure(project);
                    }

                    // Verify updateProjectProc exists
                    if (updateProjectProc != null)
                    {
                        // Execute Update Stored Procedure
                        bool saved = this.DataManager.ProjectManager.UpdateProject(updateProjectProc, dataConnector);

                        // Create returnObject.Boolean
                        returnObject.Boolean = new NullableBoolean();

                        // If save was successful
                        if (saved)
                        {
                            // Set returnObject.Boolean.Value to true
                            returnObject.Boolean.Value = NullableBooleanEnum.True;
                        }
                        else
                        {
                            // Set returnObject.Boolean.Value to false
                            returnObject.Boolean.Value = NullableBooleanEnum.False;
                        }
                    }
                    else
                    {
                        // Raise Error Data Connection Not Available
                        throw new Exception("The database connection is not available.");
                    }
                }
            }

            // return value
            return(returnObject);
        }
        public void RemovingLastItemOfAItemGroupWontLeaveItEmpty()
        {
            var project = CsProjects.SampleProjectSimple;
            var writer = new ProjectWriter(project);
            writer.AddFile(@"asd/qwe.txt", "ASDASD");

            var newWriter = new ProjectWriter(writer.GetXml());
            newWriter.RemoveFile("asd/qwe.txt");

            var xml = newWriter.GetXml().Replace("\n", "").Replace("\r", "").Replace(" ", "");
            StringAssert.DoesNotContain("<ItemGroup></ItemGroup>", xml);
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            var stopwatch                 = Stopwatch.StartNew();
            var projectAssembly           = "EventHorizon.Blazor.BabylonJS.WASM";
            var projectGenerationLocation = Path.Combine(
                "..",
                "_generated"
                );

            var sourceDirectory = Path.Combine(
                ".",
                "SourceFiles"
                );
            var textFormatter = new NoFormattingTextFormatter();
            var writer        = new ProjectWriter(
                projectGenerationLocation,
                projectAssembly
                );
            var sourceFiles = new List <string>
            {
                "babylon.d.ts",
                "babylon.gui.d.ts",
            };
            var generationList = new List <string>
            {
                "Scene",
                "VertexBuffer",
                "ICameraInput",
                "AbstractActionManager",
                "ICustomAnimationFrameRequester",
                "IAction",
                "Vector3",
                "EventState",
                "Observable",
                "Container",
                "Control",
                "Button",
                "UniversalCamera",
                "ArcRotateCamera",
                "PointLight",
                "Grid",
                "StackPanel",
                "MeshBuilder",
                "StandardMaterial",
                "Texture",
                "HemisphericLight",
                "PointerInfo",
                "PointerInfoBase",
                "SceneLoader",
            };

            // Remove any already Generated Source.
            if (Directory.Exists(Path.Combine(
                                     projectGenerationLocation,
                                     projectAssembly
                                     )))
            {
                Directory.Delete(
                    Path.Combine(
                        projectGenerationLocation,
                        projectAssembly
                        ),
                    true
                    );
            }
            GlobalLogger.Info("Removed Generation Directory");

            new GenerateInteropSource().Run(
                projectAssembly,
                sourceDirectory,
                sourceFiles,
                generationList,
                writer,
                textFormatter,
                new Dictionary <string, string>
            {
                { "BABYLON.PointerInfoBase | type", "int" }
            }
                );
            stopwatch.Stop();
            GlobalLogger.Info("Removed Generation Directory");
            GlobalLogger.Info($"Took {stopwatch.ElapsedMilliseconds}ms to generate.");
        }
Beispiel #15
0
        public void process(string filename)
        {
            //
            // Create a ProjectFile instance
            //
            ProjectFile file = new ProjectFile();

            //
            // Uncomment these lines to test the use of alternative
            // delimiters and separators for MPX file output.
            //
            //file.setDelimiter(';');
            //file.setDecimalSeparator(',');
            //file.setThousandsSeparator('.');

            //
            // Add a default calendar called "Standard"
            //
            ProjectCalendar calendar = file.addDefaultBaseCalendar();

            //
            // Add a holiday to the calendar to demonstrate calendar exceptions
            //
            calendar.addCalendarException(ParseDate("2006-03-13"), ParseDate("2006-03-13"));

            //
            // Retrieve the project properties and set the start date. Note Microsoft
            // Project appears to reset all task dates relative to this date, so this
            // date must match the start date of the earliest task for you to see
            // the expected results. If this value is not set, it will default to
            // today's date.
            //
            ProjectProperties properties = file.ProjectProperties;

            properties.StartDate = ParseDate("2003-01-01");

            //
            // Set a couple more properties just for fun
            //
            properties.ProjectTitle = "Created by MPXJ";
            properties.Author       = "Jon Iles";

            //
            // Add resources
            //
            Resource resource1 = file.addResource();

            resource1.Name = "Resource1";

            Resource resource2 = file.addResource();

            resource2.Name = "Resource2";

            //
            // This next line is not required, it is here simply to test the
            // output file format when alternative separators and delimiters
            // are used.
            //
            resource2.MaxUnits = NumberHelper.getDouble(50.0);

            //
            // Create a summary task
            //
            Task task1 = file.addTask();

            task1.Name = "Summary Task";

            //
            // Create the first sub task
            //
            Task task2 = task1.addTask();

            task2.Name     = "First Sub Task";
            task2.Duration = Duration.getInstance(10.5, TimeUnit.DAYS);
            task2.Start    = ParseDate("2003-01-01");

            //
            // We'll set this task up as being 50% complete. If we have no resource
            // assignments for this task, this is enough information for MS Project.
            // If we do have resource assignments, the assignment record needs to
            // contain the corresponding work and actual work fields set to the
            // correct values in order for MS project to mark the task as complete
            // or partially complete.
            //
            task2.PercentageComplete = NumberHelper.getDouble(50.0);
            task2.ActualStart        = ParseDate("2003-01-01");

            //
            // Create the second sub task
            //
            Task task3 = task1.addTask();

            task3.Name     = "Second Sub Task";
            task3.Start    = ParseDate("2003-01-11");
            task3.Duration = Duration.getInstance(10, TimeUnit.DAYS);

            //
            // Link these two tasks
            //
            task3.addPredecessor(task2, RelationType.FINISH_START, null);

            //
            // Add a milestone
            //
            Task milestone1 = task1.addTask();

            milestone1.Name     = "Milestone";
            milestone1.Start    = ParseDate("2003-01-21");
            milestone1.Duration = Duration.getInstance(0, TimeUnit.DAYS);
            milestone1.addPredecessor(task3, RelationType.FINISH_START, null);

            //
            // This final task has a percent complete value, but no
            // resource assignments. This is an interesting case it it requires
            // special processing to generate the MSPDI file correctly.
            //
            Task task4 = file.addTask();

            task4.Name               = "Next Task";
            task4.Duration           = Duration.getInstance(8, TimeUnit.DAYS);
            task4.Start              = ParseDate("2003-01-01");
            task4.PercentageComplete = NumberHelper.getDouble(70.0);
            task4.ActualStart        = ParseDate("2003-01-01");

            //
            // Assign resources to tasks
            //
            ResourceAssignment assignment1 = task2.addResourceAssignment(resource1);
            ResourceAssignment assignment2 = task3.addResourceAssignment(resource2);

            //
            // As the first task is partially complete, and we are adding
            // a resource assignment, we must set the work and actual work
            // fields in the assignment to appropriate values, or MS Project
            // won't recognise the task as being complete or partially complete
            //
            assignment1.Work       = Duration.getInstance(80, TimeUnit.HOURS);
            assignment1.ActualWork = Duration.getInstance(40, TimeUnit.HOURS);

            //
            // If we were just generating an MPX file, we would already have enough
            // attributes set to create the file correctly. If we want to generate
            // an MSPDI file, we must also set the assignment start dates and
            // the remaining work attribute. The assignment start dates will normally
            // be the same as the task start dates.
            //
            assignment1.RemainingWork = Duration.getInstance(40, TimeUnit.HOURS);
            assignment2.RemainingWork = Duration.getInstance(80, TimeUnit.HOURS);
            assignment1.Start         = ParseDate("2003-01-01");
            assignment2.Start         = ParseDate("2003-01-11");

            //
            // Write a 100% complete task
            //
            Task task5 = file.addTask();

            task5.Name               = "Last Task";
            task5.Duration           = Duration.getInstance(3, TimeUnit.DAYS);
            task5.Start              = ParseDate("2003-01-01");
            task5.PercentageComplete = NumberHelper.getDouble(100.0);
            task5.ActualStart        = ParseDate("2003-01-01");

            //
            // Write the file
            //
            ProjectWriter writer = ProjectWriterUtility.getProjectWriter(filename);

            writer.write(file, filename);
        }
Beispiel #16
0
        /// <summary>
        /// Ports a list of projects
        /// </summary>
        /// <param name="projectPaths">List of projects paths</param>
        /// <param name="solutionPath">Path to solution file</param>
        /// <param name="targetFramework">Target framework to be used when porting</param>
        /// <param name="upgradeVersions">List of key/value pairs where key is package and value is version number</param>
        /// <returns>A PortingProjectFileResult object, representing the result of the porting operation</returns>
        public List <PortingResult> ApplyProjectChanges(
            List <string> projectPaths, string solutionPath, string targetFramework,
            Dictionary <string, string> upgradeVersions)
        {
            _logger.LogInformation("Applying porting changes to {0}", projectPaths);

            var results = new List <PortingResult>();
            var projectFilesNotFound = projectPaths.Where((path) => !File.Exists(path)).ToList();

            projectFilesNotFound.ForEach((path) => results.Add(new PortingResult
            {
                Message     = "File not found.",
                ProjectFile = path,
                ProjectName = Path.GetFileNameWithoutExtension(path),
                Success     = false
            }));

            var conversionOptions = new ConversionOptions
            {
                ForceOnUnsupportedProjects = true,
                ProjectCache     = new DefaultProjectCache(),
                TargetFrameworks = new List <string> {
                    targetFramework
                },
            };

            var(projects, _) = _facility.ParseProjects(new[] { solutionPath }, Vs16TransformationSet.Instance, conversionOptions);

            var selectedProjects = projects.Where(project => projectPaths.Contains(project.FilePath.FullName)).ToList();

            var writer = new ProjectWriter(_logger, writeOptions);

            foreach (var project in selectedProjects)
            {
                try
                {
                    project.PackageReferences = project.PackageReferences.Select(p =>
                                                                                 new PackageReference
                    {
                        Id      = p.Id,
                        Version = upgradeVersions.ContainsKey(p.Id) ? upgradeVersions[p.Id] : p.Version,
                        IsDevelopmentDependency = p.IsDevelopmentDependency,
                        DefinitionElement       = p.DefinitionElement
                    }).ToList();

                    if (writer.TryWrite(project))
                    {
                        results.Add(new PortingResult
                        {
                            Success     = true,
                            ProjectFile = project.FilePath.FullName,
                            ProjectName = project.ProjectName
                        });
                    }
                    else
                    {
                        results.Add(new PortingResult
                        {
                            Success     = false,
                            ProjectFile = project.FilePath.FullName,
                            ProjectName = project.ProjectName
                        });
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Project {Item} analysis has thrown an exception",
                                     project.ProjectName);

                    results.Add(new PortingResult
                    {
                        Success     = false,
                        ProjectFile = project.FilePath.FullName,
                        ProjectName = project.ProjectName,
                        Exception   = ex
                    });
                }
            }

            conversionOptions.ProjectCache?.Purge();

            _logger.LogInformation("Completed porting changes to {0}", projectPaths);

            return(results);
        }
        public void Save(string fileName)
        {
            // StringWriter.Encoding always returns UTF16. We need it to return UTF8, so the
            // XmlDocument will write the UTF8 header.

            if (!this.Settings.MaintainOriginalItemOrder)
            {
                ItemGroups.Each(group =>
                {
                    XmlElement[] elements = null;
                    elements = @group.Items.Select(x => x.Element).OrderBy(x => x.GetAttribute("Include")).ToArray();

                    group.Element.RemoveAll();

                    elements.Each(x => group.Element.AppendChild(x));

                });
            }

            var sw = new ProjectWriter(bom);
            sw.NewLine = newLine;
            doc.Save(sw);

            string content = sw.ToString();
            if (endsWithEmptyLine && !content.EndsWith(newLine))
                content += newLine;

            var shouldSave = !this.Settings.OnlySaveIfChanged ||
                             (File.Exists(fileName) && !File.ReadAllText(fileName).Equals(content));

            if (shouldSave)
                new FileSystem().WriteStringToFile(fileName, content);
        }
Beispiel #18
0
        public int Compile()
        {
            try
            {
                Console.Write("Loading project file... ");
                using (FileStream projectStream = new FileStream(ProjectFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))

                    // meh. yes, that many streams.
                    using (MemoryStream gamedataBase = new MemoryStream())
                        using (ProjectWriter gamedataStream = new ProjectWriter(gamedataBase))
                            using (MemoryStream gmkryptBase = new MemoryStream())
                                using (ProjectWriter gmkryptStream = new ProjectWriter(gmkryptBase))
                                {
                                    Project = new GMProject(projectStream);

                                    Console.WriteLine("Done");

                                    // Just like the Editor does.
                                    if (Project.Rooms.Count <= 0)
                                    {
                                        throw new Exception("A game must have at least one room in order to run you dummy :)");
                                    }

                                    Console.Write("Unpacking rundata... ");
                                    RundataManager.LoadRundata(Project.Version, OutputExecutablePath);
                                    Console.WriteLine("Done");

                                    ExeResInfo eri = new ExeResInfo(
                                        Project.Options.GameVersion,
                                        Project.Options.Company,
                                        Project.Options.Product,
                                        Project.Options.Copyright,
                                        Project.Options.Description,
                                        Project.Options.RawIcon
                                        );

                                    Console.Write("Setting exe information... ");
                                    ExeResource.SetExeResourceInfo(OutputExecutablePath, eri);
                                    Console.WriteLine("Done");

                                    Console.Write("Writing game data... ");
                                    gamedataStream.Write(GMProject.GMMagic);
                                    gamedataStream.Write(Project.Version);

                                    // dummy value 1
                                    if (Project.Version == 810)
                                    {
                                        gamedataStream.Write(1337);
                                    }

                                    // the debug mode flag, not encrypted...
                                    gamedataStream.Write(EnableDebugMode);

                                    // dummy value 2
                                    if (Project.Version == 810)
                                    {
                                        gamedataStream.Write(6969);
                                    }

                                    // options (not encrypted)
                                    Options.WriteOptions(gamedataStream, Project.Options);

                                    // embedded direct3d 8.0 dll
                                    gamedataStream.Write("D3DX8.dll");
                                    gamedataStream.Write(File.ReadAllBytes(Path.Combine(AppDir, "dxdata")));

                                    // actual crypto fun starts.
                                    gamedataStream.Write(0); // count1
                                    gamedataStream.Write(0); // count2
                                    // GMKrypt table, or in this case, a dummy table :p
                                    for (int i = 0; i <= byte.MaxValue; i++)
                                    {
                                        gamedataStream.Write((byte)i);
                                    }

                                    // dummy ints...
                                    gmkryptStream.Write(0); // count3

                                    // header
                                    gmkryptStream.Write(EnableProMode);
                                    gmkryptStream.Write(Project.GameID);
                                    gmkryptStream.Write(Project.DirectPlayGuid);

                                    // extensions
                                    Asset.WriteExtensions(gmkryptStream, Project.ExtensionPackageNames, GEXSearchPath);

                                    // triggers
                                    Asset.WriteAsset(gmkryptStream, Project.Triggers, AssetDelegates.Trigger);

                                    // constants
                                    Asset.WriteConstants(gmkryptStream, Project.Constants);

                                    // sounds
                                    Asset.WriteAsset(gmkryptStream, Project.Sounds, AssetDelegates.Sound);

                                    // sprites
                                    Asset.WriteAsset(gmkryptStream, Project.Sprites, AssetDelegates.Sprite);

                                    // backgrounds
                                    Asset.WriteAsset(gmkryptStream, Project.Backgrounds, AssetDelegates.Background);

                                    // paths
                                    Asset.WriteAsset(gmkryptStream, Project.Paths, AssetDelegates.Path);

                                    // scripts
                                    Asset.WriteAsset(gmkryptStream, Project.Scripts, AssetDelegates.Script);

                                    // fonts
                                    Asset.WriteAsset(gmkryptStream, Project.Fonts, AssetDelegates.Font);

                                    // timelines
                                    Asset.WriteAsset(gmkryptStream, Project.Timelines, AssetDelegates.Timeline, Project);

                                    // objects
                                    Asset.WriteAsset(gmkryptStream, Project.Objects, AssetDelegates.Object, Project);

                                    // rooms
                                    Asset.WriteAsset(gmkryptStream, Project.Rooms, AssetDelegates.Room, Project);
                                    Asset.WriteMaxRoomIDs(gmkryptStream, Project.LastInstanceID, Project.LastTileID);

                                    // included files
                                    Asset.WriteAsset(gmkryptStream, Project.IncludedFiles, AssetDelegates.IncludedFile);

                                    // game information
                                    Asset.WriteGameInformation(gmkryptStream, Project.GameInformation);

                                    // library creation code
                                    Asset.WriteLibCC(gmkryptStream, Project.LibraryCreationCode);

                                    // room execution order
                                    Asset.WriteRoomExecOrder(gmkryptStream, Project.RoomExecutionOrder, Project);

                                    // encryption
                                    byte[] gmkryptData = Encryption.EncryptGM8(gmkryptBase);
                                    gamedataStream.Write(gmkryptData.Length);
                                    gamedataStream.Write(gmkryptData);

                                    // encryption crc/xor (810 only)
                                    if (Project.Version == 810)
                                    {
                                        // TODO: implement the thing.
                                        Encryption.EncryptGM81(gamedataBase);
                                    }

                                    // finalization (rundata, icon, version, etc)
                                    Console.WriteLine("Done");

                                    // Write rundata.
                                    Console.Write("Appending game data to rundata... ");
                                    FileStream rundata     = new FileStream(OutputExecutablePath, FileMode.Append, FileAccess.Write, FileShare.Read);
                                    byte[]     dataToWrite = gamedataBase.ToArray();

                                    // GM8.1 STARTS AT A DIFFERENT POSITION, NEED TO CHANGE.
                                    // Technically 2000000 should always be beyond rundata, but if you set a very large icon
                                    // this position may be inside rundata, luckily GameMaker will also add 10000
                                    // in a loop to the seek position until it finds the game data.
                                    long pos = 2000000;
                                    while (pos <= rundata.Length)
                                    {
                                        pos += 10000;
                                    }
                                    rundata.Seek(pos, SeekOrigin.Begin);

                                    // Write gamedata to rundata.
                                    rundata.Write(dataToWrite);

                                    // Flush and close the stream safely.
                                    rundata.Flush(true);
                                    rundata.Dispose();

                                    // yay!!!
                                    Console.WriteLine("Done");
                                }

                if (RunAfterBuild)
                {
                    try
                    {
                        Console.Write("Trying to run the game... ");
                        Process game;
                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            game = Process.Start(OutputExecutablePath);
                        }
                        else
                        {
                            game = Process.Start("wine", OutputExecutablePath);
                        }

                        if (game == null)
                        {
                            throw new Exception("No game process was started.");
                        }
                        game.Dispose();

                        Console.WriteLine("Done");
                    }
                    catch
                    {
                        Console.WriteLine("Warning: Unable to run the game process!");
                    }
                }

                Console.WriteLine("All Done!");
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.WriteLine("-- BUILD FAILURE, EXCEPTION BEGIN --");
                Console.WriteLine(e.ToString());
                Console.WriteLine("-- EXCEPTION END --");
                Console.WriteLine();
                return(Program.EXIT_FAILURE);
            }

            return(Program.EXIT_SUCCESS);
        }
		string SaveToString (WriteContext ctx)
		{
			// StringWriter.Encoding always returns UTF16. We need it to return UTF8, so the
			// XmlDocument will write the UTF8 header.
			ProjectWriter sw = new ProjectWriter (format.ByteOrderMark);
			sw.NewLine = format.NewLine;
			var xw = XmlWriter.Create (sw, new XmlWriterSettings {
				OmitXmlDeclaration = !hadXmlDeclaration,
				NewLineChars = format.NewLine,
				NewLineHandling = NewLineHandling.Replace
			});

			MSBuildWhitespace.Write (initialWhitespace, xw);

			Save (xw);

			xw.Dispose ();

			return sw.ToString ();
		}
 public void CanRemoveNonExistingFileFromProject()
 {
     var project = CsProjects.SampleProjectSimple;
     var writer = new ProjectWriter(project);
     writer.RemoveFile(@"asd.qwe/asd.txt");
     var newProject = writer.GetXml();
 }
Beispiel #21
0
        public void Save(string fileName)
        {
            // StringWriter.Encoding always returns UTF16. We need it to return UTF8, so the
            // XmlDocument will write the UTF8 header.

            ItemGroups.Each(group => {
                var elements = group.Items.Select(x => x.Element).OrderBy(x => x.GetAttribute("Include")).ToArray();
                group.Element.RemoveAll();

                elements.Each(x => group.Element.AppendChild(x));

            });

            var sw = new ProjectWriter(bom);
            sw.NewLine = newLine;
            doc.Save(sw);

            string content = sw.ToString();
            if (endsWithEmptyLine && !content.EndsWith(newLine))
                content += newLine;

            new FileSystem().WriteStringToFile(fileName, content);
        }
Beispiel #22
0
		public void Save (string fileName)
		{
			// StringWriter.Encoding always returns UTF16. We need it to return UTF8, so the
			// XmlDocument will write the UTF8 header.
			ProjectWriter sw = new ProjectWriter (bom);
			sw.NewLine = newLine;
			doc.Save (sw);

			string content = sw.ToString ();
			if (endsWithEmptyLine && !content.EndsWith (newLine))
				content += newLine;

			TextFile.WriteFile (fileName, content, bom, true);
		}
Beispiel #23
0
 public void Save(ProjectWriter writer)
 {
     writer.Write(Name);
     writer.Write(Value);
 }
Beispiel #24
0
 private void Save_Header(ProjectWriter writer)
 {
     writer.Write(GameID);
     writer.Write(DirectPlayGuid);
 }
Beispiel #25
0
        private ProjectWriter CreateProjectWriter(string @namespace, ProjectVersion projectVersion)
        {
            var pw = new ProjectWriter(@namespace, projectVersion);

            return(pw);
        }
Beispiel #26
0
 private void Save_LastIDs(ProjectWriter writer)
 {
     writer.Write(LastInstanceID);
     writer.Write(LastTileID);
 }
Beispiel #27
0
        public void Write(ProjectWriter writer)
        {
            writer.Write(StartInFullscreen);
            writer.Write(InterpolatePixels);
            writer.Write(DontDrawBorder);
            writer.Write(DisplayCursor);
            writer.Write(Scaling);
            writer.Write(AllowWindowResize);
            writer.Write(AlwaysOnTop);
            writer.Write(OutsideRoom);
            writer.Write(SetResolution);
            writer.Write((int)ColorDepth);
            writer.Write((int)ScreenResolution);
            writer.Write((int)Frequency);
            writer.Write(Borderless);
            uint vsync = VSync ? 1U : 0U;

            if (SoftwareVertex)
            {
                vsync |= 0x80000000;
            }
            writer.Write(vsync);
            writer.Write(DisableScreensavers);
            writer.Write(LetF4Fullscreen);
            writer.Write(LetF1GameInfo);
            writer.Write(LetESCEndGame);
            writer.Write(LetF5F6SaveLoad);
            writer.Write(LetF9Screenshot);
            writer.Write(TreatCloseAsESC);
            writer.Write((int)Priority);
            writer.Write(FreezeWhenFocusLost);
            writer.Write((int)LoadingBarMode);
            if (LoadingBarMode == ProgBars.BAR_CUSTOM)
            {
                if (BackLoadingBar != null)
                {
                    writer.Write(1);
                    writer.Write(BackLoadingBar);
                }
                else
                {
                    writer.Write(0);
                }

                if (FrontLoadingBar != null)
                {
                    writer.Write(1);
                    writer.Write(FrontLoadingBar);
                }
                else
                {
                    writer.Write(0);
                }
            }
            writer.Write(ShowCustomLoadImage);
            if (ShowCustomLoadImage)
            {
                if (LoadingImage != null)
                {
                    writer.Write(1);
                    writer.Write(LoadingImage);
                }
                else
                {
                    writer.Write(0);
                }
            }
            writer.Write(LoadimgImagePartTransparent);
            writer.Write(LoadImageAlpha);
            writer.Write(ScaleProgressBar);
            writer.Write(GameIcon);
            writer.Write(DisplayErrors);
            writer.Write(WriteToLog);
            writer.Write(AbortOnAllErrors);
            writer.Write(TreatUninitAsZero);

            writer.Write(Author);
            writer.Write(Version);
            writer.Write(LastChanged);
            writer.Write(Information);
            writer.Write(GameVersion);
            writer.Write(Company);
            writer.Write(Product);
            writer.Write(Copyright);
            writer.Write(Description);
            writer.Write(OptionsLastChanged);
        }
Beispiel #28
0
		public string SaveToString ()
		{
			// StringWriter.Encoding always returns UTF16. We need it to return UTF8, so the
			// XmlDocument will write the UTF8 header.
			ProjectWriter sw = new ProjectWriter (bom);
			sw.NewLine = newLine;
			doc.Save (sw);

			string content = sw.ToString ();
			if (endsWithEmptyLine && !content.EndsWith (newLine))
				content += newLine;

			return content;
		}
Beispiel #29
0
        private static int GenerateSources(
            IList <string> source,
            IList <string> classToGenerate,
            string projectAssembly           = "Generated.WASM",
            string projectGenerationLocation = "_generated",
            bool force = false
            )
        {
            try
            {
                var stopwatch = Stopwatch.StartNew();
                ValidateArguments(
                    source,
                    classToGenerate,
                    projectAssembly,
                    projectGenerationLocation
                    );
                GlobalLogger.Info($"projectAssembly: {projectAssembly}");
                GlobalLogger.Info($"projectGenerationLocation: {projectGenerationLocation}");

                GlobalLogger.Info($"classToGenerate.Length: {classToGenerate.Count}");
                foreach (var classToGenerateItem in classToGenerate)
                {
                    GlobalLogger.Info($"classToGenerateItem: {classToGenerateItem}");
                }

                GlobalLogger.Info($"sourceFile.Length: {source.Count}");
                foreach (var sourceFileItem in source)
                {
                    GlobalLogger.Info($"sourceFile: {sourceFileItem}");
                }

                projectGenerationLocation = Path.Combine(
                    ".",
                    projectGenerationLocation
                    );

                var sourceDirectory = Path.Combine(
                    ".",
                    SOURCE_FILES_DIRECTORY_NAME
                    );
                var sourceFiles = CopyAndDownloadSourceFiles(
                    source
                    );
                var generationList = classToGenerate;

                // Check for already Generated Source.
                var projectAssemblyDirectory = Path.Combine(
                    projectGenerationLocation,
                    projectAssembly
                    );
                if (Directory.Exists(
                        projectAssemblyDirectory
                        ))
                {
                    if (!force)
                    {
                        GlobalLogger.Error(
                            $"Project Assembly Directory was not empty: {projectAssemblyDirectory}"
                            );
                        GlobalLogger.Error(
                            $"Use --force to replace directory."
                            );
                        return(502);
                    }

                    GlobalLogger.Warning(
                        $"Deleting existing projectAssemblyDirectory: {projectAssemblyDirectory}"
                        );
                    Directory.Delete(
                        projectAssemblyDirectory,
                        true
                        );
                }

                var textFormatter = new NoFormattingTextFormatter();
                var writer        = new ProjectWriter(
                    projectGenerationLocation,
                    projectAssembly
                    );

                new GenerateSource().Run(
                    projectAssembly,
                    sourceDirectory,
                    sourceFiles,
                    generationList,
                    writer,
                    textFormatter,
                    new Dictionary <string, string>
                {
                    { "BABYLON.PointerInfoBase | type", "int" }
                }
                    );
                stopwatch.Stop();
                GlobalLogger.Success($"Took {stopwatch.ElapsedMilliseconds}ms to Generate Source Project.");

                return(0);
            }
            catch (ArgumentException ex)
            {
                GlobalLogger.Error(
                    $"Argument failure: {ex.ParamName} -> {ex.Message}"
                    );
                return(404);
            }
            catch (InvalidSourceFileException ex)
            {
                GlobalLogger.Error(
                    $"Invalid Source File Exception: {ex.Message}"
                    );
                return(501);
            }
        }