Generating code for service proxies - visual-studio-2010

I'm trying to generate some additional code base on the auto-generated webservice proxies in my VS2010 solution, I'm using a T4 template to do so.
The problem is, automatically generated proxies are added in "Service Reference" folder but ProjectItems (files) are hidden by default and the following code does not find them in the project structure:
var sr = GetProjectItem(project, "Service References");
if(sr != null)
{
foreach(ProjectItem item in sr.ProjectItems)
{
foreach(var file in item.ProjectItems)
{
//Services.Add(new ServiceInfo { Name = file.Name });
}
}
}
The above code runs and although service reference is found, and there are ProjectItems under that node (named by the webservice reference name), under object under that node is of type System.__ComObject and I'm not sure how to progress.
Any help is appreciated.

It turns out I figured out how to fix this right after posting it here!
The problem was I was using the "var" keyword in second loop, and casting the "file" variable to "ProjectItem" work just like first loop.

Related

T4 iterate over projects in solution folders

I have a T4 template which generates my fluent builder classes for my api-contracts. So when i have a contract CreatePersonRequest which has a name and a firstname, i generate a CreatePersonRequestBuilder which makes the CreatePersonRequest.
This way my builders are always up to date and by inheriting one of these I can make easily various pre-filled objects with a nice syntax.
This works fine when my projects are all located in root of my solution. Once i started to add some solution folders, this didn't work anymore.
public EnvDTE.Project GetProjectByName(string projectName) {
var serviceProvider = (IServiceProvider)this.Host;
var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE));
var solution = dte.Solution;
foreach (Project p in solution.Projects)
{
if (p != null) {
if (p.Name == projectName){
return p;
}
}
}
return null;
}
I retrieve all my projects from my solutions in the beginning and then iterate over these and verify the name. Apparantly the word 'project' here can also means solution folder.
Pretty easy fix I thought. Check the kind of the project (can be a project/folder/....) and in case of a folder go deeper into the ProjectItems hierarchy.
The problem I now have is that I have ProjectItem which is an interface (and not implemented by Project). So I have no way to convert this ProjectItem to a Project (altough the ProjectItem.Kind property tells me it is a Project).
How can i retrieve projects deeper into the Solution hierarchy?

When I set the CanonicalKey or CanonicalUrl for a dynamic node, I get a NullReferenceException

I'm using MVCSiteMapProvider v4.6.22 and have a dynamic node provider for one of my controllers.
Something like:
public class ProviderDetailsNodeProvider : DynamicNodeProviderBase
{
public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
{
foreach (var provider in providers)
{
var dn = new DynamicNode()
{
Title = provider.Name,
ParentKey = "ParentKey",
Key = $"provider_master_{provider.ID}",
CanonicalUrl = "/url/something"
};
dn.RouteValues.Add("myRouteParamName", "myRouteParamValue");
yield return dn;
}
}
}
Without setting the CanonicalKey or CanonicalUrl properties of the DynamicNode, I get the correct behaviour. However I now wish to have multiple URLs pointing at the same content so I need to utilise the Canonical URL features of MVCSiteMapProvider.
If I attempt to set the CanonicalUrl as in the above snippet, or the CanonicalKey (my preferred choice), then when I attempt to use the helper methods, such as:
#Html.MvcSiteMap().SiteMapPath()
I get a NullReferenceException - it's the #Html.MvcSiteMap() which returns null.
What am I doing incorrectly, why do I get this NullReferenceException just by setting these properties against my dynamic nodes?
I'm using the MvcSiteMapProvider.MVC5 package, in an MVC6 application. I can't see a newer version on Nuget.
MVC 6 is not yet supported, as per the issue on NuGet.

Selection of a property in a compartment shape

