TFS API: Mapped worked space is always null - c#

Question background:
I'm trying to do the following process but currently cannot succesfully map the TFS code to the specified local folder:
Create a temporary work space.
Set the temporay workspace to be on the C drive in a folder called 'BasicSccExample'
From a passed object called 'vssItem', concatenate its 'VcQaFolder' and 'Name' properties to set the specified TFS server path.
Map the TFS server path to the local path.
Get the latest code from the TFS server.
Create a folder called 'sub' within the 'BasicSccExample' Folder.
Create the this new 'basic' folder.
Check the differences between the local specified file copies.
Delete the temporary workspace.
The code to carry out the above process:
Workspace workspace = tfServer.CreateWorkspace("BasicSccExample", tfServer.AuthorizedUser);
string topDir = null;
string result = null;
string localDir = #"c:\BasicSccExample";
string test = vssItem.VcQaFolder + "/"+vssItem.Name;
workspace.Map(test, localDir);
workspace.Get();
topDir = Path.Combine(workspace.Folders[0].LocalItem, "sub");
Directory.CreateDirectory(topDir);
var potentialDifference = Difference.DiffFiles(topDir, FileType.Detect(topDir, null), topDir, FileType.Detect(topDir, null), new DiffOptions());
result = potentialDifference.Next == null ? "Identical" : "Different";
workspace.Delete();
The error:
I always receive a null exception when attempting to compare the files - which for testing purpose at the moment are the same file. The reason for this error is because the specified local folder on the C drive that the code should be mapped too is always empty. Can anyone tell me where I'm going wrong?

Sorted this issue out. I was trying to set the file as a folder.
For anyone out there with similar issues, check you're not making the same mistake and this code works
.
I can now map from the specifed TFS server path to the specified local path.
Workspace workspace = tfServer.CreateWorkspace("TempDevWorkspace", tfServer.AuthorizedUser);
string topDir = null;
string localDir = #"c:\TempDevWorkspaceFolder";
workspace.Map(tfsItem.VcDevFolder, localDir);
workspace.Get();
string directory = Path.Combine(workspace.Folders[0].LocalItem, null);

Related

Get TFS mapped folder of a local sub folder of the solution?

Let's say we have a solution in TFS Source Control which has already been mapped to a local folder SolutionFolder.
We are in a sub folder SubFolder of this SolutionFolder.
How can we write C# code to get the mapped path of this SubFolder?
Use the WorkStation.Current to grab the information for the folder in question:
Import the following namespaces:
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
and then use you can get to the data you want through:
var workspace = Workstation.Current.GetLocalWorkspaceInfo(solutionFolder);
if (workspace != null)
{
var teamProjectUri = workspace.ServerUri;
// var server = TfsConfigurationServerFactory.GetConfigurationServer(teamProjectUri);
var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(teamProjectUri);
var cssService = projectCollection.GetService<ICommonStructureService4>();
var project = cssService.GetProjectFromName(solutionName);
}
From there you can easily grab the Workspace as well and from there the serverpath: workspace.GetWorkspace().GetServerItemForLocalItem()
To provide credentials, you can use one of the additional overloads that accepts a CredentialsProvider. The default provider is the UICredentialsProvider. Or you can also call server or projectCollection's EnsureAuthenticated.
See also:
https://jessehouwing.net/vsts-tfs-api-auto-detect-connection-details/

How to map workspace and get latest folders in c#

