Example #1
0
        internal static IEnumerable <string> GetCSharpFilesFromProject(string csProjFolderPath)
        {
            var csProjFilePath = Directory.EnumerateFiles(csProjFolderPath, "*.csproj", SearchOption.TopDirectoryOnly).SingleOrDefault();

            if (csProjFilePath is null)
            {
                throw new FileNotFoundException();
            }

            var fileSystem  = new Cake.Core.IO.FileSystem();
            var platform    = new CakePlatform();
            var runtime     = new CakeRuntime();
            var cakeConsole = new CakeConsole();
            var cakeLog     = new CakeBuildLog(cakeConsole, Verbosity.Diagnostic);
            var environment = new CakeEnvironment(platform, runtime, cakeLog);

            var projectPath = new Cake.Core.IO.FilePath(csProjFilePath);

            if (projectPath.IsRelative)
            {
                projectPath = projectPath.MakeAbsolute(environment);
            }
            var projectFile = fileSystem.GetFile(projectPath);
            var parseResult = projectFile.ParseProjectFile("Debug");

            // TODO: do not assume all .cs files are included by default?
            // TODO: do not return .cs files that are removed from Compile in the .csproj
            foreach (var sourceFile in GetCSharpFilesFromFolder(csProjFolderPath))
            {
                yield return(sourceFile);
            }

            // TODO: if a project or package is encountered multiple times through recursion, ensure it only gets evaluated once (use HashSet?)
            // TODO: handle the case where a library is referenced as both a projectReference and a packageReference (NuGet gives error when this happens)

            foreach (var projectReference in parseResult.ProjectReferences)
            {
                // TODO: test that this works correctly
                foreach (var sourceFile in GetCSharpFilesFromProject(projectReference.FilePath.FullPath))
                {
                    yield return(sourceFile);
                }
            }

            // Assume package reference is either a .Sources package, or it's not and has no .cs files packed.
            foreach (var packageReference in parseResult.PackageReferences)
            {
                // TODO: try to get source files from package's dependencies (recursively)
                foreach (var sourceFile in DiscoverPackageReferenceSourceFiles(packageReference.Name, packageReference.Version))
                {
                    yield return(sourceFile);
                }
            }
        }
Example #2
0
        internal ProjectReference(Cake.Core.IO.FilePath path, string workingDirectory, string targetFramework, string configuration, string platform = "AnyCPU")
        {
            if (path.IsRelative)
            {
                _environment.WorkingDirectory = workingDirectory;
                path = path.MakeAbsolute(_environment);
            }

            _project = _fileSystem.GetFile(path).ParseProjectFile(_configuration = configuration, _platform = platform);
            _folder  = _project.ProjectFilePath.GetDirectory().FullPath;

            _target = targetFramework ?? _project.TargetFrameworkVersions.Single();
        }
Example #3
0
        /// <summary>
        ///Loads the project file and finds the last item group in its contents
        ///Then checks each file in the array for an existing entry in the project file
        ///Assuming a matched file name
        ///If the entry exists in the project file but not on disk the reference is removed
        ///a new entry is added to the item group
        /// </summary>
        /// <param name="files">String array of file paths to add</param>
        /// <param name="projectFilePath">String path to VS project file to modify</param>
        /// <returns>Nothing.</returns>
        public static void AddFilesToProjectAsEmbeddedResources(string[] files, string projectFilePath)
        {
            var ProjectFile = XDocument.Load(projectFilePath);

            var itemGroup = GetLastItemGroup(ProjectFile);

            foreach (var file in files)
            {
                //Make a path relative from the file specified.
                var relativePath = new Cake.Core.IO.FilePath(System.IO.Path.GetFullPath(projectFilePath))
                                   .GetRelativePath(new Core.IO.FilePath(System.IO.Path.GetFullPath(file)))
                                   .ToString().Replace('/', Path.DirectorySeparatorChar);

                if (!EmbeddedResourceExists(relativePath, ProjectFile))
                {
                    var xelem = AddEmbeddedResource(relativePath, ProjectFile);
                    itemGroup.Add(xelem);
                }
            }
            ProjectFile.Save(projectFilePath);
        }