I have a problem with selecting a property on a compartmentshape of a dsl. What I want to do is:
I have a DSL with one compartmentshape which has many properties in one compartment. Each of this properties has a textfield which is used for saving c# code. I compile this code and add the error tasks to the error list. I added an event handler for the navigate event of the error task. Inside this handler, i would like to select the property of the compartmentshape which is responsible for the error. I tried many things, but didn't succeeded. This is my current selection logic:
public void Select(Rule rule)
{
Library.Field ruleField = rule.Field as Library.Field;
var ruleFieldPresentation = PresentationViewsSubject.GetPresentation(ruleField as ModelElement).FirstOrDefault() as ShapeElement;
VSDiagramView activeDiagramView = Diagram.ActiveDiagramView as VSDiagramView;
if (activeDiagramView != null)
{
var docView = activeDiagramView.DocView;
activeDiagramView.Selection.Clear();
docView.CurrentDiagram.ActiveDiagramView.Selection.Set(new DiagramItem(ruleFieldPresentation));
}
}
The problem seems that an property of the compartmentshape doesn't have a presentationview, because I'm not able to get it.
I would be glad and very grateful if someone can helpe me with this problem.
Thank you
Regards Manuel
I wanted to open an error from the error list. There is a better solution than using the navigation event on an error. The better solution is to add a validation rule to the domain class and add the error with the context to the error list. Than the navigation to the property works out of the box.
context.LogError(errorDescription, "GAIN001RuleCompilationError", Field);

how to disable T4 template auto-run in visual studio (2012)?

I have some T4 templates in my project. Whenever I make changes and save the tt file, it auto update the generated files. This is a template that loops all tables in a database and generates about 100+ files. So visual studio hangs for a few seconds every time I save my template and this is annoying. Is there a way to disable to "auto-refresh" function and I can manually run the template through the context menu.
Thanks!
You could delete TextTemplatingFileGenerator under "Custom Tool" in the file's Properties while you are editing it, and then put it back when you are finished.
I had a similiar issue. I found a quick work around by creating a ttinclude file (actually this was already a standard include file containing utility functions for my templates) and including it in all of my T4 templates. Then I simply created a compiler error in the include file. Thus when the generator attempted to run it would simply fail on the compile. Then when I'm ready to actually generate, I get rid of the offending code and then generate.
e.g. To cause a failure:
<#+
#
#>
To disable the failure:
<#+
//#
#>
You can also use this trick in the T4 template itself if you just want to disable the one you're working on.
Hopefully future VS versions will allow you to simply disable the auto-transform.
Since the TT is always executed (still), I found a different way to control the output when the TT is executed.
/********SET THIS TO REGENERATE THE FILE (OR NOT) ********/
var _RegenerateFile = true;
/********COS VS ALWAYS REGENERATES ON SAVE ***************/
// Also, T4VSHostProcess.exe may lock files.
// Kill it from task manager if you get "cannot copy file in use by another process"
var _CurrentFolder = new FileInfo(Host.ResolvePath(Host.TemplateFile)).DirectoryName;
var _AssemblyLoadFolder = Path.Combine(_CurrentFolder, "bin\\Debug");
Directory.SetCurrentDirectory(_CurrentFolder);
Debug.WriteLine($"Using working folder {_CurrentFolder}");
if (_RegenerateFile == false)
{
Debug.WriteLine($"Not Regenerating File");
var existingFileName = Path.ChangeExtension(Host.TemplateFile, "cs");
var fileContent = File.ReadAllText(existingFileName);
return fileContent;
}
Debug.WriteLine($"Regenerating File"); //put the rest of your usual template
Another way (what I eventually settled on) is based on reading a conditional compilation symbol that sets a property on one of the the classes that is providing the data for the T4. This gives the benefit of skipping all that preparation (and IDE lag) unless you add the REGEN_CODE_FILES conditional compilation symbol. (I guess this could also be made into a new solution configuration too. yes, this does work and removes the need for the class change below)
An example of the class i am calling in the same assembly..
public class MetadataProvider
{
public bool RegenCodeFile { get; set; }
public MetadataProvider()
{
#if REGEN_CODE_FILES
RegenCodeFile = true; //try to get this to set the property
#endif
if (RegenCodeFile == false)
{
return;
}
//code that does some degree of preparation and c...
}
}
In the TT file...
var _MetaProvider = new MetadataProvider();
var _RegenerateFile = _MetaProvider.RegenCodeFile;
// T4VSHostProcess.exe may lock files.
// Kill it from task manager if you get "cannot copy file in use by another process"
var _CurrentFolder = new FileInfo(Host.ResolvePath(Host.TemplateFile)).DirectoryName;
var _AssemblyLoadFolder = Path.Combine(_CurrentFolder, "bin\\Debug");
Directory.SetCurrentDirectory(_CurrentFolder);
Debug.WriteLine($"Using working folder {_CurrentFolder}");
if (_RegenerateFile == false)
{
Debug.WriteLine($"Not Regenerating File");
var existingFileName = Path.ChangeExtension(Host.TemplateFile, "cs");
var fileContent = File.ReadAllText(existingFileName);
return fileContent;
}
Debug.WriteLine($"Regenerating File");

