C# Examples

Examples of programs integrating with Vault and Fortress API. Also, information on integrating with NAnt, CruiseControl.Net and other third-party tools

Moderator: SourceGear

Post Reply
shannon

C# Examples

Post by shannon » Mon Jun 11, 2007 2:58 pm

The following C# example code was written for version 4.0.1.

All methods except AddFortressItem will work with either the Vault or Fortress API, AddFortressItem requires Fortress.

Code: Select all

using System;
using System.Collections.Generic;
using System.Text;

using VaultClientIntegrationLib;
using VaultClientOperationsLib;
using VaultLib;
using MantisLib;
using System.IO;
using System.Xml;

namespace Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            // Call a method here to test it out after changing the relevant variables.
        }

        static void BasicSourceControl()
        {
            string url = "http://VaultServer/VaultService";
            string username = "username";
            string password = "password";
            string repository = "Your Repository";

            // Set the login options and login/connect to a repository.
            ServerOperations.client.LoginOptions.URL = url;
            ServerOperations.client.LoginOptions.User = username;
            ServerOperations.client.LoginOptions.Password = password;
            ServerOperations.client.LoginOptions.Repository = repository;
            ServerOperations.Login();

            //Create a folder.
            string pathToANewFolder = "$/path/to/a/newFolder";
            ServerOperations.ProcessCommandCreateFolder(pathToANewFolder);

            //Add two files to the new folder.
            string pathToFile1 = "c:/path/to/a/file";
            string pathToFile2 = "c:/path/to/another/file";
            string folderToAddItemsTo = "$/path/to/a/folder/";
            ServerOperations.client.AutoCommit = true;
            ServerOperations.ProcessCommandAdd(folderToAddItemsTo, new string[] { pathToFile1, pathToFile2 });
        }

        static void MoreBasicSourceControl()
        {
            string url = "http://VaultServer/VaultService";
            string username = "username";
            string password = "password";
            string repository = "Your Repository";

            // Set the login options and login/connect to a repository.
            ServerOperations.client.LoginOptions.URL = url;
            ServerOperations.client.LoginOptions.User = username;
            ServerOperations.client.LoginOptions.Password = password;
            ServerOperations.client.LoginOptions.Repository = repository;
            ServerOperations.Login();

            // Set a working folder.
            string repositoryFolderPath = "$/path/to/a/repository/folder/";
            string diskPath = "c:/path/to/a/working/folder/";
            bool bCreateDiskPath = true;
            ServerOperations.SetWorkingFolder(repositoryFolderPath, diskPath, bCreateDiskPath);

            // Do a get on the working folder.
            GetOptions getOptions = new GetOptions();
            getOptions.Recursive = true;
            GetOperations.ProcessCommandGet(new string[] { diskPath }, getOptions);

            // Exclusively check out a file.
            getOptions = new GetOptions();
            string filePath = "$/path/to/a/file";
            bool bExclusive = true;
            bool bGetLatest = true;
            ServerOperations.ProcessCommandCheckout(new string[] { filePath }, bExclusive, bGetLatest, getOptions);

            // List all checkouts.
            VaultClientCheckOutList coList = ServerOperations.ProcessCommandListCheckOuts();

            // output the checkout list
            StringWriter sw = new StringWriter();
            System.Xml.XmlTextWriter xml = new XmlTextWriter(sw);
            xml.Formatting = System.Xml.Formatting.Indented;
            xml.WriteStartElement("root");

            xml.WriteStartElement("ListCheckOuts");
            XmlHelper.XmlOutput(xml, coList);
            xml.WriteEndElement();

            // Check in the file we just checked out, set the unchanged handler to check in the item (the default unchanged op is Undo Checkout).
            bool bKeepCheckedOut = false;
            ServerOperations.ProcessCommandCheckIn(new string[] { filePath }, UnchangedHandler.Checkin, bKeepCheckedOut, LocalCopyType.Leave);

            //Query the file history so we can view the check in.
            bool bRecursive = false;
            int beginVersion = -1;
            int endVersion = -1;
            VaultHistoryItem[] items = ServerOperations.ProcessCommandHistory(filePath, bRecursive, DateSortOption.desc, null, null, VaultDate.EmptyDate().ToString(), VaultDate.EmptyDate().ToString(), null, null, beginVersion, endVersion, 10);

            // output the history items
            xml.WriteStartElement("root");

            xml.WriteStartElement("History");
            XmlHelper.XmlOutput(xml, items);
            xml.WriteEndElement();

            xml.Close();
            Console.Out.WriteLine(sw.ToString());
        }

        public static void WildcardTasks()
        {
            string url = "http://VaultServer/VaultService";
            string username = "username";
            string password = "password";
            string repository = "Your Repository";

            // Set the login options and login/connect to a repository.
            ServerOperations.client.LoginOptions.URL = url;
            ServerOperations.client.LoginOptions.User = username;
            ServerOperations.client.LoginOptions.Password = password;
            ServerOperations.client.LoginOptions.Repository = repository;
            ServerOperations.Login();

            ServerOperations.client.AutoCommit = true;

            // add some files to use with wildcard tasks
            string pathToFile1 = "c:/path/to/wildcard1.txt";
            string pathToFile2 = "c:/path/to/wildcard2.txt";
            string pathToFile3 = "c:/path/to/wildcardWithLetters.txt";
            string folderPath = "$/a/folder/";
            ServerOperations.ProcessCommandAdd(folderPath, new string[] { pathToFile1, pathToFile2, pathToFile3 });

            //  get all three wildcards to a nonworking folder
            string wildcardStr = "wildcard*.txt";
            GetOptions getOptions = new GetOptions();
            string nonworkingFolderPath = "c:/path/to/nonworkingFolderForWildcards/";
            GetOperations.ProcessCommandGetWildcardToNonWorkingFolder(folderPath, new string[] { wildcardStr }, getOptions, nonworkingFolderPath);

            // get wildcard1.txt and wildcard2.txt to a working folder
            wildcardStr = "wildcard?.txt";
            string workingFolderPath = "c:/path/to/aWorkingFolder/";
            GetOperations.ProcessCommandGetWildcard(workingFolderPath, new string[] {wildcardStr}, getOptions);
        }

        public static void LabelTasks()
        {
            string url = "http://VaultServer/VaultService";
            string username = "username";
            string password = "password";
            string repository = "Your Repository";

            // Set the login options and login/connect to a repository.
            ServerOperations.client.LoginOptions.URL = url;
            ServerOperations.client.LoginOptions.User = username;
            ServerOperations.client.LoginOptions.Password = password;
            ServerOperations.client.LoginOptions.Repository = repository;
            ServerOperations.Login();

            ServerOperations.client.AutoCommit = true;

            // Label the current version of a folder
            string objectPath = "$/path/to/a/folderToLabel/";
            string labelName = "LabeledFolder";
            long versionID = -1; //pass -1 to get the current version
            ServerOperations.ProcessCommandLabel(objectPath, labelName, versionID);

            // Get label to a location on disk
            GetOptions getOptions = new GetOptions();
            string destPath = "c:/path/to/labeledFolder/";
            GetOperations.ProcessCommandGetLabelToLocationOutsideWorkingFolder(objectPath, labelName, null, getOptions, destPath);
        }

        public static void AddFortressItem()
        {
            string url = "http://FortressServer/VaultService";
            string username = "username";
            string password = "password";

            // Set the login options and login/connect to a repository.
            ServerOperations.client.LoginOptions.URL = url;
            ServerOperations.client.LoginOptions.User = username;
            ServerOperations.client.LoginOptions.Password = password;
            ServerOperations.Login();

            // List the open fortress items
            string projectName = "aProject";
            MantisItemExpanded[] openItems = ItemTrackingOperations.ProcessCommandListOpenFortressItems(projectName);

            // output the items
            StringWriter sw = new StringWriter();
            System.Xml.XmlTextWriter xml = new XmlTextWriter(sw);
            xml.Formatting = System.Xml.Formatting.Indented;
            xml.WriteStartElement("root");

            xml.WriteStartElement("ListOpenFortressItems");
            XmlHelper.XmlOutput(xml, openItems);
            xml.WriteEndElement();

            // Make a new fortress item
            FortressItemExpanded newItem = new FortressItemExpanded();
            newItem.ProjectName = projectName;
            newItem.Description = "A new item.";
            newItem.Details = "Some details about the new item.";
            newItem.Status = "Open";
            newItem.Assignee = "someUser";
            newItem.Resolver = "anotherUser";
            newItem.Platform = "Unknown";
            newItem.ItemType = "Bug";
            newItem.TimeEstimate = "Unknown";
            newItem.Priority = "Low";
            newItem.Validate();  // Call Validate after setting all your strings for your item and before you pass the item to a method.

            
            // Add the new item
            ItemTrackingOperations.ProcessCommandAddFortressItem(newItem);

            // List the open fortress items again
            openItems = ItemTrackingOperations.ProcessCommandListOpenFortressItems(projectName);

            // output the items
            xml.WriteStartElement("root");

            xml.WriteStartElement("ListOpenFortressItems");
            XmlHelper.XmlOutput(xml, openItems);
            xml.WriteEndElement();

            xml.Close();
            Console.Out.WriteLine(sw.ToString());
        }
    }
}


