TFS API: GetLocalWorkspaceInfo always returns null - c#

On one of my machines, I get a return value of null from any GetLocalWorkspaceInfo call. I have isolated to problem to where it even fails for this simple program:
namespace WorkstationTest
{
using Microsoft.TeamFoundation.VersionControl.Client;
class Program
{
static void Main()
{
string workspaceLocalPath = #"C:\Dev";
var info = Workstation.Current
.GetLocalWorkspaceInfo(workspaceLocalPath);
// info is always null here
}
}
}
What I have already checked:
The exact same code works on my other machine the way it should.
I have verified that I have a workspace at C:\Dev
I have created a new workspace and in a different directory and changed the workspaceLocalPath variable in the code to match.
I have consulted the documentation which states that the return value will be null if the path is not in a workspace. From the above image, the path should be in a workspace.
Yet, everything seems to suggest this should work. Is there anything I could be missing?

After migrating from TFS2013 to TFS2017 in the company I work for I had the same problem with Workstation.Current.GetLocalWorkspaceInfo.
What worked for me is a call to Workstation.EnsureUpdateWorkspaceInfoCache:
TfsTeamProjectCollection tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("<your-tfs-uri-here>"));
VersionControlServer tfServer = tpc.GetService<VersionControlServer>();
Workstation.Current.EnsureUpdateWorkspaceInfoCache(tfServer, tfServer.AuthorizedUser);
I added the above code lines to the constructor of my TFS proxy class that uses GetLocalWorkspaceInfo.

When executing tf workspaces (on my computer) in the Visual Studio 2010 command prompt it says No workspace matching * found on this computer, but when executing the same command in Visual Studio 2012 it returns back all my expected workspaces.
The issue can be resolved by doing any of the following:
Reference the version of the Microsoft.TeamFoundation.VersionControl.Client dll that was connected with Visual Studio 2012 instead of the dll connected with Visual Studio 2010.
Open Visual Studio 2010 and connect it to TFS to where it will create the workspaces for Visual Studio 2010

I know this is an old post, but just like to share the workaround that we have, by using VersionControlServer.QueryWorkspaces to query all the workspaces for the user on his/her machine.
private static Workspace FindWorkspaceByPath(TfsTeamProjectCollection tfs, string workspacePath)
{
VersionControlServer versionControl = tfs.GetService<VersionControlServer>();
WorkspaceInfo workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(workspacePath);
if (workspaceInfo != null)
{
return versionControl.GetWorkspace(workspaceInfo);
}
// No Workspace found using method 1, try to query all workspaces the user has on this machine.
Workspace[] workspaces = versionControl.QueryWorkspaces(null, Environment.UserName, Environment.MachineName);
foreach (Workspace w in workspaces)
{
foreach (WorkingFolder f in w.Folders)
{
if (f.LocalItem.Equals(workspacePath))
{
return w;
}
}
}
throw new Exception(String.Format("TFS Workspace cannot be determined for {0}.", workspacePath));
}

In my case, this issue occurred because of VersionControl.config file put under TFS cache folder (C:\Users\DeepakR\AppData\Local\Microsoft\Team Foundation\5.0\Cache\Volatile\0cb76a25-2556-4bd6-adaa-5e755ac07355_http) goes for a toss i.e. the configured workspace information weren't available as expected.
So, it basically needs a refresh of VersionControl.config file. Auto Refresh happens when Visual Studio gets loaded again i.e. it pulls the configured workspace information from Server and updates the config file or even if we execute tf command utility (tf.exe workspaces /collection:TFSURL)
Microsoft.TeamFoundation.VersionControl.Client's (v12.0.0.0) Workstation class has a function EnsureUpdateWorkspaceInfoCache which will do the same trick
VersionControlServer vcs = (VersionControlServer)tpc.GetService(typeof(VersionControlServer));
Workstation.Current.EnsureUpdateWorkspaceInfoCache(vcs, Environment.UserName);
https://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.versioncontrol.client.workstation.ensureupdateworkspaceinfocache(v=vs.120).aspx
Hope the suggestion helps to resolve the issue.