Visual Studio 2010 plugin / code to clear "Error List" warnings before each build

VS2010 is driving me nuts: whenever I rebuild, the "Error List" warnings from the previous compilation are persisted and any new warnings are simply added to the end of the list. Over time, this list becomes ridiculously long and unwieldy.
I'm using the Chirpy 2.0 tools to run JSHint and JSLint on my JS files, and these tools generate a lot of false positives.
I've been looking for an easy way to clear the contents of this window, but the only manual mechanism that works 100% of the time is to close and re-open the solution. Not very elegant.
I'd like to write a small VS Plug-In or some code that gets called right before a compilation to clear out this list so I can focus only on new warnings for the currently loaded file(s).
I see a .Clear() method for the Output window but not for the Error List. Is this doable?
Once upon a time I was an Add-In/VSIX Package/MEF developer ...
The answer is shortly no, but I have to do it on the long way:
Add-Ins, packages (Managed or not) have access to the VS service level separatedly. Every error belongs to the reporter (If they are manage them as Chirpy do), so you can not handle the errors created by Chirpy 2.0
I take a several look to it's source code and it is persist it's erros gained by the tools in a Singleton collection called TaskList.
The deletion of the collection elements is happening in several point of code in the latest release through the RemoveAll method:
First: after the soulution is closed.
by this:
private static string[] buildCommands = new[] { "Build.BuildSelection", "Build.BuildSolution", "ClassViewContextMenus.ClassViewProject.Build" };
private void CommandEvents_BeforeExecute(string guid, int id, object customIn, object customOut, ref bool cancelDefault) {
EnvDTE.Command objCommand = default(EnvDTE.Command);
string commandName = null;
try {
objCommand = this.App.Commands.Item(guid, id);
} catch (System.ArgumentException) {
}
if (objCommand != null) {
commandName = objCommand.Name;
var settings = new Settings();
if (settings.T4RunAsBuild) {
if (buildCommands.Contains(commandName)) {
if (this.tasks != null) {
this.tasks.RemoveAll();
}
Engines.T4Engine.RunT4Template(this.App, settings.T4RunAsBuildTemplate);
}
}
}
}
As you may see, clear of results depends on many thigs.
First on a setting (which I don't know where to set on GUI or configs, but seems to get its value form a check box).
Second the array of names which are not contains every build commands name.
So I see a solution, but only on the way to modify and rebuild/redepeloy your own version from Chirpy (and make a Pull request):
The code souldn't depend on the commands, and their names. (rebuilds are missing for example)
You could change the method above something like this:
this.eventsOnBuild.OnBuildBegin += ( scope, action ) =>
{
if (action != vsBuildAction.vsBuildActionDeploy)
{
if (this.tasks != null)
{
this.tasks.RemoveAll();
}
if (settings.T4RunAsBuild && action != vsBuildAction.vsBuildActionClean)
{
Engines.T4Engine.RunT4Template(this.App, settings.T4RunAsBuildTemplate);
}
}
};
Or with something equivalent handler method instead of lambda expression.
You shold place it into the subscription OnStartupComplete method of Chirp class.
The unsubscription have to placed into OnDisconnection method in the same class. (As for all other subscribed handlers...)
Update:
When an Add-In disconneced, it isn't means the Studio will be closed immediately. The Add-In could be unloaded. So you should call the RemoveAll from OnDisconneconnection too. (Or Remove and Dispose the TaskList...)
Update2:
You can also make a custom command, and bind it to a hotkey.

Resources