JeffM
Posts: 12
Joined: Wed Feb 27, 2008 2:59 pm

Post by JeffM » Wed Feb 27, 2008 3:09 pm

Can we get a more detailed example of getting folder history from vault? Its tough to wrap your head around these APIs when all of the parameters are strings.

How can I only return files that were checked in or modified? The example uses null for a lot of the parameters. Its nice to know that you CAN use a null when you do not need to filter by that specific parameter, but what if we DO want to filter by the actions?

Any reason why ProcessCommandHistory() does not use enum's for these parameters? Consuming the API's would be a lot easier if I could use intellisense to write the code for me!!

Thanks for any help,

Jeff

shannon

Post by shannon » Wed Feb 27, 2008 3:25 pm

/// <param name="excludedActions">A comma-separated list of actions to filter out of the history request. To exclude all actions, pass "add,branch,checkin,create,delete,label,move,obliterate,pin,propertychange,rename,rollback,share,snapshot,undelete". Pass null to return history for all actions.</param>

Pass a comma-separated list of the actions you want to exclude as one big string. The strings for the actions are listed in the doc I pasted above. For example, to only see checkins pass this string "add,branch,create,delete,label,move,obliterate,pin,propertychange,rename,rollback,share,snapshot,undelete"

Excluding users is the same, just substitute usernames for action strings.

