Get all folders from TFS using TFS SDK - c#

I am creating a TFS tool that will get "changeset information" from the TFS server.
Now, I want to provide a "TFS Browser" so that the user can browse what "branch/folder" he wants to fetch information from.
I am using a TreeView control and the GetItems function to get the items' path from TFS:
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
e.Node.Nodes.RemoveAt(0);
RecursionType recursion = RecursionType.OneLevel;
Item[] items = null;
// Get the latest version of the information for the items.
ItemSet itemSet = sourceControl.GetItems(e.Node.Tag.ToString(), recursion);
items = itemSet.Items;
foreach (Item item in items)
{
if (item.ServerItem == e.Node.Tag.ToString()) //Skip self
continue;
string filename = Path.GetFileName(item.ServerItem);
if (Path.GetExtension(filename) == "")
{
TreeNode node = new TreeNode(filename, new TreeNode[] { new TreeNode() });
node.Tag = item.ServerItem;
e.Node.Nodes.Add(node);
}
}
}
The code below demonstrates that after clicking the "expand" button from a node, the app will "query" the items that are below the current "branch" (e).
However, I don't want to include files to the browser. As a quick and dirty check, I am checking if the "path" has an extension and if not, assume that it is a directory and show it. All was good until I discovered that we have a folder named "v1.1".
There is a solution. I can re-invoke GetItems and check its content. According to MSDN:
If the path argument is a file,
returns a set of Items that contain
just that file. If the path is a
folder, returns a set of Items that
contain all items in that folder. If
the path contains a wildcard
character, returns a set of Items in
the specified folder that match the
wildcard.
However, each call to GetItems take roughly a second and if a folder contains multiple files, the "expansion" of the node takes forever.
So, is there a way to just get all the "folders" from TFS? Or any other idea how to check if a path is a folder or a file?
Thanks!

It seems that there is a member called .ItemType for Item. You can check against that.

One solution that I have just found is to use the GetFileTypes method to retrieve the different extensions registered on the server. Then check every "item" against these extensions like so:
if (!Extensions.Contains(Path.GetExtension(item.ServerItem).Replace(".","").ToLower()))
{
//Add Node
}
However, this is not really fool proof. What if a folder is named FOLDER.DLL?

Related

Dropbox API, How to see each team member's folder permissions?

I am new to using the Dropbox API and I want to access every team member's folder permissions and put it into a database, but I'm having trouble on where to find this information. I am able to access each member's folders and can see the name of every folder, but not the permissions of each folder that the user has. How can I do this?
Here is what I have so far:
public MainPage()
{
this.InitializeComponent();
var task = Task.Run((Func<Task>)MainPage.Run);
task.Wait();
}
static async Task Run()
{
using (DropboxTeamClient DBTeamClient = new DropboxTeamClient("MY ACCESS KEY"))
{
//get all the dropbox members
var members = await DBTeamClient.Team.MembersListAsync();
//loop through all members ordered by email alphabetical
foreach (var member in members.Members.OrderBy(a => a.Profile.Email))
{
//get each user
var userClient = DBTeamClient.AsMember(member.Profile.TeamMemberId);
//get each user's file information
var list = await userClient.Files.ListFolderAsync(string.Empty);
//loop through the list of file and show permissions on folders
foreach (var item in list.Entries.OrderBy(b => b.PathDisplay))
{
//only display folder information
if (item.IsFolder)
{
//find out the user's permissions to this folder here?
//then I will output user information and permissions to a db
}
}
}
}
}
Am I approaching this the wrong way? Any guidance is appreciated, thanks in advance!
Thanks to Greg's comment and post on Dropbox I was able to solve my problem. Here is his solution:
"When you list files and folders using FilesUserRoutes.ListFolderAsync like this, you're listing the contents of the member's Dropbox folder, which will include both shared folders (where they have some specific permission level) as well as their private folders (where they don't have a specific permission level, since it's just their folders). For shared folders, the returned FolderMetadata.SharingInfo will be set, but it doesn't contain information about that user's permission level in that folder. (By the way, make sure you implement ListFolderContinueAsync as well, to make sure you can retrieve all results, when using ListFolderAsync. Check out the ListFolderAsync documentation for more information.)
Instead, if you want to list the shared folders the user has access to, including their level of access in each one, you should use SharingUserRoutes.ListFoldersAsync. Likewise, make sure you implement SharingUserRoutes.ListFoldersContinueAsync too, as this interface is also paginated. Each returned SharedFolderMetadata will list the user's AccessType and Permissions.
Here's a little example:
var actionsToCheck = new Dropbox.Api.Sharing.FolderAction[] { Dropbox.Api.Sharing.FolderAction.EditContents.Instance, Dropbox.Api.Sharing.FolderAction.InviteEditor.Instance };
var list = await userClient.Sharing.ListFoldersAsync(actions: actionsToCheck); // actions can optionally be supplied to check the permissions the user has for specific actions
foreach (var item in list.Entries)
{
Console.WriteLine(item.SharedFolderId);
Console.WriteLine(item.PathLower); // only set if the folder is mounted
Console.WriteLine(item.AccessType);
Console.WriteLine(item.Permissions);
}
// and so on, iterating over pages from userClient.Sharing.ListFoldersContinueAsync if list.Cursor is set
Hope this helps!"
I hope others find this as useful as I did.