Example #4
0
        /// <inheritdoc/>
        public override void Run(BuildContext context)
        {
            string version = $"{context.MajorVersion}.{context.MinorVersion}.{context.GetBuildRevisionVersion()}";

            if (context.IsDevelop)
            {
                version += $"-beta";
            }

            string solutionPath = Path.GetFullPath(BuildContext.OPENDDSHARP_SOLUTION_FOLDER);
            string path         = Path.Combine(solutionPath, "Sources", "OpenDDSharp.Standard", "OpenDDSharp.Standard.csproj");

            context.DotNetPack(path, new DotNetPackSettings
            {
                Configuration         = "Release",
                NoBuild               = true,
                ArgumentCustomization = args => args.Append($"/p:Version={version}"),
                OutputDirectory       = ".",
            });

            path = Path.Combine(solutionPath, "Sources", "OpenDDSharp.Templates", "OpenDDSharp.Templates.csproj");
            context.DotNetPack(path, new DotNetPackSettings
            {
                Configuration         = "Release",
                NoBuild               = true,
                ArgumentCustomization = args => args.Append($"/p:Version={version}"),
                OutputDirectory       = ".",
            });

            path = Path.Combine(solutionPath, "Sources", "OpenDDSharp.Native", "OpenDDSharp.Native.csproj");
            context.DotNetPack(path, new DotNetPackSettings
            {
                Configuration         = "Release",
                NoBuild               = true,
                ArgumentCustomization = args => args.Append($"/p:Version={version}"),
                OutputDirectory       = ".",
            });

            path = Path.Combine(solutionPath, "Native", "OpenDDSharp.Standard.IdlGenerator.nuspec");
            var filePath = new Cake.Core.IO.FilePath(path);

            context.NuGetPack(filePath, new NuGetPackSettings
            {
                Verbosity = NuGetVerbosity.Detailed,
            });

            string releaseFolder = Path.Combine(solutionPath, "Release");

            if (!Directory.Exists(releaseFolder))
            {
                Directory.CreateDirectory(releaseFolder);
            }

            foreach (var file in Directory.GetFiles(releaseFolder, "*.nupkg"))
            {
                File.Delete(file);
            }

            foreach (var file in Directory.GetFiles(".", "*.nupkg"))
            {
                FileInfo fi = new FileInfo(file);
                File.Move(file, Path.Combine(releaseFolder, fi.Name));
            }
        }
Example #5
0
 public static void AddEmbeddedResources(this ICakeContext context, Cake.Core.IO.FilePathCollection files, Cake.Core.IO.FilePath projectFile)
 {
     AddFilesToProjectAsEmbeddedResources(files.Select(f => f.FullPath).ToArray(), projectFile.FullPath.ToString());
 }
Example #6
0
        public static void EditAssemblyInfo(this ICakeContext context, Cake.Core.IO.FilePath assemblyInfoPath)
        {
            var assemblyInfoManager = new AssemblyInfoManager(context.FileSystem, context.Environment);

            assemblyInfoManager.EditAssemblyInfo(assemblyInfoPath);
        }