JeffM
Posts: 12
Joined: Wed Feb 27, 2008 2:59 pm

Post by JeffM » Wed Feb 27, 2008 3:57 pm

Thanks for the help, very much appreciated.

Jeff

nemoby
Posts: 56
Joined: Mon Jan 10, 2005 4:34 pm
Location: Bellingham WA

Post by nemoby » Mon Mar 31, 2008 3:30 pm

Any examples of how to check for success on a Checkin, folder create or Commit opperation?

Thanks,

-Andy

shannon

Post by shannon » Tue Apr 01, 2008 8:25 am

ServerOperations should throw an exception when any of those operations fail. Short of checking the history, I am not sure there is another way to check.

nemoby
Posts: 56
Joined: Mon Jan 10, 2005 4:34 pm
Location: Bellingham WA

Post by nemoby » Tue Apr 01, 2008 2:59 pm

Ok, I see how that works. It would be really nice if ServerOperations threw something other than a plain old System.Exception. Difficult to trap on from a high level. Something along the lines of a custom ServerOperationException would be much nicer and make for a better API design.

-Andy

icnocop
Posts: 46
Joined: Wed Aug 18, 2004 12:41 pm

Re: C# Examples

Post by icnocop » Tue Dec 16, 2008 7:09 pm

Hi.

I am wondering how to compare the working folder version with the latest version in vault, and how to detect files that are missing in the working folder.

This is part of the code I am working on, but it does not detect the version number in the working folder. Any ideas?

Code: Select all

private void GetOldAndMissing(string path)
        {
            VaultClientFolder folder = ServerOperations.ProcessCommandListFolder(path, true);
            
            foreach (VaultClientFile file in folder.Files)
            {
                long version = file.Version;
                VaultFileProperties props = file.GetFileProperties();
                long latestVersion = props.LatestVersion;
                if (latestVersion > version)
                {
                    GetOperations.ProcessCommandGet(new string[] { file.FullPath}, m_getOptions);
                }
            }

            foreach (VaultClientFolder subfolder in folder.Folders)
            {
                GetOldAndMissing(subfolder.FullPath);
            }
        }
Thank you.

shannon

Re: C# Examples

Post by shannon » Wed Dec 17, 2008 8:55 am

Try looping over the files and calling this:

WorkingFolderFileAge fileAge = ServerOperations.client.ClientInstance.GetWorkingFolder(file).FileAge(file);

if (fileAge = WorkingFolderFileAge.Old) then do your get

icnocop
Posts: 46
Joined: Wed Aug 18, 2004 12:41 pm

Re: C# Examples

Post by icnocop » Fri Dec 19, 2008 7:46 am

Thank you, that worked great! :)

shannon

Re: C# Examples

Post by shannon » Fri Dec 19, 2008 8:08 am

Glad to hear it. Let us know if you have any more trouble.

kayessaych
Posts: 5
Joined: Tue Apr 24, 2012 4:44 pm

Re: C# Examples

Post by kayessaych » Thu Apr 26, 2012 12:43 pm

shannon wrote: All methods except AddFortressItem will work with either the Vault or Fortress API, AddFortressItem requires Fortress.
I can confirm this does work with Vault Pro 5.1.2 at this time - something I wish I would have known while searching the other day!

Beth
Posts: 8550
Joined: Wed Jun 21, 2006 8:24 pm
Location: SourceGear
Contact:

Re: C# Examples

Post by Beth » Thu Apr 26, 2012 3:14 pm

Thank you for the update.

At the time that the post was written, Vault Professional did not exist, but Vault Standard did.
Beth Kieler
SourceGear Technical Support

Post Reply