Recent open files in RichTextBox [duplicate]

First of all I am a newbie in C# Programming, and I need to create a simple MRU as fast as i could.
Well the thing is I've tried looking at some online examples but however I found them to be quite a bit too confusing...
So is there anyway that anyone can create a "Recently Used" section in the toolstripmenuitem without going into those complicated codes??
E.g I will not be able to understand this stuff...
Registry key:
KEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\FileMRUList
Code:
Application.UserAppDataRegistry.DeleteSubKey("MRU", false);
RegistryKey appKey = Application.UserAppDataRegistry.CreateSubKey("MRU");
dictionary
microsoft.win32
I will only need something as simple as shown in this link below http://www.codeproject.com/KB/menus/MRUHandler.aspx
So you want to create a submenu like in the screenshot? For this, you will have to:
Store the list of recently-used files somewhere. This could be the registry, or it could just be a simple textfile, which I’ll do now to keep it simple.
Learn how to generate menu items at runtime instead of in the designer.
1. Store the MRU in a file
You will probably have already declared a private field to contain your MRU, right?
private List<string> _mru = new List<string>();
Every time someone opens a file, you add this file to the beginning of the MRU, right?
_mru.Insert(0, fullFilePath);
Now, of course when the application closes, you need to save this MRU to a file. Let’s do that in the Form’s FormClosed event. Double-click the FormClosed event in the properties and write some code which looks somewhat like this:
var appDataPath = Application.UserAppDataPath;
var myAppDataPath = Path.Combine(appDataPath, "MyApplication");
var mruFilePath = Path.Combine(myAppDataPath, "MRU.txt");
File.WriteAllLines(mruFilePath, _mru);
Now we have saved the MRU in a file. Now obviously when the application starts, we need to load it again, so do something like this in the form’s Load event:
var appDataPath = Application.UserAppDataPath;
var myAppDataPath = Path.Combine(appDataPath, "MyApplication");
var mruFilePath = Path.Combine(myAppDataPath, "MRU.txt");
if (File.Exists(mruFilePath))
_mru.AddRange(File.ReadAllLines(mruFilePath));
2. Create the menu items
Now that _mru contains the file paths that we want in our menu, we need to create a new menu item for each. I’ll be assuming here that you already have a menu item in the File menu (the item called “Most Recently Used” in your screenshot) and that it is called mnuRecentlyUsed, and that we only need to create sub-items:
foreach (var path in _mru)
{
var item = new ToolStripMenuItem(path);
item.Tag = path;
item.Click += OpenRecentFile;
mnuRecentlyUsed.DropDownItems.Add(item);
}
Now all we need is the method that actually opens a file, which I called OpenRecentFile:
void OpenRecentFile(object sender, EventArgs e)
{
var menuItem = (ToolStripMenuItem) sender;
var filepath = (string) menuItem.Tag;
// Proceed to open the file
// ...
}
Disclaimer
Please don’t use any of this code unless you understand it and you are sure that it is written to do what you intended. If it needs to do something slightly different, I’m sure you can make the necessary changes yourself.
Also, I’m sure you will have noticed that the above doesn’t update the sub-menu while the program is running. If you understand how the above code works, then I’m sure you’ll be able to figure out the rest for yourself.
http://www.codeproject.com/Tips/680088/Recent-Items-Tool-Strip-Menu-Item
This project does exactly what you want

Windows API CodePack. Get all selected items in the CommonOpenFileDialog:IFileOpenDialog

