How to get the solution path in c# - c#

I need to get the path where the solution file (.sln) is located. I try with this lines:
string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName,"abc.txt");
// Read the file as one string.
string text = System.IO.File.ReadAllText(startupPath);
When I run it, I get an "Unauthorized Access Exception". When I put the path "manually": C:\Users\yabej\source\repos\tutoriales\Proyecto 0.1 it works!
However I need an "automatic" solution to be sure that the path will be correct when I run my project on different computers

The proper way to get the right solution path worked for me in Visual Studio 2019 with the EnvDTE100 NuGet Package.
Clarification: Only works with a single VS Instance Open (credits #junliantolovich)
Be sure use the correct ProgId for your Visual Studio:
using System;
using EnvDTE80;
using System.IO;
using System.Runtime.InteropServices;
namespace Test
{
public class Program
{
public static void Main()
{
var di = GetSolutionDirInfo();
Console.WriteLine(di.FullName);
}
public static DirectoryInfo GetSolutionDirInfo()
{
// Use here the ProgId of your Visual Studio
// VS 2010 -> "VisualStudio.DTE.10.0"
// VS 2012 -> "VisualStudio.DTE.11.0"
// VS 2013 -> "VisualStudio.DTE.12.0"
// VS 2015 -> "VisualStudio.DTE.14.0"
// VS 2017 -> "VisualStudio.DTE.15.0"
// VS 2019 -> "VisualStudio.DTE.16.0"
var progId = "VisualStudio.DTE.16.0";
var dte2 = (DTE2)Marshal.GetActiveObject(progId);
return Directory.GetParent(dte2.Solution.FullName);
}
}
}

If you add your file (abc.txt) to your solution, then in the properties for the file, you can set 'Copy to output directory' to 'Copy always'. Make sure the build action is set to 'None'. Then during the build process, it'll be copied to the same location as your executable and you can get the path using
var path = Path.Combine(Directory.GetCurrentDirectory(), "\\abc.txt");

Related

How to add information from called method to Visual Studio Test output console in TFS 2018 R3

I try to add additional information to the output console or log file in TFS2018 from a called method, because of broken unit test only on the build server and too less information about exception.
Let's say we have a method (in this example properties):
public GsModule GdiModule
{
get
{
if (_gdiModule == null)
{
string directory = (new FileInfo(typeof(GsModule).Assembly.Location)).DirectoryName;
string path = Path.Combine(directory, "WinGDI.txv");
_gdiModule = (GsModule) SystemObjects.DynamicLinker.LoadModule(path, false, true);
}
return _gdiModule;
}
}
I would like to get information about the path and directory from this method in output in Visual Studio Test Task in Team Foundation Server 2018.
I tried with:
Trace.WriteLine($"GDI directory: {directory}"));
and NUinit.Framework
TestContext.WriteLine($"GDI directory: {directory}"));
but without success.
PS: The build is configurated to x64 | Release and <DefineConstants>TRACE</DefineConstants>
Do you have any idea how can I get this kind of information?

ResourceManager set wrong on save

