how to retrieve list of local git repos via libgit2sharp? - libgit2sharp

Via libgit2sharp how to obtain a list of local repos?
I don't see anything useful in the list of git commands
https://github.com/libgit2/libgit2sharp/wiki/LibGit2Sharp-Hitchhiker%27s-Guide-to-Git

via libgit2sharp how to obtain a list of local repos ?
LibGit2sharp is a library that allows users to interact with git repositories.
However, it doesn't provide any feature which would scan the filesystem, searching for potentially existing local repositories.

If you are actually asking about branches in an enlistment:
public List<string> GetLocalBranchList()
{
var output = new List<string>();
using (var repo = new Repository(_LocalGitPath))
{
foreach (var branch in repo.Branches)
output.Add(branch.FriendlyName);
return output;
}
}
if you are truly meaning repros and not branches, then no. But you don't really need libgit2sharp for that. Just scan all the directories for some of the files or folders that are present in each enlistment (the .git hidden folder, .gitignore, etc.)

This worked for me to find the list of repositories inside a directory (non-recursive) using libgit2sharp.
Usage example:
var gitService = new GitService();
var repositoryPaths = gitService.FindRepositoryPaths(rootDirectory);
public class GitService
{
private const string GitRepoFolder = ".git";
public IEnumerable<string> FindRepositoryPaths(string path)
{
var repositories = new List<string>();
var directories = Directory.EnumerateDirectories(path);
foreach(var directory in directories)
{
var possibleGitDirectory = Path.Combine(directory, GitRepoFolder);
if (Directory.Exists(possibleGitDirectory))
{
try
{
using (var repo = new Repository(directory))
{
if (repo != null)
{
repositories.Add(directory);
}
}
}
catch(RepositoryNotFoundException)
{
}
}
}
return repositories;
}
}

Related

CRUD Functions for creating folder in wwwroot

I want to create a function which can create folder inside wwwroot folder.
Because my client requirement is to create albums (folder). I need to save this albums in my root folder and then the pictures in those folders. For example : BirthdayAlbum, WeedingAlbum and so on..
How can i do this in ASP.NET Core MVC?
Although your question does not include what you have done so far but I hope this will help you in a way:
public async Task<IActionResult> Upload(string folder)
{
if (folder == null)
{
folder = "Uploads";
}
var file = Request.Form.Files[0];
var directory = Path.Combine(_environment.WebRootPath, $"{folder}");
var filePath = $"{Request.Scheme}://{Request.Host}/{folder}/";
var finalFileName = "";
if (file.Length > 0)
{
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var fileName = Path.GetFileName(Guid.NewGuid().ToString().Substring(0, 12).ToLower() + file.FileName);
var path = Path.GetFullPath(directory);
using (var fileStream = new FileStream(Path.Combine(path, fileName), FileMode.Create, FileAccess.ReadWrite))
{
await file.CopyToAsync(fileStream);
}
finalFileName = fileName;
}
return Ok($"{filePath + finalFileName}");
}
NOTE: Please inject IWebHostEnvironment in your controller constructor if you are using ASP.NET Core 3.1 or its equivalent if lower.
What the above code does is to allow you create folders in the wwwroot folder with the folder name you specified and as well upload images or files.
I hope this helps you resolve the issue.

VSTS SDK retrieve projects in subfolders

I have the following code to retrieve all projects in TFS using the .net SDK for VSTS and using TFS2018. But I only get the top most project folders. How can I retrieve the subfolders of a certain project?
var uri = new Uri("https://devserver/tfs/DefaultCollection");
using (var projectHttpClient = new ProjectHttpClient(uri, cred)) {
var projects = projectHttpClient.GetProjects().Result;
}
I also tried changing the uri to
var uri = new Uri("https://devserver/tfs/DefaultCollection/MyProject");
But I get a Page not found error.
Here is a snapshot of the TFS structure. I would like to retrieve the projects on the sublevel. However I am only receiving the second level projects. The level with the user icons.
Try the code below to get folders:
using Microsoft.TeamFoundation.Client;
using System;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace TestCaseProject
{
class Program
{
static void Main(string[] args)
{
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("http://tfsserver:8080/tfs/DefaultCollection"));
var versioncontrols = tfs.GetService<VersionControlServer>();
var workspace = versioncontrols.CreateWorkspace("workspaceName","workspaceOwner");
String ServerFolder = #"$/TeamProject/Folder";
String LocalFolder = #"C:\Folder";
WorkingFolder workfolder = new WorkingFolder(ServerFolder, LocalFolder);
workspace.CreateMapping(workfolder);
workspace.Get();
}
}
}

How to access team project list or Git project list using TFS REST API