I work with the CommonOpenFileDialog class from the Windows® API Code Pack for Microsoft® .NET Framework that implements the IFileOpenDialog interface.
More info about Windows API CodePack here:
http://archive.msdn.microsoft.com/WindowsAPICodePack
Problem:
The below method returns the First selected folder if (multiple folders) or (mutltiple folders and files) were selected in the "Open File Dialog" dialog window.
IFileOpenDialog.GetSelectedItems([MarshalAs(UnmanagedType.Interface)] out IShellItemArray ppsai)
How to return All selected elements (folders and files) in the IFileOpenDialog window as a list of IShellItem, no matter what I selected there?
You need to specify the Multiselect property.
Here's an unmarshalled example:
CommonOpenFileDialog folderDialog = new CommonOpenFileDialog("Input Folder Selection");
folderDialog.IsFolderPicker = true;
folderDialog.Multiselect = true;
if (folderDialog.ShowDialog() == CommonFileDialogResult.Ok)
{
foreach (string folderName in folderDialog.FileNames) //it's a little confusing, but FileNames represents folders as well in the API
{
// do something
}
}

How do I get the filename of an Item?? - Team Foundations SDK

I am trying to get a file by name from TFS. I am getting all the files from a location recursively and then looping through these to find a specific file. It appears that the VersionControl.Client.Item object does not expose the filename (or foldername).
tfs.EnsureAuthenticated();
VersionControlServer vcs = versionControlServer)tfs.GetService(typeof(VersionControlServer));
var allStaticFiles = vcs.GetItems(path + "*", RecursionType.Full).Items;
foreach (var staticFile in allStaticFiles)
{
if(staticFile == ?? // need the filename)
{
}
(Assuming TFS2008.)
The type of vcs.GetItems(...).Items is Item[].
So therefore staticFile is an Item instance.
The properties of Item are all server side because details of the path will depend on the client's workspace mapping (there can be multiple workspaces including this item on the same computer for the same user).
You can use Item.ServerItem to get the filename (take the last path element)
To the path, get a Workspace instance representing your current workspace and use one of its methods to map the ServerItem to a local path (there are a few with subtly different behaviour, without more context it is not clear which is the right one).

C# Search for subdirectory (not for files)

Every example I see seems to be for recursively getting files in subdirectories uses files only. What I'm trying to do is search a folder for a particular subdirectory named "xxx" then save that path to a variable so I can use it for other things.
Is this possible without looping through all the directories and comparing by name?
Well
Directory.GetDirectories(root);
will return you an array of the subdirectories.
You can then use Linq to find the one you're interested in:
IEnumerable<string> list = Directory.GetDirectories(root).Where(s => s.Equals("test"));
which isn't a loop in your code, but is still a loop nevertheless. So the ultimate answer is that "no you can't find a folder 'test' without looping".
You could add .SingleOrDefault() to the Linq, but that would depend on what you wanted to do if your "test" folder couldn't be found.
If you change the GetDirectories call to include the SearchOption SearchOption.AllDirectories then it will do the recursion for you as well. This version supports searching - you have to supply a search string - though in .NET Framework it's case sensitive searching. To return all sub directories you pass "*" as the search term.
Obviously in this case the call could return more than one item if there was more than one folder named "test" in your directory tree.
var foldersFound = Directory.GetDirectories(root, "test", SearchOption.AllDirectories)
This will return a string array with all the folders found with the given name. You can change the last parameter so that it only checks top level directories and you can change root to adjust where it is starting from.
First of all, "No, it is not possible without looping through all the directories and comparing by name".
I believe your real question is "Is there an existing API which will handle looping through all the directories and comparing by name for me?"
Yes, there is. It's called Directory.Exists():
var xxxPath = Path.Combine(parentFolder, "xxx");
if (Directory.Exists(xxxPath))
savedPath = xxxPath;
Yes, I believe that the only available solution (short of third party libraries) is a recursive search for the directory via name comparison.
You can use Windows Search which provides api for .Net too. Here is more detailed information: Windows Search 4.0 for Developers
Here is a snippet for searching for a folder using two filters while considering for the UnauthorizedAccessException, it can be refactored to use only one filter:
public static string FindGitPath(string firstFilter, string secondFilter, string initialPath)
{
string gitPath = string.Empty;
foreach (var i in Directory.GetDirectories(initialPath)) {
try {
foreach (var f in Directory.GetDirectories(i, firstFilter, SearchOption.AllDirectories)) {
foreach (var s in Directory.GetDirectories(f)) {
if (s == Path.Combine(f,secondFilter)) {
gitPath = f;
break;
}
}
}
} catch (UnauthorizedAccessException) {
Console.WriteLine("Path is not accessible: {0}", i);
}
}
return gitPath;
}
Usage example:
Console.WriteLine("Retrieved the git database folder as {0}", FindGitPath("database",".git", "c:\\"));

Categories