I am having a issue where every time i change my resource files, the ResourceManager is set with a invalid path.
Example
namespace bundlrs_MVC6.Resources {
...
global::System.Resources.ResourceManager temp = new global::System.ResourceManager("bundlrs_MVC6.HomeIndexViewResources", typeof(HomeIndexViewResources).GetTypeInfo().Assembly);
Should be: (Note the extra Resources)
namespace bundlrs_MVC6.Resources {
...
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("bundlrs_MVC6.Resources.HomeIndexViewResources", typeof(HomeIndexViewResources).GetTypeInfo().Assembly);
Folder structure:
I am using Visual Studio 2015
Should i move all resource files to: namespace bundlrs_MVC6 instead of namespace bundlrs_MVC6.Resources if so, why?
This issue was fixed with the CoreCLR 1.0.0 RTM release

VSIX extension for VS2012 not running when debugging

I created a new VSIX extension project in Visual Studio 2012, and wrote a MEF classifier (as a test) that should simply highlight all text in a .mylang file. Here are the relevant parts of my .NET 4.5 code:
internal static class MyLangLanguage
{
public const string ContentType = "mylang";
public const string FileExtension = ".mylang";
[Export(typeof(ClassificationTypeDefinition))]
[Name(ContentType)]
[BaseDefinition("code")]
internal static ContentTypeDefinition MyLangSyntaxContentTypeDefinition = null;
[Export]
[FileExtension(FileExtension)]
[ContentType(ContentType)]
internal static FileExtensionToContentTypeDefinition MyLangSyntaxFileExtensionDefinition = null;
}
[Export(typeof(IClassifierProvider))]
[ContentType(MyLangLanguage.ContentType)]
[Name("MyLangSyntaxProvider")]
internal sealed class MyLangSyntaxProvider : IClassifierProvider
{
[Import]
internal IClassificationTypeRegistryService ClassificationRegistry = null;
public IClassifier GetClassifier(ITextBuffer buffer)
{
return buffer.Properties.GetOrCreateSingletonProperty(() => new MyLangSyntax(ClassificationRegistry, buffer));
}
}
internal sealed class MyLangSyntax : IClassifier { }
Here is the full code.
These are the relevant parts from my source.extension.vsixmanifest file. Based on suggestions and similar files I found across the web, I added the dependency on MPF and the two assets.
<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<!-- ... -->
<Dependencies>
<Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="4.5" />
<Dependency d:Source="Installed" Id="Microsoft.VisualStudio.MPF.11.0" DisplayName="Visual Studio MPF 11.0" Version="[11.0,12.0)" />
</Dependencies>
<Assets>
<Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" />
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" />
</Assets>
</PackageManifest>
I also tried a version 1.0 manifest:
<?xml version="1.0" encoding="utf-8"?>
<Vsix Version="1.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2010">
<!-- ... -->
<References />
<Content>
<MefComponent>|%CurrentProject%|</MefComponent>
</Content>
</Vsix>
When I run it, it starts an experimental instance of Visual Studio 2012, and the Extensions and Updates window shows that my extension is active. However, it does not do anything when I load or create a .mylang file. Any exceptions I throw (as a test) from my extension are never thrown. Breakpoints are never hit, and get an exclamation mark with the following warning:
The breakpoint will not currently be hit. No symbols have been loaded for this document.
It feels as if my extension is never really loaded at all. My problem is similar to this problem and this problem, but I'm using Visual Studio 2012 which uses a new VSIX manifest format.
What I know:
I can find my DLL and VSIX file in the %localappdata%\Microsoft\VisualStudio\11.0Exp\Extensions\MyLang\VSIXProject1\1.0 folder, so I know they are copied.
Their timestamp corresponds to when I last built the project, so I know they are up-to-date.
Project Properties > Debug > Start external program: is already automatically set to C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe, and the Command line arguments were automatically set to /rootsuffix Exp.
The Visual Studio log (created with the /log option) has two entries related to my extension: Successfully loaded extension... and Extension is enabled....
My DLL does not appear on the Modules tab (list of all loaded DLLs) of the debugging Visual Studio, while some (not all) other extensions do appear.
It doesn't get loaded in Visual Studio 2012 or 2010 both on my laptop and my desktop PC.
What I've tried:
Set <IncludeAssemblyInVSIXContainer> to true in the .csproj file, per this suggestion, but it did not make any difference.
I can't add the line <MefComponent>|%CurrentProject%|</MefComponent> to the source.extension.vsixmanifest file as it uses a different format (2.0) than VSIX projects for previous versions of Visual Studio (1.0).
This suggestion (setting IncludeAssemblyInVSIXContainer and friends in my .csproj to true) but it does not make a difference. And my breakpoints are still showing the warning and not being hit.
Reset the VS Experimental instance using the Reset the Visual Studio 2012 Experimental Instance shortcut in the Start Menu, as per this suggestion. It didn't make a difference.
How can I at the very least be sure my VSIX MEF extension is loaded and works? And if possible, how can I make by breakpoint work and debug it?
Edit: The problem is you've improperly exported your ContentTypeDefinition as a ClassificationTypeDefinition. You should use the following instead:
[Export] // <-- don't specify the type here
[Name(ContentType)]
[BaseDefinition("code")]
internal static ContentTypeDefinition MyLangSyntaxContentTypeDefinition = null;
Here's my two guesses right now:
Try removing the following line from your vsixmanifest. I assume you do not have a class in your project that extends Package, in which case Visual Studio might be refusing to load your package due to the following Asset line (your extension does not actually provide this asset).
<Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" />
If that fails, try replacing your current source.extension.vsixmanifest with one written to the old schema (version 1.0). I know this form still works in Visual Studio 2012 because all ~20 extensions I work on (with >10 public releases) use the old schema.
280Z28 solved the problem! For completeness, this is the full tried and tested code that will create a super simple VSIX Visual Studio MEF extension that colors all text in a .mylang file blue (or whatever the current keyword color is).
How to create a simple coloring MEF VSIX extension
Make sure you have the Visual Studio SDK installed. (VS2010 SP1 SDK, VS2012 SDK)
Create a new VSIX Project(From the template under Installed → Templates → Visual C# → Extensibility.)
Enter something in the Author field of the VSIX manifest editor, then save and close it.
Add references to the following libraries,version 10.0.0.0 for VS2010, or 11.0.0.0 for VS2012:
Microsoft.VisualStudio.CoreUtility.dll
Microsoft.VisualStudio.Language.StandardClassification.dll
Microsoft.VisualStudio.Text.Data.dll
Microsoft.VisualStudio.Text.Logic.dll
Microsoft.VisualStudio.Text.UI.dll
Microsoft.VisualStudio.Text.UI.Wpf.dll
Add a reference to the following library:
System.ComponentModel.Composition.dll version 4.0.0.0
Create and add a new code file MyLang.cs, and copy-and-paste the code below in it.
Edit source.extension.vsixmanifest as XML.
For Visual Studio 2010, add the following XML just before the closing tag </Vsix>, and save:
<Content>
<MefComponent>|%CurrentProject%|</MefComponent>
</Content>
(If there is already an empty <Content/>, remove it.)
For Visual Stuio 2012, add the following XML just before the closing tag </PackageManifest>, and save:
<Assets>
<Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" />
</Assets>
(If there is already an empty <Assets/>, remove it.)
Only for Visual Studio 2010:
Unload the VSIX project (right-click the project → Unload project).
Edit the .csproj project file (right-click the project → Edit MyProject.csproj).
Change the value at <IncludeAssemblyInVSIXContainer> to true.
Save and close the file.
Reload the VSIX project (right-click the project → Reload project).
Now build and run it. When you load a .mylang file, all text should be colored blue (or whatever the default keyword color is).
MyLang.cs
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
namespace VSIXProject1
{
internal static class MyLangLanguage
{
public const string ContentType = "mylang";
public const string FileExtension = ".mylang";
[Export]
[Name(ContentType)]
[BaseDefinition("code")]
internal static ContentTypeDefinition MyLangSyntaxContentTypeDefinition = null;
[Export]
[FileExtension(FileExtension)]
[ContentType(ContentType)]
internal static FileExtensionToContentTypeDefinition MyLangSyntaxFileExtensionDefinition = null;
}
[Export(typeof(IClassifierProvider))]
[ContentType(MyLangLanguage.ContentType)]
[Name("MyLangSyntaxProvider")]
internal sealed class MyLangSyntaxProvider : IClassifierProvider
{
[Import]
internal IClassificationTypeRegistryService ClassificationRegistry = null;
public IClassifier GetClassifier(ITextBuffer buffer)
{
return buffer.Properties.GetOrCreateSingletonProperty(() => new MyLangSyntax(ClassificationRegistry, buffer));
}
}
internal sealed class MyLangSyntax : IClassifier
{
private ITextBuffer buffer;
private IClassificationType identifierType;
private IClassificationType keywordType;
public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged;
internal MyLangSyntax(IClassificationTypeRegistryService registry, ITextBuffer buffer)
{
this.identifierType = registry.GetClassificationType(PredefinedClassificationTypeNames.Identifier);
this.keywordType = registry.GetClassificationType(PredefinedClassificationTypeNames.Keyword);
this.buffer = buffer;
this.buffer.Changed += OnBufferChanged;
}
public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan snapshotSpan)
{
var classifications = new List<ClassificationSpan>();
string text = snapshotSpan.GetText();
var span = new SnapshotSpan(snapshotSpan.Snapshot, snapshotSpan.Start.Position, text.Length);
classifications.Add(new ClassificationSpan(span, keywordType));
return classifications;
}
private void OnBufferChanged(object sender, TextContentChangedEventArgs e)
{
foreach (var change in e.Changes)
ClassificationChanged(this, new ClassificationChangedEventArgs(new SnapshotSpan(e.After, change.NewSpan)));
}
}
}
Set <IncludeAssemblyInVSIXContainer> to true in the .csproj file, per
this suggestion.
I had exactly the same problem and this solved it. Do a full rebuild.

Rlapack.dll is missing from your computer - c# and R

When I run a c# application through Visual Studio 2010, where R is integrated, I get the error: The program can't start because Rlapack.dll is missing from your computer. Try reinstalling the program to fix this problem.
I tried reinstalling the program but it did not work.
I also tried putting it in the folder that has the Matrix in it but it did not work. This solution was suggested in StackOverflow Q.
I am running 64-bit Windows 7! The application is 32-bit.
There are two dll's. One in a folder called i386, and another one in the folder x64.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RDotNet;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string dlldir = #"D:\Program Files\R-2.15.0\bin\i386";
bool r_located = false;
while (r_located == false)
{
try
{
REngine.SetDllDirectory(dlldir);
REngine.CreateInstance("RDotNet");
r_located = true;
}
catch
{
MessageBox.Show(#"Unable to find R installation's \bin\i386 folder.
Press OK to attempt to locate it.");
}
}
}
}
}
I realize this has been answered, but that was back in 2012. For anyone still having this problem with R version 3.4.3 or later in 2018, especially while trying to follow the simple example from the r.net home page, below is what I did to fix it:
In your code, before the line REngine engine = REngine.GetInstance();, add this line REngine.SetEnvironmentVariables(#"C:\Program Files\R\R-3.4.3\bin\x64", #"C:\Program Files\R\R-3.4.3");.
right click project, go to build and uncheck "Prefer 32-bit".
copy Rlapack.dll from C:\Program Files\R\R-3.4.3\bin\i386
paste in both C:\Program Files\R\R-3.4.3\library\stats\libs\i386 and C:\Program Files\R\R-3.4.3\library\Matrix\libs\i386
copy Rlapack.dll from C:\Program Files\R\R-3.4.3\bin\x64
paste in both C:\Program Files\R\R-3.4.3\library\stats\libs\x64 and C:\Program Files\R\R-3.4.3\library\Matrix\libs\x64.
Such a pain, but that is what finally got it to work for me.
Here is what I just did and it worked: I put the dll in the bin folder of my application.
Try setting path variable before caling the dll:
var envPath = Environment.GetEnvironmentVariable("PATH");
string s = null;
if (Environment.Is64BitProcess)
s = #"C:\Program Files\R\R-2.15.0\bin\x64";
else
s = #"C:\Program Files\R\R-2.15.0\bin\i386";
Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + s);