I am trying the following to get list of projects from "on prem" TFS
private static async void Method()
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "Username", "Password"))));
using (HttpResponseMessage response = client.GetAsync(
"http://test-test-app1:8080/tfs/boc_projects/_apis/projects?api-version=2").Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
I am using a user name and password which has admin permissions on TFS i am trying to connect.But i get unauthorized access error when i try the above.
The REST API of getting a list of team projects is:
>
http://tfsserver:8080/tfs/CollectionName/_apis/projects?api-version=1.0
Make sure you have enabled Basic Auth for your TFS:
check your IIS to see whether the Basic authentication service role is installed.
go to IIS Manager, select Team Foundation Server -- Authentication
and disable everything other than Basic Authentication. Then do the
same for the tfs node under Team Foundation Server.
restart your IIS.
Here's a simple app using the Catalog Service. It looks for a file by cycling through all Project Collections and Projects, and finds instances of the file by name. It wouldn't take much to change it for your needs.
using System;
using System.Linq;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace EpsiFinder
{
internal class Program
{
// Server URL. Yes, it's hardcoded.
public static string Url = #"http://tfs.someserver.com:8080/tfs";
private static void Main()
{
// Use this pattern search for the file that you want to find
var filePatterns = new[] { "somefile.cs" };
var configurationServerUri = new Uri(Url);
var configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(configurationServerUri);
var configurationServerNode = configurationServer.CatalogNode;
// Query the children of the configuration server node for all of the team project collection nodes
var tpcNodes = configurationServerNode.QueryChildren(
new[] { CatalogResourceTypes.ProjectCollection },
false,
CatalogQueryOptions.None);
// Changed to use the Catalog Service, which doesn't require admin access. Yay.
foreach (var tpcNode in tpcNodes)
{
Console.WriteLine("Collection: " + tpcNode.Resource.DisplayName + " - " + tpcNode.Resource.Description);
// Get the ServiceDefinition for the team project collection from the resource.
var tpcServiceDefinition = tpcNode.Resource.ServiceReferences["Location"];
var configLocationService = configurationServer.GetService<ILocationService>();
var newUrl = new Uri(configLocationService.LocationForCurrentConnection(tpcServiceDefinition));
// Connect to the team project collection
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(newUrl);
// This is where we can do stuff with the team project collection object
// Get the Version Control instance
var versionControl = tfs.GetService<VersionControlServer>();
// Select the branches that match our criteria
var teamBranches = versionControl.QueryRootBranchObjects(RecursionType.Full)
.Where(s => !s.Properties.RootItem.IsDeleted)
.Select(s => s.Properties.RootItem.Item)
.ToList();
// Match the file in the branches, spit out the ones that match
foreach (var item in from teamBranch in teamBranches
from filePattern in filePatterns
from item in
versionControl.GetItems(teamBranch + "/" + filePattern, RecursionType.Full)
.Items
select item)
Console.WriteLine(item.ServerItem);
}
}
}
}

Is it possible to get all the projects and subprojects using TFS API

I am working on TFS API. I am trying to get the entire list of projects, subprojects, files from TFS.
Could someone guide me regarding it.
TfsTeamProjectCollection teamProjectCollection = teamFoundationserver.TfsTeamProjectCollection;
ProjectCollection projCollect = (ProjectCollection) teamProjectCollection.GetService(typeof(ProjectCollection));
The above code just shows the first level from TFS. How Can I go further deep into TFS tree.
I want the entire list of projects, and solutions under each project.
Thanks,
SV
There's no such thing as a "subproject." What it sounds like you want to do is get a listing of all subfolders / files under each project.
To do that, iterate through each of your projects, and do a GetItems on each. Here's some code:
TfsTeamProjectCollection teamProjectCollection = new TfsTeamProjectCollection(new Uri("http://sw100429:8080"));
ProjectCollection projCollect = (ProjectCollection)teamProjectCollection.GetService(typeof(ProjectCollection));
VersionControlServer vcs = teamProjectCollection.GetService<VersionControlServer>();
// This approach lets you get the list of files for each team project individually.
foreach (TeamProject tp in projCollect)
{
string path = string.Format("$/{0}", tp.Name);
var filesAndFolders = vcs.GetItems(path, RecursionType.Full);
}
// However, this approach is a bit more succinct - instead
// of getting them for each team project, just start at "$/" and work your way down
var allFilesAndFolders = vcs.GetItems("$/", RecursionType.Full);
Using your q&a (thanks) I was able to put this sample together after a lot of trial and error. It goes a step further to show how to map the local paths too. I hope this saves some readers some head aches.
This example was put together in a form in VS 2015 and uses the following assembly references (that were also tricky to track down)
All located in C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\vl45o2it.tph on my machine.
Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.VisualStudio.TeamFoundation.dll
Apologies if my terminology is out in places. I don't mind if you edit any of this.
using System;
using System.Linq;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Framework.Client;
using System.Diagnostics;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace Tfs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Uri tfsUri = new Uri("http://server:8080/tfs");
string repositoryName = "yourrepository";
string projectPath = "$/project/path/path/path";
Uri repositoryUri = new Uri(string.Format("{0}/{1}", tfsUri.AbsoluteUri, repositoryName));
TfsConfigurationServer tfscs = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
//get the repository
CatalogNode repository = tfscs.CatalogNode.QueryChildren(new Guid[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None)
.FirstOrDefault(a => string.Compare(a.Resource.DisplayName, repositoryName, true) == 0);
//open in the project collection
TfsTeamProjectCollection pc = tfscs.GetTeamProjectCollection(new Guid(repository.Resource.Properties["InstanceId"]));
//tfs project file structure access
VersionControlServer vcs = pc.GetService<VersionControlServer>();
WorkspaceInfo wsi = Workstation.Current.GetAllLocalWorkspaceInfo().FirstOrDefault(a => a.ServerUri == repositoryUri);
//user functionality (checkin, localpaths etc)
Workspace ws = wsi.GetWorkspace(pc);
//get the file structure
ItemSet items = vcs.GetItems(projectPath, RecursionType.Full);
foreach (Item i in items.Items)
{
Debug.WriteLine(string.Format("{0} ({1}) - {2} - {3}", i.ServerItem,
i.ContentLength.ToString(),
i.ItemType.ToString(),
ws.GetLocalItemForServerItem(i.ServerItem)));
}
}
}
}