Example #7
0
        public static void SharePointUploadFile(this ICakeContext cakecontext, Cake.Core.IO.FilePath filename, string destinationfoldername, SharePointSettings sharepointdetails)
        {
            // Get the name of the file.
            string uniqueFileName = Path.GetFileName(filename.FullPath);
            // Get the size of the file.
            long fileSize = new FileInfo(filename.FullPath).Length;

            cakecontext?.Log.Write(Verbosity.Normal, LogLevel.Debug, $"Uploading file '{uniqueFileName}' ({(fileSize / 1048576):F} MB) to SharePoint ({destinationfoldername})");

            using (var authenticationManager = new AuthenticationManager())
            {
                using (var clientcontext = authenticationManager.GetContext(cakecontext, sharepointdetails))
                {
                    var rootfolder = GetRootFolder(sharepointdetails, clientcontext);

                    //upload file
                    var sw = new Stopwatch();
                    sw.Start();
                    // Each sliced upload requires a unique ID.
                    Guid uploadId = Guid.NewGuid();
                    // Get the folder to upload into.



                    var targetFolder = GetRemoteFolder(clientcontext, destinationfoldername, rootfolder);

                    // File object.
                    Microsoft.SharePoint.Client.File uploadFile;

                    // Calculate block size in bytes.
                    int blockSize = sharepointdetails.fileChunkSizeInMB * 1024 * 1024;

                    if (fileSize <= blockSize)
                    {
                        // Use regular approach.
                        using (FileStream fs = new FileStream(filename.FullPath, FileMode.Open))
                        {
                            FileCreationInformation fileInfo = new FileCreationInformation();
                            fileInfo.ContentStream = fs;
                            fileInfo.Url           = uniqueFileName;
                            fileInfo.Overwrite     = true;
                            uploadFile             = targetFolder.Files.Add(fileInfo);
                            clientcontext.Load(uploadFile);
                            clientcontext.ExecuteQueryAsync().Wait();
                            sw.Stop();
                            cakecontext?.Log.Write(Verbosity.Normal, LogLevel.Debug, $"{DateTime.Now.ToShortTimeString()}: Upload of file '{uniqueFileName}' ({(fileSize / 1048576):F} MB) Finished! ({((fileSize / sw.Elapsed.TotalSeconds) / 1048576):F} MBytes/s)");
                            cakecontext?.Log.Write(Verbosity.Normal, LogLevel.Debug, $"Upload took {sw.Elapsed} to complete");
                            return;
                        }
                    }
                    else
                    {
                        // Use large file upload approach.
                        ClientResult <long> bytesUploaded = null;

                        FileStream fs = null;
                        try
                        {
                            fs = System.IO.File.Open(filename.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                            using (BinaryReader br = new BinaryReader(fs))
                            {
                                byte[] buffer         = new byte[blockSize];
                                Byte[] lastBuffer     = null;
                                long   fileoffset     = 0;
                                long   totalBytesRead = 0;
                                int    bytesRead;
                                bool   first = true;
                                bool   last  = false;

                                // Read data from file system in blocks.
                                while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    totalBytesRead = totalBytesRead + bytesRead;

                                    // You've reached the end of the file.
                                    if (totalBytesRead == fileSize)
                                    {
                                        last = true;
                                        // Copy to a new buffer that has the correct size.
                                        lastBuffer = new byte[bytesRead];
                                        Array.Copy(buffer, 0, lastBuffer, 0, bytesRead);
                                    }
                                    cakecontext?.Log.Write(Verbosity.Normal, LogLevel.Debug, $"Upload @ {Math.Round(((double)totalBytesRead / (double)fileSize) * 100)}% : {(totalBytesRead / 1048576):F}/{(fileSize / 1048576):F} MBytes ({((totalBytesRead / sw.Elapsed.TotalSeconds) / 1048576):F} MBytes/s)");

                                    if (first)
                                    {
                                        using (MemoryStream contentStream = new MemoryStream())
                                        {
                                            // Add an empty file.
                                            FileCreationInformation fileInfo = new FileCreationInformation();
                                            fileInfo.ContentStream = contentStream;
                                            fileInfo.Url           = uniqueFileName;
                                            fileInfo.Overwrite     = true;
                                            uploadFile             = targetFolder.Files.Add(fileInfo);

                                            // Start upload by uploading the first slice.
                                            using (MemoryStream s = new MemoryStream(buffer))
                                            {
                                                // Call the start upload method on the first slice.
                                                bytesUploaded = uploadFile.StartUpload(uploadId, s);
                                                clientcontext.ExecuteQueryAsync().Wait();
                                                // fileoffset is the pointer where the next slice will be added.
                                                fileoffset = bytesUploaded.Value;
                                            }

                                            // You can only start the upload once.
                                            first = false;
                                        }
                                    }
                                    else
                                    {
                                        // Get a reference to your file.
                                        uploadFile = clientcontext.Web.GetFileByServerRelativeUrl(targetFolder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + uniqueFileName);

                                        if (last)
                                        {
                                            // Is this the last slice of data?
                                            using (MemoryStream s = new MemoryStream(lastBuffer))
                                            {
                                                // End sliced upload by calling FinishUpload.
                                                uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s);
                                                clientcontext.ExecuteQueryAsync().Wait();
                                                return;
                                            }
                                        }
                                        else
                                        {
                                            using (MemoryStream s = new MemoryStream(buffer))
                                            {
                                                // Continue sliced upload.
                                                bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s);
                                                clientcontext.ExecuteQueryAsync().Wait();
                                                // Update fileoffset for the next slice.
                                                fileoffset = bytesUploaded.Value;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
                            sw.Stop();
                            cakecontext?.Log.Write(Verbosity.Normal, LogLevel.Debug, $"Upload of file '{uniqueFileName}' ({(fileSize / 1048576):F} MB) Finished! ({((fileSize / sw.Elapsed.TotalSeconds) / 1048576):F} MBytes/s)");
                            cakecontext?.Log.Write(Verbosity.Normal, LogLevel.Debug, $"Upload took {sw.Elapsed} to complete");

                            if (fs != null)
                            {
                                fs.Dispose();
                            }
                        }
                    }
                }
            }
        }