I had this issue recently (today) using Visual Studio 2017, plus several other versions installed and a number of local workspaces.
I ended up updating the 'Team Foundation Server Client' NuGet package to the latest version (15.x) through the 'Manage NuGet Packages' menu and that fixed it.
I did also remove the existing project references first but that part might depend on what you need.

Simply run with the tricks.
Nothing is going to work properly without a proper DLL reference. The below had fixed the same issue i had for 5 days as it was screwing my time up.
Place the below DLL's in the bin folder of your project and give a reference to the whole solution for all the DLL's. If any error comes up like 'Reference could not be given' ignore it and skip that DLL from giving reference instead just place also the error creating DLL in bin folder which the project will automatically take during build
DLL's:
Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.Core.WebApi.dll
Microsoft.TeamFoundation.TestManagement.Client.dll
Microsoft.TeamFoundation.TestManagement.Common.dll
Microsoft.TeamFoundation.Work.WebApi.dll
Microsoft.TeamFoundation.WorkItemTracking.Client.DataStoreLoader.dll
Microsoft.TeamFoundation.WorkItemTracking.Client.dll
Microsoft.TeamFoundation.WorkItemTracking.Common.dll
Microsoft.TeamFoundation.WorkItemTracking.Controls.dll
Microsoft.TeamFoundation.WorkItemTracking.Proxy.dll
Microsoft.TeamFoundation.WorkItemTracking.WebApi.dll
Microsoft.VisualStudio.Services.Client.Interactive.dll
Microsoft.VisualStudio.Services.Common.dll
Microsoft.VisualStudio.Services.WebApi.dll
Microsoft.WITDataStore32.dll
Microsoft.WITDataStore64.dll
The above dll's can be found in the below path if the System is installed with MTM or TFS
Path: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer

In my C:\Users\<username>\AppData\Local\Microsoft\Team Foundation folder I had 2 folders:
7.0
8.0
Within the 8.0 folder was the following folder:
\Cache\Volatile\c1dbda02-c575-4dd2-b221-e83f7cb63665_http
But within the 7.0 folder the \Cache\Volatile folder was empty
So all I did was copy across the c1dbda02-c575-4dd2-b221-e83f7cb63665_http folder into 7.0\Cache\Volatile\
After this GetLocalWorkspaceInfo call returned the workspace info successfully

This is how to find workspace when you have server path:
Workspace[] workspaces = _versionControl.QueryWorkspaces(null, Environment.UserName, Environment.MachineName);
return workspaces.FirstOrDefault(w => !string.IsNullOrEmpty(w.TryGetLocalItemForServerItem(ConstDefaultFlowsTfsPath)));
Where ConstDefaultFlowsTfsPath is server path with "$" for instance : "$/MyCompany/Services/DiagnosticsFlows"
You could also replace the last line to:
return workspaces.FirstOrDefault(w => !string.IsNullOrEmpty(w.GetServerItemForLocalItem(myLocalPath)));
and that should work for you too.

Related

TuesPechkin unable to load DLL 'wkhtmltox.dll'