It is my first time to work with TFS and I am not quite familiar how workspace mapping works. I would just like to print the local folder and repository folder when the workspace is mapped, so I would know if the workspace is mapped because I get an exception such as "Object reference not set to an instance of an object."
var workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(path);
var server = new TfsTeamProjectCollection(workspaceInfo.ServerUri);
var workspace = workspaceInfo.GetWorkspace(server);
workspace.PendEdit(path);
And is my Get Latest code correct? I mean I would like to get the latest version of a whole folder and this is what I got.
var service = tpc.GetService<VersionControlServer>();
var getLatestOfTfsRepositoryCs = service.GetWorkspace(#"C:\temp\project");
I suggest you to use Workspace.IsLocalPathMapped method in order to check
link : http://msdn.microsoft.com/fr-fr/library/microsoft.teamfoundation.versioncontrol.client.workspace.islocalpathmapped.aspx
If you wish get lastest version you can use Workspace.Get method, with VersionSpec.Latest value

Saving image to a folder in IIS localhost

I have to save images to a folder located in "c:\inetpub\wwwroot\" and named as "UploadedImages". Here is my code:
public string SaveImage(string base64,int compno)
{
string res = "";
try
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
{
using (Bitmap bm2 = new Bitmap(ms))
{
bm2.Save(Server.MapPath("~/UploadedImages/ID"+compno+".jpg"));
}
}
res = "done";
}
catch (Exception ex) {
res = ex.ToString();
}
return res;
}
but it throws "A generic error occured in GDI+ at System.Drawing.Image.Save" exception. What am I doing wrong? This code works fine when saving image locally as
bm2.Save("D:Embasy\UploadedImages\ID"+compno+".jpg"));
What changes do I need to make to save images in localhost directory?
Your not going to believe this -- the site running v1.1 had a virtual directory set-up which was mapped to the directory in which the image was saved to -- things worked fine.
The v2.0 site also had the same virtual directory name, but the physical path was different -- I changed the path to point to the same directory as the v1.0 site and now the code works.
So in short -- you were right about the "path must exist".
Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. For a supported alternative, see Windows Imaging Components.
and kindly refer this link
http://msdn.microsoft.com/en-us/library/xs6ftd89.aspx
When you are using Server.Mappath
bm2.Save(Server.MapPath("~/UploadedImages/ID"+compno+".jpg"));
"~(tield)" : is point to project/application root folder c:\inetpub\wwwroot\yourproject
then find remaining your path /UploadedImages and then create ID1.jpg.
But your imagefolder "UploadImages" is exist in d: not in c:\inetpub\wwwroot\yourproject
if you want to exist your image folder in D: then you should to create
virtual directory and then you need to apply path as relevant
My problem actually was that every time i published website, I replaced the "UploadedImages" folder too and thus permissions were changed. So, i didnt replaced the folder again after changing its permissions and creating "everyone" group and giving full rights to it. Now code is working perfectly :)

get latest specific project in C#

I have a project that should be get latest to specific date. I have this code:
var serverFolder = pathInTfs;
var localFolder = pathInLocalMachin;
var workingFolder = new WorkingFolder(serverFolder, localFolder);
// Create a workspace mapping
workspace.CreateMapping(workingFolder);
if (!workspace.HasReadPermission)
{
throw new SecurityException(
String.Format("{0} does not have read permission for {1}",
versionControl.AuthorizedUser, serverFolder));
}
// Get the files from the repository
workspace.Get(dateForLatest, GetOptions.Overwrite);
every thing is good but I want to be get latest only directory "pathInTfs" in "pathInLocalMachin" but when program run workspace.Get() every project be get latest.
How I can get latest one path in my project.
There are several overloads of Get which allow you to specify the set of objects you want to get. For what you're doing, I think you want Get(GetRequest, GetOptions).
The GetRequest includes an ItemSpec where you can specify a folder to get, and then indicate RecursionType.Full.

How to get Directory while running unit test

