Create a solution and add a project using "VisualStudio.DTE.10.0" - visual-studio-2010

I'm trying to create a VS2010 solution and add a project from a stand-alone app (not an add-in). I can create an instance of VS2010, but I'm not able to determine how to create a project properly...I can only find an example of how to create a project using the EnvDTE80 object, which later causes an exception because the project file is in an earlier format and needs to be upgraded. I have this:
EnvDTE80.DTE2 dte2;
object obj;
System.Type t;
t = System.Type.GetTypeFromProgID("VisualStudio.DTE.10.0", true);
obj = System.Activator.CreateInstance(t, true);
dte2 = (EnvDTE80.DTE2)obj;
What I'm looking for is the equivalent of something like "EnvDTE100.DTE2" but don't know how to get there.
Thanks

You do not have to go via DTE object. The treatment to the object solution4 it's different you should do this
Type latestSolution = Type.GetTypeFromProgID("VisualStudio.10.0", true);
EnvDTE100.Solution4 vsSolution = (EnvDTE100.Solution4)Activator.CreateInstance(latestSolution, true);

I think I'm doing something similar, I have a application that creates a solution and loads two projects from templates that I created in VS2010. You're right in that it seems everything still uses the EnvDTE80, even in VS2010, but then we use it to create a 2010 solution:
System.Type type = System.Type.GetTypeFromProgID("VisualStudio.DTE.10.0");
Object obj = System.Activator.CreateInstance(type, true);
EnvDTE80.DTE2 dte2 = (EnvDTE80.DTE2)obj;
EnvDTE100.Solution4 soln = (EnvDTE100.Solution4)dte2.Solution;
Then you can call methods on the soln object to create your project (in my case its AddFromTemplate).

Related

Windows 8 Store app, Type.IsClass and System.ComponentModel.DesignerProperties.IsInDesignTool missing

I am investigating Windows 8 Store app development, and am having trouble locating the following members
Type.IsClass
System.ComponentModel.DesignerProperties.IsInDesignTool
Visual studio claims they don't exist, but MSDN suggests they should.
I am obviously missing something silly: Can anyone point me in the right direction please?
Regards
John.
The IsClass property has moved to the TypeInfo class. Basically you need to replace;
bool result = type.IsClass;
with;
bool result = type.GetTypeInfo().IsClass;
GetTypeInfo() is an extension method from the System.Reflection namespace, no not obviously visible on System.Type unless you're already using System.Reflection.
The IsInDesignTool property has moved to another place too and changed name;
bool result = Windows.ApplicationModel.DesignMode.DesignModeEnabled;

Can't make MVC4 WebApi include null fields in JSON