I've been using TuesPechkin for some time now and today I went to update the nuget package to the new version 2.0.0+ and noticed that Factory.Create() no longer resolved, so I went to read on the GitHub the changes made and noticed it now expects the path to the dll?
IConverter converter =
new ThreadSafeConverter(
new PdfToolset(
new StaticDeployment(DLL_FOLDER_PATH)));
For the past few hours I've tried almost all the paths I can think of, "\bin", "\app_data", "\app_start", etc and I can't seem to find or figure out what it wants for the path and what dll?
I can see the TuesPechkin dll in my bin folder and it was the first path I tried, but I got the following error:
Additional information: Unable to load DLL 'wkhtmltox.dll': The
specified module could not be found. (Exception from HRESULT:
0x8007007E)
Where is that dll and now can I get it as the library doesn't seem to contain it, I tried installing the TuesPechkin.Wkhtmltox.Win32 package but the dll still is nowhere to be found. Also I am using this in a asp.net website project so I assume that using the following should work for obtaining the path, right?
var path = HttpContext.Current.Server.MapPath(#"~\bin\TuesPechkin.dll");
Further information: https://github.com/tuespetre/TuesPechkin/issues/57
The Tuespechkin has a zip file as a resource in the Win32 and Win64 embedded packages for the 'wkhtmltox.dll' file.
What it does when you use the Win32 or Win64 Embedded package is unzips the file and places it in the directory that you specify.
I have been putting a copy of the wkhtmltox dll at the root portion of my web app directory and pointing the DLL_FOLDER_PATH to it using the server physical path of my web app to get to it.
According to the author, you must set the converter in a static field for best results.
I do that, but set the converter to null when I am finished using it, and that seems to work.
Tuespechkin is wrapper for the wmkhtmlox dll file.
The original file is written in C++ and so will not automatically be usable in C# or VB.NET or any of the other managed code domains.
The Tuespechkin.dll file DOES NOT contain a copy of 'wkhtmltox.dll'. You either have to use one of the other embedded deployment modules or install a copy of the 'wkhtmltox.dll' in your web app after downloading it from the internet. That is what I do, and it seems to work just fine.
I am using Team Foundation Server, and attempts to compile code after using the Tuespechkin routines will fail the first time because the 'wkhtmltox.dll' file gets locked, but all you have to do is simply retry your build and it will go through.
I had issues with the 32-bit routine not working in a 64-bit environment and the 64-bit environment not being testable on localhost. I went with the workaround I came up with after examining the source code for Tuespechkin and the Win32 and Win64 embedded deployment packages.
It works well as long as you specify a url for the input rather than raw html.
The older package didn't render css very well.
If you are using a print.aspx routine, you can create the url for it as an offset from your main url.
I don't have the source code I am using with me at this point to offset to your base url for your web application, but it is simply an offshoot of HttpRequest.
You have to use the physical path to find the .dll, but you can use a web path for the print routine.
I hope this answers your question a bit.
If you are getting this error -> Could not load file or assembly 'TuesPechkin.Wkhtmltox.Win64' or one of its dependencies. An attempt was made to load a program with an incorrect format.
In Visual Studio Go to -
Tools -> Options -> Projects and Solutions -> Web Projects -> Use the 64 bit version of IIS Express for web sites and projects.
I installed TuesPechkin.Wkhtmltox.Win64 Nuget package and used the following code in a singleton:
public class PechkinPDFConvertor : IPDFConvertor
{
IConverter converter =
new ThreadSafeConverter(
new RemotingToolset<PdfToolset>(
new Win64EmbeddedDeployment(
new TempFolderDeployment())));
public byte[] Convert(string html)
{
// return PechkinSync.Convert(new GlobalConfig(), html);
return converter.Convert(new HtmlToPdfDocument(html));
}
}
The web application then has to be run in x64 otherwise you will get an error about trying to load an x64 assembly in an x86 environment. Presumably you have to choose x64 or x86 at design time and use the corresponding nuget package, it would be nicer to choose this in the web.config.
EDIT: The above code failed on one server with the exact same message as yours - it was due to having not installed VC++ 2013. So the new code is running x86 as follows
try
{
string path = Path.Combine(Path.GetTempPath(), "MyApp_PDF_32");
Converter = new ThreadSafeConverter(
new RemotingToolset<PdfToolset>(
new Win32EmbeddedDeployment(
new StaticDeployment(path))));
}
catch (Exception e)
{
if (e.Message.StartsWith("Unable to load DLL 'wkhtmltox.dll'"))
{
throw new InvalidOperationException(
"Ensure the prerequisite C++ 2013 Redistributable is installed", e);
}
else
throw;
}
If you do not want run the installer for wkhtmltox just to get the dll, you can do the following:
As #Timothy suggests, if you use the embedded version of wkhtmltox.dll from TuesPechkin, it will unzip it and place it in a temp directory. I copied this dll and referenced it with the StaticDeployment option without any issues.
To find the exact location, I just used Process Monitor (procmon.exe). For me it was C:\Windows\Temp\-169958574\8\0.12.2.1\wkhtmltox.dll
In my case, I am deploying on a 64-bit VPS then I got this error. I have solved the problem by installing the wkhtmltopdf that I downloaded from http://wkhtmltopdf.org/downloads.html. I chose the 32-bit installer.
In my case, I have solved the problem by installing the Wkhtmltox for win32 at https://www.nuget.org/packages/TuesPechkin.Wkhtmltox.Win32/
This error: Unable to load DLL 'wkhtmltox.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) is returned in two situations:
1- Deploy dependency not installed:
For solve this, you can install nuget package "TuesPechkin.Wkhtmltox.Win64" and use this code (for WebApplications running in IIS):
IConverter converter =
new ThreadSafeConverter(
new RemotingToolset<PdfToolset>(
new Win64EmbeddedDeployment(
new TempFolderDeployment())));
// Keep the converter somewhere static, or as a singleton instance!
// Do NOT run the above code more than once in the application lifecycle!
byte[] result = converter.Convert(document);
In runtime this code will copy the dependency "wkhtmltox.dll" in a temporary directory like: "C:\Windows\Temp\1402166677\8\0.12.2.1". It's possible to get the destination of file using:
var deployment = new Win64EmbeddedDeployment(new TempFolderDeployment());
Console.WriteLine(deployment.Path);
2- Microsoft Visual C++ 2013 Redistributable not installed:
As described here:
https://github.com/tuespetre/TuesPechkin/issues/65#issuecomment-71266114, the Visual C++ 2013 Runtime is required.
The solution from README is:
You must have Visual C++ 2013 runtime installed to use these packages. Otherwise, you will need to download the MingW build of wkhtmltopdf and its dependencies from their website and use that with the library. https://github.com/tuespetre/TuesPechkin#wkhtmltoxdll
or, you can install the Microsoft Visual C++ 2013 Redistributable:
choco install msvisualcplusplus2013-redist
Here is AnyCpu version, also support iis-base or winform application
using TuesPechkin.Wkhtmltox.AnyCPU;
...
var converter = PDFHelper.Factory.GetConverter();
var result = converter.Convert(This.Document);
Reference : https://github.com/tloy1966/TuesPechkin
Installing the Visual C++ Redistributable for Visual Studio 2013 resolved the error for me.
https://www.microsoft.com/en-us/download/details.aspx?id=40784

TFS Query History with Physical File Path Exception

I have a piece of code that queries the history of tfs but on my machine I get an exception
saying:
There is no working folder mapping for C:\SDAM.
However if I run this same piece of code in colleagues machine there is no problem.
I am using:
Microsoft.TeamFoundation.Client; version 10
Microsoft.TeamFoundation.VersionControl.Client; version 10
VS2012 Project Update 4
4.5 Framework
Things I have tried:
Refreshing the cache
Delete the cache.
Checked the working folders and added them using Team Foundation Sidekicks to be sure I have source control folder and local folder mapped.
I have passed in the source control folder path $/SDAM and I get history. I go into to tfs explorer and check that $/SDAM is mapped to C:\SDAM
I am completely baffled and any suggestions would be appreciated. This code is already being used widely by us and I need to reuse it.
The results of
tf workspaces /format:detailed /collection:http://XXXX/tfs/
Workspace : XXXXXXXX
Owner : Domain\zzzzzzz
Computer : XXXXXXXX
Comment :
Collection : cccc\ddddd
Permissions: Private
Location : Server
File Time : Current
Working folders:
$/SDAM: C:\SDAM
IEnumerable tfsHistory;
string SourceControlPath = #"C:\SDAM";
var tfsUri = new Uri(#"http://XXXX/tfs/");
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsUri);
var vcs = tfs.GetService<VersionControlServer>();
VersionSpec fromVersion = null, toVersion = null;
fromVersion = new ChangesetVersionSpec(1);
toVersion = new ChangesetVersionSpec(2);
tfsHistory =
vcs.QueryHistory(
SourceControlPath,
LatestVersionSpec.Instance,
0,
RecursionType.Full,
null,
fromVersion,
toVersion,
Int32.MaxValue,
true,
false);
if (tfsHistory != null)
{
//Do something
}
Your tool cannot find a working folder mapping because it is not in the working folder cache for the version of the SDK you're building against. If you do not specify a Team Project Collection and want to get connected to TFS by only a local path, TFS will look in the working folder cache to determine what server and server path correspond to that local path.
If you're building against version 10.0 of the SDK, then it's looking for the working folder cache created by Visual Studio 10.0 (ie, Visual Studio 2010.)
However, if you're running Visual Studio 11.0 and tf 11.0, then it will store the working folder information in the working folder cache for Visual Studio 11.0 (ie, Visual Studio 2012.)
Thus, your tool cannot bootstrap itself with only a working folder mapping. You need to either:
Have your tool connect to the TFS server in question so that it will obtain a fresh copy of the working folder information
Match the version of the SDK you build against to the version of TFS you use with Visual Studio
If you want to dynamically load the newest SDK, you may be able to bind an assembly resolution handler.

Antlr4 C# build error

I am trying to install Antlr4 on a new machine but I am getting the following build error:
C:\antlrtest\antlrtest\Reference\Antlr4\Antlr4.targets(129,5): error AC1000: Unknown build error: Object reference not set to an instance of an object.
This is the offending code:
<Antlr4ClassGenerationTask
ToolPath="$(Antlr4ToolLocation)"
BuildTaskPath="$(Antlr4BuildTaskLocation)"
OutputPath="$(IntermediateOutputPath)"
TargetLanguage="%(Antlr4.TargetLanguage)"
TargetFrameworkVersion="$(TargetFrameworkVersion)"
TargetNamespace="%(Antlr4.CustomToolNamespace)"
SourceCodeFiles="#(Antlr4)"
ContinueOnError="$(_IntellisenseOnlyCompile)"
TokensFiles="#(Antlr4Tokens)"
AbstractGrammarFiles="#(Antlr4AbstractGrammar)"
LanguageSourceExtensions="$(DefaultLanguageSourceExtension)"
GenerateListener="%(Antlr4.Listener)"
GenerateVisitor="%(Antlr4.Visitor)"
ForceAtn="%(Antlr4.ForceAtn)"
AbstractGrammar="%(Antlr4.Abstract)">
<Output ItemName="Antlr4GeneratedCodeFiles" TaskParameter="GeneratedCodeFiles" />
</Antlr4ClassGenerationTask>
I think I followed the correct procedure:
I installed the extension from the VS 2012 website for Antlr.
Then I edited the project file to point to the References.
Then I added a reference to the Runtime DLL.
Any help would be appreciated.
So I ran into this today and was pulling my hair out over it for quite some time. The solution for me was to install both the 32-bit and 64-bit versions of the Java SDK.
Initially I only had the 64-bit version installed. It immediately started working after I installed the 32-bit as well.
Hope that helps someone.
This error is caused by Antlr4 failing to find an appropriate version of Java. On a Windows machine, Antlr4 checks the registry first before it checks your environment variables to determine the suitable location of Java.
Shortly before I experienced the same problem, I had been consolidating the many instances of the Java Runtime Environment I had on my computer. I had many and I trimmed them down to only 1 instance of a 64b JRE and 32b JRE each. I removed the rest by just deleting their folders. Subsequently I checked that my user and system environment variables (specifically JAVA_HOME) still pointed to a valid Java directory.
But I failed to realise that there are registry entries that have to be updated too. Possibly a reinstall of Java would fix the registry entries, but I reverted to just fixing them manually.
So the appropriate place in the Antlr4 code is at https://github.com/tunnelvisionlabs/antlr4cs/blob/master/runtime/CSharp/Antlr4BuildTasks/Antlr4ClassGenerationTaskInternal.cs#L144 .
private string JavaHome
{
get
{
#if !NETSTANDARD
string javaHome;
if (TryGetJavaHome(RegistryView.Default, JavaVendor, JavaInstallation, out javaHome))
return javaHome;
if (TryGetJavaHome(RegistryView.Registry64, JavaVendor, JavaInstallation, out javaHome))
return javaHome;
if (TryGetJavaHome(RegistryView.Registry32, JavaVendor, JavaInstallation, out javaHome))
return javaHome;
#endif
if (Directory.Exists(Environment.GetEnvironmentVariable("JAVA_HOME")))
return Environment.GetEnvironmentVariable("JAVA_HOME");
throw new NotSupportedException("Could not locate a Java installation.");
}
}
#if !NETSTANDARD
private static bool TryGetJavaHome(RegistryView registryView, string vendor, string installation, out string javaHome)
{
javaHome = null;
string javaKeyName = "SOFTWARE\\" + vendor + "\\" + installation;
using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
{
using (RegistryKey javaKey = baseKey.OpenSubKey(javaKeyName))
{
if (javaKey == null)
return false;
object currentVersion = javaKey.GetValue("CurrentVersion");
if (currentVersion == null)
return false;
using (var homeKey = javaKey.OpenSubKey(currentVersion.ToString()))
{
if (homeKey == null || homeKey.GetValue("JavaHome") == null)
return false;
javaHome = homeKey.GetValue("JavaHome").ToString();
return !string.IsNullOrEmpty(javaHome);
}
}
}
}
#endif
Your .\packages\Antlr4.CodeGenerator.4.6.3\build\Antlr4.CodeGenerator.targets file (adjust for correct version number) has lines to set the JavaVendor and JavaInstallation variables:
<Antlr4JavaVendor Condition="'$(Antlr4JavaVendor)'==''">JavaSoft</Antlr4JavaVendor>
<Antlr4JavaInstallation Condition="'$(Antlr4JavaInstallation)'==''">Java Runtime Environment</Antlr4JavaInstallation>
So, in my case at least, the appropriate registry settings were located in HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
To fix the incorrect registry:
Ensure that CurrentVersion's value (in my case 1.8.0_91) has a corresponding key
Ensure that the JavaHome key in HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.8.0_91 (replace with your version) has a directory path to a valid Java installation.
If you're running a 64b Windows, ensure this for both the 64b and 32b versions of the registry (see https://support.microsoft.com/fr-dz/help/305097/how-to-view-the-system-registry-by-using-64-bit-versions-of-windows for how to view the 32b registry on a 64b machine).
Keep in mind, that Visual Studio is a 32b process and that, by default, it will run Antlr4 by looking for a 32b version of the JRE. If, for some reason, you're building the solution outside of Visual Studio with 64b processes, the 64b version of the registry is used.
I am using Visual Studio 2022 and I had to compile a project that used Antlr4.4.5.3. The grammar file was configured to generate a Visitor but it did not work. I had the same error as you.
In my case I had an Open JDK in my JAVA_HOME environment variable. I also had an Oracle Java JDK installed. So, I deduced that Antl4 did not like my JAVA_HOME pointing to the Open JDK.
So I deleted the JDK and JRE folders (that pointed to the Open JDK) at HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft in the registry allowing me to compile my project successfully.
I deduce that Antlr then used the HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment folder where the configuration is set when you install an Oracle Java JDK version.

Programmatically retrieve version of an installed application

I want to programmatically retrieve the version of an installed application (which is currently running), of which I have the name of the running process. If possible, retrieving the install directory would also be appreciated, but that is optional.
I've searched at a lot of places, and some questions looked similar, but they do not give me what I ask for.
To be a bit more specific, right now I want to do this for Visual Studio i.e. I have a WPF app, which is running alongside Visual Studio & given that I know the process name for Visual Studio i.e. "devenv", how can I get the version information of Visual Studio installed on my machine, from the WPF app? This is just an example, don't assume anything particular to Visual Studio. In the general case, we'd have an app running, for which we know the Process name & want its installed version.
Can you please provide the C# code for doing this?
This is gonna be simple. All kind of system related information will be present in Registry. (i.e) If you open regedit, you may find various HKEY. Now, please navigate to the following location.
" HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall "
You can find many folders inside this location, in which the name of the folder will be encrypted. Those folders indicates the installed application in the current machine.
In each folder there will be many key and data pair of values. In that you can find DisplayName and DisplayVersion. So this DisplayVersion gives you the actual version of your application.
So, How to achieve this through code?
RegistryKey rKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
List<string> insApplication = new List<string>();
if (rKey != null && rKey.SubKeyCount > 0)
{
insApplication = rKey.GetSubKeyNames().ToList();
}
int i = 0;
string version = "";
foreach (string appName in insApplication)
{
RegistryKey finalKey = rKey.OpenSubKey(insApplication[i]);
string installedApp = finalKey.GetValue("DisplayName").ToString();
if (installedApp == "Google Chrome")
{
version = finalKey.GetValue("DisplayVersion").ToString();
return;
}
i++;
}
Process.GetProcessesByName("DevEnv")[0].Modules[0].FileVersionInfo
Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
This gets the version of the executing assembly.
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Public DTE As EnvDTE.DTE
Dim version As String
DTE = System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.9.0")
version = DTE.Version
MsgBox("The visual studio version is {0}", version)

Programatically checking files into TFS getting more than expected

So I have a .NET app which goes thru and generates a series of files, outputs them to a local directory and then determines if it needs to update an existing file or add a new file into a TFS (Team Foundation Server) project.
I have a single workspace on my local machine and there are 10 different working folders that are other coding projects I have worked on from this particular machine. My problem happens when I go to check if the file already exists in the TFS project and an update is required or if needs to be added to the project as a new file.
snipet:
static string TFSProject = #"$/SQLScripts/";
static WorkspaceInfo wsInfo;
static VersionControlServer versionControl;
static string argPath = "E:\\SQLScripts\\";
wsInfo = Workstation.Current.GetLocalWorkspaceInfo(argPath);
TeamFoundationServer tfs = new TeamFoundationServer(wsInfo.ServerUri.AbsoluteUri);
versionControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
Workspace workspace = versionControl.GetWorkspace(wsInfo);
workspace.GetLocalItemForServerItem(TFSProject);
At this point I check if the file exists and I do one of two things. if the file exists, then I mark the file for EDIT and then I writeout the file to the local directory, otherwise I will script the file first and then ADD the file to the workspace. I dont care if the physical file is identical to the one I am generating as I am doing this as a SAS70 requirement to 'track changes'
If it exists I do:
workspace.PendEdit(filename,RecurisionType.Full);
scriptoutthefile(filename);
or if it doesn't exist
scriptoutthefilename(filename);
workspace.PendAdd(filename,true);
Ok, all of that to get to the problem. When I go to check on pending changes against the PROJECT I get all the pending changes for all of the projects I have on my local machine in the workspace.
// Show our pending changes.
PendingChange[] pendingChanges = workspace.GetPendingChanges();
foreach (PendingChange pendingChange in pendingChanges)
{
dosomething...
}
I thought that by setting the workspace to workspace.GetLocalItemForServerItem(TFSProject) that it would give me ONLY the objects for that particular working folder.
If there any way to force the workspace object to only deal with a particular working folder?
Did that make any sense? Thanks in advance...
using LINQ you can get the pending changes of particular folder
PendingChange[] pendingChanges = workspace
.GetPendingChanges()
.Where(x => x.LocalOrServerFolder.Contains(argPath))
.ToArray();
Here is another way to refresh you workspace cache:
tf workspaces /s:http://SomeTFSServer:8080/
Also, Workspace has a method called UpdateWorkspaceInfoCache(..) that seems to do the same thing. I haven't tested this, though.
Ok, so it turned out that I had a corrupted TFS workspace cache on my machine.
Here was the solution (from a command prompt):
SET AppDataTF=%USERPROFILE%\Local Settings\Application Data\Microsoft\Team Foundation
SET AppDataVS=%APPDATA%\Microsoft\VisualStudio
IF EXIST "%AppDataTF%\1.0\Cache" rd /s /q "%AppDataTF%\1.0\Cache" > NUL
IF EXIST "%AppDataTF%\2.0\Cache" rd /s /q "%AppDataTF%\2.0\Cache" > NUL
IF EXIST "%AppDataVS%\8.0\Team Explorer" rd /s /q "%AppDataVS%\8.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\9.0\Team Explorer" rd /s /q "%AppDataVS%\9.0\Team Explorer" > NUL
The other part of the issue is that by having the project folder in the same workspace, it WILL pull in all pending changes from other projects. I created a secondary workspace with only the SQLScripts project and local folder and everything works like a charm.
Maybe someone else will find this useful...

Categories