Hi when running my unit test I'm wanting to get the directory my project is running in to retrieve a file.
Say I have a Test project named MyProject. Test I run:
AppDomain.CurrentDomain.SetupInformation.ApplicationBase
and I receive "C:\\Source\\MyProject.Test\\bin\\Debug".
This is close to what I'm after. I don't want the bin\\Debug part.
Anyone know how instead I could get "C:\\Source\\MyProject.Test\\"?
I would do it differently.
I suggest making that file part of the solution/project. Then right-click -> Properties -> Copy To Output = Copy Always.
That file will then be copied to whatever your output directory is (e.g. C:\Source\MyProject.Test\bin\Debug).
Edit: Copy To Output = Copy if Newer is the better option
Usually you retrieve your solution directory (or project directory, depending on your solution structure) like this:
string solution_dir = Path.GetDirectoryName( Path.GetDirectoryName(
TestContext.CurrentContext.TestDirectory ) );
This will give you the parent directory of the "TestResults" folder created by testing projects.
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
This will give you the directory you need....
as
AppDomain.CurrentDomain.SetupInformation.ApplicationBase
gives nothing but
Directory.GetCurrentDirectory().
Have alook at this link
http://msdn.microsoft.com/en-us/library/system.appdomain.currentdomain.aspx
Further to #abhilash's comment.
This works in my EXE's, DLL's and when tested from a different UnitTest project in both Debug or Release modes:
var dirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location.Replace("bin\\Debug", string.Empty));
/// <summary>
/// Testing various directory sources in a Unit Test project
/// </summary>
/// <remarks>
/// I want to mimic the web app's App_Data folder in a Unit Test project:
/// A) Using Copy to Output Directory on each data file
/// D) Without having to set Copy to Output Directory on each data file
/// </remarks>
[TestMethod]
public void UT_PathsExist()
{
// Gets bin\Release or bin\Debug depending on mode
string baseA = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
Console.WriteLine(string.Format("Dir A:{0}", baseA));
Assert.IsTrue(System.IO.Directory.Exists(baseA));
// Gets bin\Release or bin\Debug depending on mode
string baseB = AppDomain.CurrentDomain.BaseDirectory;
Console.WriteLine(string.Format("Dir B:{0}", baseB));
Assert.IsTrue(System.IO.Directory.Exists(baseB));
// Returns empty string (or exception if you use .ToString()
string baseC = (string)AppDomain.CurrentDomain.GetData("DataDirectory");
Console.WriteLine(string.Format("Dir C:{0}", baseC));
Assert.IsFalse(System.IO.Directory.Exists(baseC));
// Move up two levels
string baseD = System.IO.Directory.GetParent(baseA).Parent.FullName;
Console.WriteLine(string.Format("Dir D:{0}", baseD));
Assert.IsTrue(System.IO.Directory.Exists(baseD));
// You need to set the Copy to Output Directory on each data file
var appPathA = System.IO.Path.Combine(baseA, "App_Data");
Console.WriteLine(string.Format("Dir A/App_Data:{0}", appPathA));
// C:/solution/UnitTestProject/bin/Debug/App_Data
Assert.IsTrue(System.IO.Directory.Exists(appPathA));
// You can work with data files in the project directory's App_Data folder (or any other test data folder)
var appPathD = System.IO.Path.Combine(baseD, "App_Data");
Console.WriteLine(string.Format("Dir D/App_Data:{0}", appPathD));
// C:/solution/UnitTestProject/App_Data
Assert.IsTrue(System.IO.Directory.Exists(appPathD));
}
I normally do it like that, and then I just add "..\..\" to the path to get up to the directory I want.
So what you could do is this:
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + #"..\..\";
For NUnit this is what I do:
// Get the executing directory of the tests
string dir = NUnit.Framework.TestContext.CurrentContext.TestDirectory;
// Infer the project directory from there...2 levels up (depending on project type - for asp.net omit the latter Parent for a single level up)
dir = System.IO.Directory.GetParent(dir).Parent.FullName;
If required you can from there navigate back down to other directories if required:
dir = Path.Combine(dir, "MySubDir");
According to https://github.com/nunit/nunit/issues/742#issuecomment-121964506
For NUnit3 , System.Environment.CurrentDirector is never changed, so it shall be the path of solution.
Eg:
string szProjectPath = System.Environment.CurrentDirectory + #"\where\your\project\is";
I prefer fixed location rather than GetParent().
One drawback of GetParent is when build is changed from AnyCPU to x86, default path would be changed from bin\Debug to bin\x86\Debug.
Need to get another parent, and it's pain in the neck.
Also, you may still access to you test assemblies at TestContext.CurrentContext.TestDirectory and get output from TestContext.CurrentContext.WorkDirectory
Edit:
Note: There are many changes in NUnit3. I will suggest reading through the documentation about "Breaking changes"
The best solution I found was to put the file as an embedded resource on the test project and get it from my unit test. With this solution I don´t need to care about file paths.
I'm not sure if this helps, but this looks to be briefly touched on in the following question.
Visual Studio Solution Path environment variable
In general you may use this, regardless if running a test or console app or web app:
// returns the absolute path of assembly, file://C:/.../MyAssembly.dll
var codeBase = Assembly.GetExecutingAssembly().CodeBase;
// returns the absolute path of assembly, i.e: C:\...\MyAssembly.dll
var location = Assembly.GetExecutingAssembly().Location;
If you are running NUnit, then:
// return the absolute path of directory, i.e. C:\...\
var testDirectory = TestContext.CurrentContext.TestDirectory;
My approach relies on getting the location of the unit testing assembly and then traversing upwards. In the following snippet the variable folderProjectLevel will give you the path to the Unit test project.
string pathAssembly = System.Reflection.Assembly.GetExecutingAssembly().Location;
string folderAssembly = System.IO.Path.GetDirectoryName(pathAssembly);
if (folderAssembly.EndsWith("\\") == false) {
folderAssembly = folderAssembly + "\\";
}
string folderProjectLevel = System.IO.Path.GetFullPath(folderAssembly + "..\\..\\");
You can do it like this:
using System.IO;
Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, #"..\..\"));
use StackTrace
internal static class Extensions
{
public static string GetSourceDirectoryName(this Type type)
{
StackTrace stackTrace = new StackTrace(true);
foreach (var frame in stackTrace.GetFrames())
{
if (frame.GetMethod() is { } method && method.DeclaringType == type)
{
return Path.GetDirectoryName(frame.GetFileName());
}
}
throw new Exception($"未找到{type.Name}源文件目录");
}
}

Categories

Resources