In Visual Studio 2010, is it possible to change the default template used when implementing an interface?
I would like to change the implementation of properties from
public int MyProperty
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
to
public int MyProperty { get; set; }
Edit
so i tried to Edit PropertyStub.snippet but to no avail, it didn't change anything...
I found this question Changing property stubs for interface refactoring which says that ReSharper is the only way.
Anyone able to make this work, with example, cause the change i made did not seem to have any effects
Yes, it is possible to change this template. The C# IDE uses templates for the majority of it's code generation and the IDE. You can update these templates to control the code generation process. They are located in the following directory
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Refactoring
Note: The " (X86)" portion will be absent on 32 bit machines.
For this particular situation you want to change the PropertyStub.snippet file.
Related
Repro:
public class TestCase
{
public Boolean MyFieldIsFour(MyRecord myRecord)
{
return myRecord.MyField == 4;
}
}
public record MyRecord(int MyField);
Right click int MyField and choose Find All References.
Visual Studio can't find any references to MyField. I would have expected it to find the reference at myRecord.MyField. If MyRecord is changed to a class then Visual Studio has no problems finding the reference as expected.
Is this a bug in Visual Studio? How can I actually find references now with records?
This is a bug (or not implemented feature if you want call it that way) in Roslyn.
The semantics around records is a mess. See this feedback, this issue, this issue, this issue, this issue
I'm looking for a way to expand/inject code at compile time,
something like templates/macros/snippets...
Let's say I wrote this code in a lot of places in my application:
[JsonObject("MyProperty")]
private string MyPropertyJson { get; set; }
public object MyProperty { get; set; }
The MyPropertyJson property is used for EF mapping purposes only so I save the value is a JSON string in DB but for class users, they only know about MyProperty property.
What I want to do is, at compile time, MyPropertyJson to be expanded to this:
private string MyPropertyJson
{
get
{
return JsonConvert.SerializeObject(MyProperty);
}
set
{
MyProperty = JsonConvert.DeserializeObject(value);
}
}
I want this to be done in the output binaries only without affecting the source code.
I know about Unity, PostSharp, Aspect-Injector, etc.. but they don't achieve what I want because by using them, I have to use some reflection to find & manipulate MyProperty but I want to expand it exactly like it's been written in the same class with access to all class internals.
It's exactly like code snippets but to be expanded during compilation phase.
A solution that doesn't cost anything extra and is supported within Visual Studio is T4 aka Text Templates. However, it does require you install the VS SDK (eg, 2015) and Modeling SDK (eg, 2015) of the version of VS that you use.
For my base class libraries, I end up dedicating an assembly for utils to use in the T4 code I write in production code. I use it in places like rolling out read/writes for primitives in IO code (eg, .TT and .CS). Although you don't have to do this if you don't need much/complex compile time code gen.
I was able to achieve my requirement by writing a BeforeBuild msbuild target to call an external console app which I've developed to:
Copy source files that will be rewritten to a temp folder
Rewrite the source code in the temp files
Added conditional Compile tag to the .csproj file to include manipulated source files instead of the original ones
It works like a charm :)
I'm working on a generic engine for this task and will commit it to github once finished.
The is a way to kind of get what you want.
Using implicit operators
That would need to create your own json object class for example, then add these:
class JsonObject {
public object obj;
public static implicit operator string(JsonObject target) {
return Json.SerializeObject(target.obj);
}
}
But that won't really do what you really wanted. Almost the same as creating a new class and add functions.
I have problem with public fields, which I use from time to time in my code. I keep forgeting to change them to private and create properties for them- especialy when Im testing some new part of code (and Im used to create public field for testing at first).
I was thinking that it would be fine to see some sort of "warning" if I use public field in my code.
I have found out, that I can create a ruleset (Im using Visual Studio Community 2013) and choose any of the rule I need. I searched for the rules relative to public fields and found these 2: CA2211: Non-constant fields should not be visible and CA1051: Do not declare visible instance fields. I checked these in the ruleset, tried to Run code analysis on whole solution but I cant see any warnings in the outcome.
I even tried to add something like public int i; in one of my classes but still nothing.
Do you know if I have the right rules or whether there is something else I should do to get the warning? Thank you.
Edit
This bugs me for an almost year. I'll update the answer and add bounty.
I've custom control, which has dependency property
public class Graph : Control
{
public List<Figure> Figures
{
get { return (List<Figure>)GetValue(FiguresProperty); }
set { SetValue(FiguresProperty, value); }
}
public static readonly DependencyProperty FiguresProperty =
DependencyProperty.Register("Figures", typeof(List<Figure>), typeof(Graph),
new PropertyMetadata((d, e) => ((Graph)d).InvalidateVisual()));
...
}
Figure is the base class for all figures:
public abstract class Figure { ... }
public class LineFigure : Figure { ... }
public class XGridFigure : Figure { ... }
public class YGridFigure : Figure { ... }
...
Now look at screenshots below to see the problem: sometimes (after doing a change to xaml in other place) designer goes crazy about it and stop rendering the whole window, throwing exceptions, while code compiles and runs without problem. I can close this xaml (designer) and open it again to make problem go away. But it always reappears.
Question: is there something wrong on my side? Missing attribute? Wrong usage? How can I fix that problem?
Old question
Ugly situation.
I have 2 UserControl. In both hand-made control Graph is used. Graph has property Figures to specify List<Figure>. There are dozens of figures which have Figure as base.
In one UserControl it works fine, in other throws exception
The specified value cannot be assigned to the collection. The following type was expected: "Figure".
And I fail to see a difference what could cause a problem.
Here is problematic one screenshot
And here is working one
Despite of errors project compiles and runs, but if I need to do modification to problematic UserControl, then it's not showing any content (says "Invalid Markup"). Graphs are nearly the same, all 8 errors are shown for to just one UserControl.
What should I do? How to troubleshoot such errors? I exclude (completely) any problem with Graph because it runs without a single problem AND it works without problem for another UserControl. Visual Studio designer problem? Using 2013 Express for Windows Desktop.
Indeed the visual designer does not recognize the inheritance from Figure. One solution is to use IList as the Interface type:
public IList Figures
{
get
{
return (IList)GetValue (FiguresProperty);
}
set
{
SetValue (FiguresProperty, value);
}
}
public static readonly DependencyProperty FiguresProperty =
DependencyProperty.Register ("Figures", typeof (IList), typeof (Graph), new PropertyMetadata (new List<object>()));
That might look like a bit strange (because you give up type safetyness). But have a closer look at the WPF classes. They all do it that way (most likely for good reasons). Or WPF even creates collection classes like PathFigureCollection that implement both IList and IList<PathFigure>.
close the project, restart VS and reopen it. does it still list the errors? visual studio often seems to report "phantom errors", but they usually go away if you close and restart etc.
If the custom control is in the same solution or project, Visual Studio builds it (when it considers it necessary) so it can use the control in the designer.
Sometimes this built/cached version gets out of sync with the code files which causes the Xaml parser/syntax checker to get confused and display those wavy red lines.
I have had success with closing and reopening all designers that use the control but that is pretty annoying to keep on doing. In my experience the most reliable solution is to move the control into a separate solution and project and set a 'proper' reference to the dll.
I had a whole load of these errors in one project.
Eventually I found that the project did not have a reference to System.Xaml.
Adding a reference to System.Xaml removed all of the warnings.
The strange thing is that it didn't cause a runtime problem.
I was watching a video about C# and the guy used a shortcut to implement a property.
public decimal Price { get; set; }
He wouldn't write the whole line, but instead let the visual studio editor fill in the get and set. Does anyone know the shortcut for completing the last part of the line above? Or even better, like a pdf quick-reference overview?
In Visual Studio 2010 you can type 'prop' then press tab twice. It's probably the same in earlier versions.
Edit: You'll then have to change the type (defaults to int) and the name (defaults to MyProperty).
Edit2: I've just found this great tool that allows you to edit these code snippets to override their default behaviour, or create new ones: http://snippeteditor.codeplex.com/