Visual Studio Addin "Exclude From Build" Property

I am currently trying to create an addin for Visual Studio 2008 that will list all files which are not excluded from the current build configuration.
I currently have test C++ console application that has 10 files, 2 of which are "Excluded From Build". This is a property that will allow a specific file to be excluded from a specific configuration (i.e. Debug or Release). This property is located when you right click on a file in the solution explorer and select Properties->Configuration Properties->General->Excluded From Build
At the moment I have the following code that will loop though all project files and get the properties for each file.
foreach (Project theProject in _applicationObject.Solution.Projects)
{
getFiles(theProject.ProjectItems);
}
private void getFiles(ProjectItems theItems)
{
foreach (ProjectItem theItem in theItems)
{
string theItemName = theItem.Name;
foreach (Property theProp in theItem.Properties)
{
string thePropName = theProp.Name;
}
getFiles(theItem.ProjectItems);
}
}
The issue I am having is that I cant seem to find the "Excluded From Build" property. I cannot find very good documentation on what properties are listed where. Where is this Excluded From Build property located within the _applicationObject object?
I'm not familiar with the Visual Studio object model, but in the documentation for VS2005 the following objects have an ExcludedFromBuild property:
VCFileConfiguration
VCFileConfigurationProperties
VCPreBuildEventTool
VCPreLinkEventTool
VCPostBuildEventTool
VCWebDeploymentTool
Hopefully this will lead you down the right path.

Categories