I'm trying to get all branches of repository by using SharpSvn but I can not find any method can do it.
Is it possible to get all branches by using SharpSvn?
I think Matt Z was on the right track, but that code doesn't compile. Here is an adjusted version that should work with the latest version of SharpSVN (as of Dec 2015).
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using SharpSvn;
....
private List<string> GetSVNPaths()
{
List<string> files = new List<string>();
using (SvnClient svnClient = new SvnClient())
{
Collection<SvnListEventArgs> contents;
//you can get the url from the TortoiseSVN repo-browser if you aren't sure
if (svnClient.GetList(new Uri(#"https://your-repository-url/"), out contents))
{
files.AddRange(contents.Select(item => item.Path));
}
}
return files;
}
I don't know anything about SharpSVN, but branches in Subversion are just directory trees -- there's nothing special about them.
If your repository follows they typical layout with three top-level directories (trunk/ branches/ tags/), you can just check out the /branches directory to get all the branches side-by-side.
The SharpSvn.SvnClient class has a GetList() function that works really well:
using (SvnClient svnClient = new SvnClient())
{
Collection contents;
List files = new List();
if (svnClient.GetList(new Uri(svnUrl), out contents))
{
foreach(SvnListEventArgs item in contents)
{
files.Add(item.Path);
}
}
}
Once you have the collection, you can get the path of each item at the location. You can also use the Entry object to get information concerning each item, including whether it is a directory or a file, when it was last modified, etc.
Related
I want to compress every video within every drive and its sub-directories so the code I have used so far finds each drive and looks for .mp4 locations. Then it uses that list of strings to compress each file but it comes up with this error at:
var mediaInfo = FFProbe.Analyse(filePath: d)
and
.FromFileInput(d, verifyExists: true)
System.ComponentModel.Win32Exception: 'The system cannot find the file specified'
I checked what the .Analyse needs and it is a string and d is a string which has the right path location C:\\Users\\Helix\\Desktop\\apartment\\5 Little Monkeys Swinging In The Tree.mp4" which I thought would work but it does not seem to like it. What am I doing wrong?
I am also curious as to if GetDrives() works on network drives? And if it does would two servers running this code conflict when grabbing the same file at the same time?
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MediaToolkit;
using MediaToolkit.Model;
using FFMpegCore;
using FFMpegCore.Enums;
namespace Video_Compressor_for_Servers
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void CompAll_Click(object sender, EventArgs e)
{
//An empty list for later to collect strings
List<string> file = new List<string>();
//extract primary drives strings into a list since there could be more than just C:\
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
//The d.Name output has "Drive C:\" as the output. remove the "Drive " part first
var replacement = d.Name.Replace("Drive ", "");
/*Grab each files location with the Directory tool from the earlier IO libary.
GetFiles is a subcommand of directory with options in the brackets. These
options can be found in more detail by seaching for GetFiles C#*/
string[] files = Directory.GetFiles(#"C:\Users\Helix\Desktop\apartment\","*.mp4", SearchOption.AllDirectories);// replacement//AllDirectories
//Convert the array to a list
List<string> templist = files.ToList();
//Add them to the earlier empty list we made
file.AddRange(templist);
}
//Now that we have paths to all the files we need we can now compress them
foreach (string d in file)
{
var mediaInfo = FFProbe.Analyse(filePath: d);
//Open the video file with MediaToolkit
FFMpegArguments
.FromFileInput(d, verifyExists: true)
.OutputToFile(d, false, options => options
.WithVideoCodec(VideoCodec.LibX264)
.WithConstantRateFactor(21)
.WithAudioCodec(AudioCodec.Aac)
.WithVariableBitrate(4)
.WithVideoFilters(filterOptions => filterOptions
.Scale(VideoSize.Ed))
.WithFastStart())
.ProcessSynchronously();
}
}
}
}
You need to download both ffprobe.exe and ffmpeg.exe.
The executable is missing not the media one.
I want to use the Teamfoundation.SourceControl.WebApi to check for updates or local changes against our TFS Source Control.
I can gather information about changesets from an item which is committed TFS but I am not able to gather this information based on a local file path inside my mapped workspace.
Is it somehow possible without using the ExtendedClient?
I want something like this:
TfvcChangesetSearchCriteria tcsc = new TfvcChangesetSearchCriteria();
tcsc.ItemPath = #"c:\source\mappedtfs\MYPROJECT\src\MainWindow.cs";/*<--- localPath would be nice here*/
List<TfvcChangesetRef> changerefs = tfvcHttpClient.GetChangesetsAsync("MYPROJECT", null, null, null, null, tcsc).Result;
Microsoft.Teamfoundation.SourceControl.WebApi is a webapi which does not interact with local workspaces and files. If you want to get changesets with local items' path, use Microsoft.TeamFoundation.VersionControl.Client in the Client Library.
using Microsoft.TeamFoundation.Client;
using System;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.Collections.Generic;
namespace ConsoleX
{
class Program
{
static void Main(string[] args)
{
Uri url = new Uri("https://tfsuri");
TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(url);
VersionControlServer vcs = ttpc.GetService<VersionControlServer>();
IEnumerable<Changeset> cses = vcs.QueryHistory("Path here could be local path or server path", RecursionType.Full);
foreach (Changeset cs in cses)
{
Console.WriteLine(cs.ChangesetId);
Console.WriteLine(cs.Comment);
}
Console.ReadLine();
}
}
}
I'm trying to write a unit test to enforce consolidation of Nuget packages (we have a build requirement that all unit tests pass so this would keep PRs that aren't consolidating from passing) and I was attempting to use Nuget.Core to do that. However, I cannot seem to find my way through their libraries and no one has asked this question yet. So, how can I get all the Nuget packages a given solution references programmatically?
This is the final solution (along with unit test). The key is to use the Directory library to iterate over all the projects in the solution and then use NuGet.Core to analyze the NuGet packages in each project.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NuGet;
using Shouldly;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace UnitTests
{
[TestClass]
public class NugetConsolidationTest
{
private List<string> _ignoredPackages = new List<string>();
[TestMethod]
public void AllNugetPackagesAreConsolidated()
{
var packageVersionMapping = new Dictionary<string, List<string>>();
var parentDir = (Directory.GetParent(Directory.GetCurrentDirectory()).Parent).Parent.FullName;
var files = Directory.GetFiles(parentDir, "packages.config", SearchOption.AllDirectories);
foreach (var packageFile in files)
{
var file = new PackageReferenceFile(packageFile);
var refs = file.GetPackageReferences(true);
foreach (var packageRef in refs)
{
if (_ignoredPackages.Contains(packageRef.Id))
continue;
if (!packageVersionMapping.ContainsKey(packageRef.Id))
packageVersionMapping[packageRef.Id] = new List<string>() { packageRef.Version.ToFullString() };
else
{
if (packageVersionMapping[packageRef.Id].All(x => !x.Equals(packageRef.Version.ToFullString(),
StringComparison.InvariantCultureIgnoreCase)))
packageVersionMapping[packageRef.Id].Add(packageRef.Version.ToFullString());
}
}
}
var errors = packageVersionMapping.Where(x => x.Value.Count > 1)?.
Select(x => $"Package {x.Key} has {x.Value.Count} separate versions installed! Current versions are {string.Join(", ", x.Value)}");
errors.ShouldBeEmpty();
}
}
}
You can always read the package.config files and parse them.
The one that's inside the solution directory with reference other packages.config file is one for each project contained in the solution.
I'd like to use Roslyn to analyze semantic information within the context of a block of C# code inside a Razor View.
Is there any way (within Visual Studio 2015, or even in a unit test) to get the SemanticModel that represents this code?
Razor files contain a C# projection buffer with the generated C# code (including the parts that you don't write yourself). This buffer has full Roslyn services and is exactly what you're looking for.
You need to walk through the TextView's BufferGraph and find the CSharp buffer; you can then get its Document and semantic model.
If you're starting from the cursor location, you need simply need to map that location to a CSharp buffer.
Note that it is perfectly legal for a TextView to contain multiple CSharp buffers. (although the Razor editor will never do that)
If you aren't working in a TextView, you need to do all of this yourself; you need to run the Razor source through the Razor compiler to get the generated C# source, then compile that with Roslyn to get a semantic model.
Extract the code representing the view from the Razor view file using RazorTemplateEngine.GenerateCode and CSharpCodeProvider.GenerateCodeFromCompileUnit (or the VBCodeProvider if you want the intermediate source as VB.NET). You can then use Roslyn to parse the code.
There's an example of using Roslyn with Razor view files here.
Take note that GenerateCode carries a caveat:
This type/member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
Just in case anyone else gets stuck on this, I have mini sample app which may help.
I had a CMS class like this:
public partial class CMS
{
public static string SomeKey
{
get { return (string) ResourceProvider.GetResource("some_key"); }
}
// ... and many more ...
}
... and I wanted to find out which of these were used throughout my solution for a report ... Enter Roslyn!
The following app will print out the count for the used and unused references:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Razor;
namespace TranslationSniffer
{
class Program
{
static void Main(string[] args)
{
new Program().Go().Wait();
}
public async Task Go()
{
// Roslyn!
var ws = MSBuildWorkspace.Create();
// Store the translation keys...
List<string> used = new List<string>();
List<string> delete = new List<string>();
string solutionRoot = #"C:\_Code\PathToProject\";
string sln = solutionRoot + "MySolution.sln";
// Load the solution, and find all the cshtml Razor views...
var solution = await ws.OpenSolutionAsync(sln);
var mainProj = solution.Projects.Where(x => x.Name == "ConsumerWeb").Single();
FileInfo[] cshtmls = new DirectoryInfo(solutionRoot).GetFiles("*.cshtml", SearchOption.AllDirectories);
// Go through each Razor View - generate the equivalent CS and add to the project for compilation.
var host = new RazorEngineHost(RazorCodeLanguage.Languages["cshtml"]);
var razor = new RazorTemplateEngine(host);
var cs = new CSharpCodeProvider();
var csOptions = new CodeGeneratorOptions();
foreach (var cshtml in cshtmls)
{
using (StreamReader re = new StreamReader(cshtml.FullName))
{
try
{
// Let Razor do it's thang...
var compileUnit = razor.GenerateCode(re).GeneratedCode;
// Pull the code into a stringbuilder, and append to the main project:
StringBuilder sb = new StringBuilder();
using (StringWriter rw = new StringWriter(sb))
{
cs.GenerateCodeFromCompileUnit(compileUnit, rw, csOptions);
}
// Get the new immutable project
var doc = mainProj.AddDocument(cshtml.Name + ".cs", sb.ToString());
mainProj = doc.Project;
}
catch(Exception ex)
{
Console.WriteLine("Compile fail for: {0}", cshtml.Name);
// throw;
}
continue;
}
}
// We now have a new immutable solution, as we have changed the project instance...
solution = mainProj.Solution;
// Pull out our application translation list (its in a static class called 'CMS'):
var mainCompile = await mainProj.GetCompilationAsync();
var mainModel = mainCompile.GetTypeByMetadataName("Resources.CMS");
var translations = mainModel.GetMembers().Where(x => x.Kind == SymbolKind.Property).ToList();
foreach (var translation in translations)
{
var references = await SymbolFinder.FindReferencesAsync(translation, solution) ;
if (!references.First().Locations.Any())
{
Console.WriteLine("{0} translation is not used!", translation.Name);
delete.Add(translation.Name);
}
else
{
Console.WriteLine("{0} :in: {1}", translation.Name, references.First().Locations.First().Document.Name);
used.Add(translation.Name);
}
}
Console.WriteLine();
Console.WriteLine("Used references {0}. Unused references: {1}", used.Count, delete.Count);
return;
}
}
}
Roslyn only models cshtml files while they are open, but during that time they are similar to every other source file in the Workspace model.
Is there something specific you have tried that isn't working?
C# 2008
I have using the WebClient DownloadFile method.
I can download the files I want. However, the client has insisted on creating different folders which will contain the version number. So the name of the folders would be something like this: 1.0.1, 1.0.2, 1.0.3, etc.
So the files will be contained in the latest version in this case folder 1.0.3. However, how can my web client detect which is the latest one?
The client will check this when it starts up. Unless I actually download all the folders and then compare. I am not sure how else I can do this.
Many thanks for any advice,
Create a page which gives you the current version number.
string versionNumber = WebClient.DownloadString();
Allow directory browsing in IIS and download the root folder. Then you could find the latest version number and construct the actual url to download. Here's a sample (assuming your directories will be of the form Major.Minor.Revision):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
using (var client = new WebClient())
{
var directories = client.DownloadString("http://example.com/root");
var latestVersion = GetVersions(directories).Max();
if (latestVersion != null)
{
// construct url here for latest version
client.DownloadFile(...);
}
}
}
static IEnumerable<Version> GetVersions(string directories)
{
var regex = new Regex(#"<a href=""[^""]*/([0-9]+\.[0-9]+\.[0-9])+/"">",
RegexOptions.IgnoreCase);
foreach (Match match in regex.Matches(directories))
{
var href = match.Groups[1].Value;
yield return new Version(href);
}
yield break;
}
}
This question might have some useful information for you. Please read my answer which deals with enumerating files on a remote server.