How do I activate a sharepoint 2007 feature on a specific document library

I have created a custom feature for sharepoint 2007 using visual studio 2010. When I activate the feature it of course fires on all document libraries in the site collection. can someone give me an example of how to make the feature fire on a specific document library/list instance.
First you'll have to add an EventReceiver to your feature and then in your Feature's xml add a ReceiverClass, like this:
<Feature Id="f68efad8-ea0a-42a2-9994-db3b74aa67f8"
Title="My features title"
Description="Blah blah blah"
Version="12.0.0.0"
Hidden="FALSE"
Scope="Web"
DefaultResourceFile="core"
ReceiverAssembly="MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c4f34f956cd0552b"
ReceiverClass="MyProject.FeatureCode.EventHandler" <!-- This is where you set the EventReceiver -->
xmlns="http://schemas.microsoft.com/sharepoint/">
EventHandler being the EventReceiver when you're feature is activated.
My example
First of, my eventreceiver:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
var assembly = typeof(PermissionHandler).Assembly.ToString();
var classList = typeof(PermissionHandler).FullName;
var web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
try
{
var list = web.Lists["MyList"];
list.EventReceivers.Add(SPEventReceiverType.ItemAdded, assembly, classList);
list.EventReceivers.Add(SPEventReceiverType.ItemUpdated, assembly, classList);
}
catch (Exception ex)
{
EventLogger.LogError("Sample feature failed to run.", this, ex);
}
}
In the above example I want to add some permissions to the elements in MyList.
As you can see I make 2 variables which is the typeof(PermissionHandler), which is a public class I've created to do the job.
I have added 5 items to the list before activating this feature, so I want the already existing items to also get the permissions I'm setting for the new items. This is how I do it:
private void updateItemPermissions(SPItemEventProperties properties)
{
DisableEventFiring();
SPListItem listItem = properties.ListItem;
SPSecurity.RunWithElevatedPrivileges(() =>
{
SPSite site = new SPSite(listItem.ParentList.ParentWeb.Site.ID);
SPWeb web = site.OpenWeb(listItem.ParentList.ParentWeb.ID);
SPList list = web.Lists[listItem.ParentList.ID];
SPListItem item = list.Items.GetItemById(properties.ListItem.ID);
item.BreakRoleInheritance(true);
if (item.RoleAssignments.Count > 0)
{
for (var i = item.RoleAssignments.Count - 1; i >= 0; i--)
item.RoleAssignments.Remove(i);
}
var group = item.Web.Site.RootWeb.Groups["Visitors"];
AddPermissions(item, web, SPRoleType.Reader, group);
});
EnableEventFiring();
}
private static void AddPermissions(SPListItem curItem, SPWeb web, SPRoleType roleType, SPPrincipal principal)
{
SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(roleType);
SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
curItem.RoleAssignments.Add(roleAssignment);
curItem.Update();
}
I hope this helped you :)

Resources