I'm trying to serialize objects as JSON with MVC4 WebAPI (RTM - just installed VS2012 RTM today but was having this problem yesterday in the RC) and I'd like for all nulls to be rendered in the JSON output.
Like this:
[{"Id": 1, "PropertyThatMightBeNull": null},{"Id":2, "PropertyThatMightBeNull": null}]
But what Im getting is
[{"Id":1},{"Id":2}]
I've found this Q/A WebApi doesnt serialize null fields but the answer either doesn't work for me or I'm failing to grasp where to put the answer.
Here's what I've tried:
In Global.asax.cs's Application_Start, I added:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;
json.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include;
This doesn't (seem to) error and seems to actually execute based on looking at the next thing I tried.
In a controller method (in a subclass of ApiController), added:
base.Configuration.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;
base.Configuration.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include;
I say #1 executed because both values in #2 were already set before those lines ran as I stepped through.
In a desperation move (because I REALLY don't want to decorate every property of every object) I tried adding this attrib to a property that was null and absent:
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Include,
NullValueHandling = NullValueHandling.Include)]
All three produce the same JSON with null properties omitted.
Additional notes:
Running locally in IIS (tried built in too), Windows 7, VS2012 RTM.
Controller methods return List -- tried IEnumerable too
The objects I'm trying to serialize are pocos.
This won't work:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;
But this does:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings()
{
NullValueHandling = Newtonsoft.Json.NullValueHandling.Include
};
For some odd reason the Newtonsoft.Json.JsonFormatter ignore assigments to the propreties os SerializerSettings.
In order to make your setting work create new instance of .SerializerSettings as shown below:
config.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Include,
};
I finally came across this http://forums.asp.net/t/1824580.aspx/1?Serializing+to+JSON+Nullable+Date+gets+ommitted+using+Json+NET+and+Web+API+despite+specifying+NullValueHandling which describes what I was experiencing as a bug in the beta that was fixed for the RTM.
Though I had installed VS2012 RTM, my project was still using all the nuget packages that the beta came with. So I nugetted (nugot?) updates for everything and all is now well (using #1 from my question). Though I'm feeling silly for having burned half a day.
When I saw this answer I was upset because I was already doing this and yet my problem still existed. My problem rooted back to the fact that my object implemented an interface that included a nullable type, so, I had a contract stating if you want to implement me you have to have one of these, and a serializer saying if one of those is null don't include it. BOOM!

How can I add an MSBuild Import with IVsBuildPropertyStorage?

I'm trying to add an Import task to a .csproj file programmatically, but I don't want to use the Microsoft.Build.BuildEngine objects to do this because VS will then pop up warnings about the project file being modified from outside of Visual Studio.
I've seen a few pages [1] [2] suggesting that the IVsBuildPropertyStorage interface will let me access the MSBuild parts of the .csproj file, but I'm having trouble figuring out how to do this, or if it's even possible really. It looks like I need to specify the name of the property I want to access, but I'm not sure how to figure that out. Calling GetPropertyValue() for an "Import" property doesn't return anything for project files that are already set up how I want my final results to look:
EnvDTE.Project proj = ...;
var sol = Package.GetGlobalService(typeof(VsSolution)) as IVsSolution;
IVsHierarchy hier;
sol.GetProjectOfUniqueName(p.UniqueName, out hier);
var storage = hier as IVsBuildPropertyStorage;
string val;
storage.GetPropertyValue("Import", String.Empty,
(uint)_PersistStorageType.PST_PROJECT_FILE, out val);
// val is null
[1] https://mpfproj.svn.codeplex.com/svn/9.0/Tests/UnitTests/ProjectTest.cs
[2] http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/e1983591-120a-4a2f-a910-e596dd625e68
Thanks. I'd appreciate any suggestions I can get with this.
I asked a similar question see here Programmatically adding and editing the Targets in a Visual Studio Project File What you can do to add an import to the project file programmatically is to use this namespace http://msdn.microsoft.com/en-us/library/microsoft.build.construction.aspx which is from the assembly (in the GAC) Microsoft.Build.dll. You can accomplish this in about 3-4 steps:
the following is pseudo code:
Get the Project File location using the DTE.ActiveSolutionProjects and getting the Properties of each Project. Get the FullPath and the FileName to get the full path of the project file.
Once you have the full path of the project file, call the ProjectRootElement.Open static method:
ProjectRootElement project = ProjectRootElement.Open(projectPath);
Once you have the ProjectRootElement reference, you can call the AddImport method (where name is the Project Identifier Attribute):
project.AddImport(name)
That should do it.
Import element is not a Property element in MSBuild nor and Item one.
I think you can't add an Import using IVsBuildPropertyStorage.

Copy object values in Visual Studio debug mode

In Visual Studio debug mode it's possible to hover over variables to show their value and then right-click to "Copy", "Copy Expression" or "Copy Value".
In case the variable is an object and not just a basic type, there's a + sign to expand and explore the object. It there a way to copy all that into the clipboard?
In the immediate window, type
?name_of_variable
This will print out everything, and you can manually copy that anywhere you want, or use the immediate window's logging features to automatically write it to a file.
UPDATE: I assume you were asking how to copy/paste the nested structure of the values so that you could either search it textually, or so that you can save it on the side and then later compare the object's state to it. If I'm right, you might want to check out the commercial extension to Visual Studio that I created, called OzCode, which lets you do these thing much more easily through the "Search" and "Compare" features.
UPDATE 2 To answer #ppumkin's question, our new EAP has a new Export feature allows users to Export the variable values to Json, XML, Excel, or C# code.
Full disclosure: I'm the co-creator of the tool I described here.
You can run below code in immediate window and it will export to an xml file the serialized XML representation of an object:
(new System.Xml.Serialization.XmlSerializer(obj.GetType())).Serialize(new System.IO.StreamWriter(#"c:\temp\text.xml"), obj)
Source: Visual Studio how to serialize object from debugger
Most popular answer from https://stackoverflow.com/a/23362097/2680660:
With any luck you have Json.Net in you appdomain already. In which
case pop this into your Immediate window:
Newtonsoft.Json.JsonConvert.SerializeObject(someVariable)
Edit: With .NET Core 3.0, the following works too:
System.Text.Json.JsonSerializer.Serialize(someVariable)
There is a extension called Object Exporter that does this conveniently.
http://www.omarelabd.net/exporting-objects-from-the-visual-studio-debugger/
Extension: https://visualstudiogallery.msdn.microsoft.com/c6a21c68-f815-4895-999f-cd0885d8774f
You can add a watch for that object, and in the watch window, expand and select everything you want to copy and then copy it.
By using attributes to decorate your classes and methods you can have a specific value from your object display during debugging with the DebuggerDisplay attribute e.g.
[DebuggerDisplay("Person - {Name} is {Age} years old")]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
I always use:
string myJsonString = JsonConvert.SerializeObject(<some object>);
Then I copy the string value which unfortunately also copies the back slashes.
To remove the backlashes go here:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace
Then within the <p id="demo">Visit Microsoft!</p> element replace the text with the text you copied.
then replace the var res = str.replace("Microsoft", "W3Schools"); line with
var res = str.replace(/\\/g, '')
Run these new changes but don't forget to click the "try it" button on the right.
Now you should have all the text of the object in json format that you can drop in a json formatter like http://jsonformatter.org or to create a POCO you can now use http://json2csharp.com/
ObjectDumper.NET
This is an awesome way!
You probably need this data for a unit test, so create a Sandbox.cs temporary test or you can create a Console App.
Make sure to get NuGet package, ObjectDumper.NET, not ObjectDumper.
Run this test (or console app)
View test output or text file to get the C# initializer code!
Code:
[TestClass]
public class Sandbox
{
[TestMethod]
public void GetInitializerCode()
{
var db = TestServices.GetDbContext();
var list = db.MyObjects.ToList();
var literal = ObjectDumper.Dump(list, new DumpOptions
{
DumpStyle = DumpStyle.CSharp,
IndentSize = 4
});
Console.WriteLine(literal); // Some test runners will truncate this, so use the file in that case.
File.WriteAllText(#"C:\temp\dump.txt", literal);
}
}
I used to use Object Exporter, but it is 5 years old and no longer supported in Visual Studio. It seems like Visual Studio Extensions come and go, but let's hope this NuGet package is here to stay! (Also it is actively maintained as of this writing.)
Google led me to this 8-year-old question and I ended up using ObjectDumper to achieve something very similar to copy-pasting debugger data. It was a breeze.
I know the question asked specifically about information from the debugger, but ObjectDumper gives information that is basically the same. I'm assuming those who google this question are like me and just need the data for debugging purposes and don't care whether it technically comes from the debugger or not.
I know I'm a bit late to the party, but I wrote a JSON implementation for serializing an object, if you prefer to have JSON output. Uses Newtonsoft.Json reference.
private static void WriteDebugJSON (dynamic obj, string filePath)
{
using (StreamWriter d = new StreamWriter(filePath))
{
d.Write(JsonConvert.SerializeObject(obj));
}
}
I've just right clicked on the variable and selected AddWatch, that's bring up watch window that consists of all the values. I selected all and paste it in a text a text editor, that's all.
Object Dumper is a free and open source extension for Visual Studio and Visual Studio Code.
"Dump as" commands are available via context menu in the Code and Immediate windows.
It's exporting objects to:
C# object initialization code,
JSON,
Visual Basic object initialization code,
XML,
YAML.
I believe that combined with the Diff tool it can be helpful.
I'm the author of this tool.
if you have a list and you want to find a specific variable:
In the immediate window, type
myList.Any(s => s.ID == 5062);
if this returns true
var myDebugVar = myList.FirstOrDefault(s => s.ID == 5062);
?myDebugVar
useful tips here, I'll add my preference for when i next end up here asking this question again in the future.
if you don't mind adding an extension that doesn't require output files or such there's the Hex Visualizer extension for visual studio, by mladen mihajlovic, he's done versions since 2015.
provides a nice display of the array via the usual magnifine glass view object from the local variables window.
https://marketplace.visualstudio.com/items?itemName=Mika76.HexVisualizer2019 is the 2019 version.
If you're in debug mode, you can copy any variable by writing copy() in the debug terminal.
This works with nested objects and also removes truncation and copies the complete value.
Tip: you can right click a variable, and click Copy as Expression and then paste that in the copy-function.
System.IO.File.WriteAllText("b.json", page.DebugInfo().ToJson())
Works great to avoid to deal with string debug format " for quote.
As #OmerRaviv says, you can go to Debug → Windows → Immediate where you can type:
myVariable
(as #bombek pointed out in the comments you don't need the question mark) although as some have found this limits to 100 lines.
I found a better way was to right click the variable → Add Watch, then press the + for anything I wanted to expand, then used #GeneWhitaker's solution, which is Ctrl+A, then copy Ctrl+C and paste into a text editor Ctrl+V.

Visual Studio 2008 Add-In Check if Hierarchy Item is solution folder

I've got a visual studio addin written by developer who is no longer at the company and have no idea how to debug it. But I want to add a feature so it can recurse into solution folders.
Sounds simple but I'm not sure the api allows testing for this?
Well there's got to be a way because AnkhSVN and VisualSVN work fine with Solution Folders.
StackOverflow I'm reaching out for some help on this issue.
Thanks
Notes
-We are using solution folders to hide "Dependency Projects" which are basically a list of project references that we probably don't care about in the particular solution and want to hide by default.
public class Connect : IDTExtensibility2, IDTCommandTarget
{
public void GetProjectLocations(DTE2 dte)
{
UIHierarchy UIH = dte.ToolWindows.SolutionExplorer;
try
{
UIHierarchyItem UIHItemd = UIH.UIHierarchyItems.Item(1);
}
catch (Exception E)
{
Debug.Write(E);
}
UIHierarchyItem UIHItem = UIH.UIHierarchyItems.Item(1);//this looks suspect to me
// Iterate through first level nodes.
for (int i = 1; i <= UIHItem.UIHierarchyItems.Count; i++)
{
Project TempGeneralProjObj = dte.Solution.Item(i);
if (TempGeneralProjObj.Kind == PrjKind.prjKindCSharpProject)
{
}
}
}
}
So far from my tests it appears that solution folders will cast to type Project surprisingly and once that is done the Project.ProjectItems property will hold a list of Projects that may exists underneath that folder. So in short, this is one way to at least get information about how things are structured. The problem however is that each ProjectItem located underneath a solution folder appears to cast find to type ProjectItem but doesn't seem to be able to be cast to a Project.
This is how I'm currently detecting a solution folder in my loop.
if(project.Kind == "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}")
{
// TODO: Do your thing
}
This has also been frustrating me and I've also noticed a bug in how ActiveReports handles solution folders as well which is related to this same issue.
UPDATE!
Ok so I found the solution but I can't claim it 100% because I found most of it at Macaw's Blog.
So it appears that my original findings were right on however in order to get the actual project type for each ProjectItem under the solution item you need to look under the ProjectItem.SubProject property.
Now Macaw takes a recursive approach to walking the project structure which I think I would also normally recommend however in my case I wanted a single method implementation to simply log out an XML representation of the project for simple research purposes so I ended up using a Stack implementation. For reference you can find my code below which is successfully handling at least one level of solution folders full of projects only and no other specialty solution items.
XElement rootNode = new XElement("Solution");
rootNode.Add(new XAttribute("Name", _applicationObject.Solution.FullName));
Stack<Project> projectStack =
new Stack<Project>(_applicationObject.Solution.Projects.Cast<Project>());
while(projectStack.Count > 0)
{
var project = (Project)projectStack.Pop();
var solutionItemName = "Project";
if(project.Kind == "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}")
{
foreach(ProjectItem innerProject in project.ProjectItems)
{
if(innerProject.SubProject != null)
{
projectStack.Push(innerProject.SubProject);
}
}
solutionItemName = "Folder";
}
var projectNode = new XElement(
solutionItemName,
new XAttribute("Name", project.Name),
new XAttribute("Kind", project.Kind)
);
rootNode.Add(projectNode);
foreach(ProjectItem item in project.ProjectItems)
{
var itemNode = new XElement("Item", new XAttribute("Name", item.Name));
projectNode.Add(itemNode);
if(item.Properties == null)
{
continue;
}
foreach(Property property in item.Properties)
{
var propertyNode = new XElement(property.Name, property.Value);
itemNode.Add(propertyNode);
}
}
}
By the fact of this post and by apparent bugs in other Add-ins it is apparent that this isn't the most intuitive design but thats what we have to live with.
To debug a Visual Studio add-in, load the source code into a copy of visual studio that is not running the add-in. Then, configure the project to start a second copy of visual studio when you "run" the project, that second copy will then run with the first able to breakpoint and debug it.
Make sure you have a batch file (or equivalent) to clean up, so that you can always get back to running VS without the plugin.
Useful resources ...
How to debug a Visual Studio .NET 2005 Add-In
Walkthrough: Debugging an Add-in Project

Resources