I'm looking for a way to accelerate a repeatable task when I write code. I have ReSharper and I'm thinking a customization could do what I need.
I have two objects of the same type. I want to copy all of the public properties of one object to the other object. I want the tool, ReSharper in this case, to do generate the code for me. I'll tell it the names of the first object and the second object. I want it to find all the public properties of the first object and copy the values to the second object.
Here's the type of code I'm looking to have generated with a tool like ReSharper:
foo.Name = moo.Name;
foo.Age = moo.Age;
foo.City = moo.City;
Automating this simple code that copies values from right to left would save a ton of time and I'm thinking that ReSharper can do it. However, I haven't seen anything pop-up in searches for it though.
I'm not looking for a CodeSmith code generation technique or T4 template because I only want it to generate these specific lines inside my class, not generate and entire class or a separate file.
Does anyone know a way to press a few keystrokes, enter the "foo" and "moo" object names above and have the tool generate these copy from right to left lines of code?
Update:
I've found some documentation on building extensions to ReSharper, and this can probably be achieved by that path, but it looks really involved.
http://www.jetbrains.net/confluence/display/ReSharper/PowerToys+Pack+3.0+User+Guide
This is beginning to look like a weekend challenge unless someone else has already written it.
It's really easy. ReSharper doesn't do it, but you can use a super duper REGEX!
In Visual Studio:
public string Email { get; set; }
public string CellPhone { get; set; }
public int NumChildren { get; set; }
public DateTime BirthDate { get; set; }
Select all your properties. Hit CTRL-D to copy down.
Now hit CTRL-H to replace. Make sure .* is selected for Regex matching.
Replace: public [\w?]* (\w*) .* (This Regex may need to be tweaked)
With: dest.$1 = source.$1;
Now you have some beautiful code you can put in a method of your choosing:
dest.Email = source.Email;
dest.CellPhone = source.CellPhone;
dest.NumChildren = source.NumChildren;
dest.BirthDate = source.BirthDate;
EDIT: New alternatives
You can use AutoMapper for dynamic runtime mapping.
Mapping Generator is really nice for static mapping. It can generate the code above and it works well with R#.
This is somewhat derivative from answer by #Jess (his regex didn't work for me on VS2013) but instead of using Visual Studio I am using regex101
Click link above and just paste your properties into Test string field and you will get them mapped.
Regex I used
public [A-Za-z\?]* ([A-Za-z0-9]*) .*
and replace
Dest.$1 = Source.$1
hope this saves you some time.
I don't believe Resharper can do this, but Open Source AutoMapper can. New to AutoMapper? Check out the Getting Started page.
I agree with #Ben Griswold.
In most situations, Automapper is the way to go.
But when you truly want to generate code that copies properties from one object to another, try this:
Create a brand new class and derive from the class from which you want to copy properties.
Right-click on this new derived class and click 'Refactor > Extract Interface'.
Check all properties that you wish to copy.
Choose 'Place beside' because this interface will be only temporary.
Click 'Next'.
Modify your derived class so that you are no longer inheriting from the base class and you are only implementing your new interface. Expect to see a red squiggle.
Place your cursor over the red squiggle and hit 'ALT-ENTER' to 'Implement Members'.
Click 'Finish'.
Delete that temporary interface and modify your class so that you are no longer implementing it.
Here's a simple class to clone an object. It's not exactly what you asked for but perhaps this will be useful for you:
//.Net 2.0
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace YourNameSpace {
public static class ObjectCloner {
public static T Clone<T>(T obj) {
using (MemoryStream buffer = new MemoryStream()) {
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(buffer, obj);
buffer.Position = 0;
T temp = (T)formatter.Deserialize(buffer);
return temp;
}
}
}
}
Based on #Matas answer I created a more robust version using regex101 that ignores generics, attributes and comments and normalizes spaces.
Regex: *((\/+.*\n*.*)|(\[.*\]\n*.*))*public [A-Za-z\_\?\<\>]* ([A-Za-z0-9\_]*).*(\n| )*
Replace: $4 = person.$4,\n
This is the kind of thing for which Cog shines. Basically, Cog is code generation tool. Code is generated via Python.
Simply copying values from one side to the other is pretty ugly.
You might find it better to create a method to include in your classes that uses reflection to copy public properties. You could save this method in resharper to regenerate into other classes you need this functionality in.
Related
I have a background in C++ and recently I started working in C#.
I have written following pieces of code (in Visual Studio):
var list_Loads = database.GetData<Load>().ToList();
var test_list = list_Loads.Where(o => (o.Name.Substring(0, 3) == "123")).ToList();
When I run the program and I move my mouse over both lists, first I get the count, which is very useful, but when I ask for the entries, this is what I get:
0 : namespace.Load
1 : namespace.Load
2 : namespace.Load
...
Not very useful, as you can imagine :-)
So my question: how can I show the Name attributes of those objects?
I thought: no problem. I have a background in native visualisers, so it should be rather easy to turn this into useful information, but then it comes:
In order to alter the way that those objects are represented, there is the first proposal to add a [DebuggerDisplay] "tag" to the definition of that class in source code.
However, as those classes are part of a framework I'm just referring to, I don't have access to the source code and hence I can't modify this.
Then I found another solution, which comes down to: "Write an entire C# project, debug, test and install it and it might work" (see documentation on "Custom visualisers of data" on the Microsoft website).
I almost choked in my coffee: writing an entire project, just for altering the view of an object??? (While, in C++, you just create a simple .natvis file, mention the classname and some configuration, launch .nvload and that's it.
Does anybody know a simple way to alter the appearance of C# object, without needing to pass through the whole burden of creating an entire C# project?
By the way, when I try to load a natvis file in Visual Studio immediate window, this is what I get:
.nvload "C:\Temp_Folder\test.natvis"
error CS1525: Invalid expression term '.'
What am I doing wrong?
Thanks in advance
OP (my emphasis):
In order to alter the way that those objects are represented, there is the first proposal to add a [DebuggerDisplay] "tag" to the definition of that class in source code.
However, as those classes are part of a framework I'm just referring to, I don't have access to the source code and hence I can't modify this.
Does anybody know a simple way to alter the appearance of C# object, without needing to pass through the whole burden of creating an entire C# project?
If you just want to specify [DebuggerDisplay] on a type, you don't have to have access to the source code. You can make use of [assembly:DebuggerDisplay()] and control how a type appears in the debugger. The only downside is that [assembly:DebuggerDisplay()] naturally only affects the current assembly whose code your mouse is hovering over. If you wish to use the customised display in other assemblies that you own, then you must repeat the [assembly:DebuggerDisplay()] definition.
Here's an easy before-and-after example with DateTime. I picked DateTime because we generally don't have access to the source code and it has some interesting properties:
var items = new List<DateTime>
{
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(-1),
DateTime.Now
};
...which on my machine defaults to:
Maybe I'm fussy and I just want to see:
Day of the week and
Day of the year
...I can do that via:
using System.Diagnostics;
[assembly: DebuggerDisplay("{DayOfWeek} {DayOfYear}", Target = typeof(DateTime))]
...which results in:
Example:
namespace DebuggerDisplayTests
{
public class DebuggerDisplayTests
{
public DebuggerDisplayTests()
{
var items = new List<DateTime>
{
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(-1),
DateTime.Now
};
}
}
.
.
.
}
Overrides
[assembly:DebuggerDisplay()] can also be used as a means to override pre-existing [DebuggerDisplay] on a 3-rd party type. Don't like what style they have chosen? Is the type showing far too much information? Change it with [assembly:DebuggerDisplay()].
I am using Roslyn to create an analyzer that warns users if a particular class exposes its fields in an unsynchronized manner, to help prevent race conditions.
The Problem:
I currently have working code that checks to make sure a field is private. I’m having trouble with the last piece of the puzzle: figuring out a way to make sure that all fields are only accessed inside a lock block, so they’re (ostensibly) synchronized.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FindSymbols;
namespace RaceConditions
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class UnsynchronizedMemberAccess : DiagnosticAnalyzer
{
public const string DiagnosticId = "UnsynchronizedMemberAccess";
internal static readonly LocalizableString Title = "UnsynchronizedMemberAccess Title";
private static readonly LocalizableString MessageFormat = "Unsychronized fields are not thread-safe";
private static readonly LocalizableString Description = "Accessing fields without a get/set methods synchronized with each other and the constructor may lead to race conditions";
internal const string Category = "Race Conditions";
private static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }
//meant to stop other classes and itself from accessing members in an unsychronized fashion.
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.RegisterSemanticModelAction((context) =>
{
var model = context.SemanticModel;
var root = model.SyntaxTree.GetRoot();
var nodes = model.SyntaxTree.GetRoot().DescendantNodes();
var fields = nodes.OfType<VariableDeclaratorSyntax>()
.Where(v => v.Ancestors().OfType<FieldDeclarationSyntax>().Any());
//since (it appears) that you can't read/write to a an initialized field,
//I think it means you can only read/write inside a block
foreach (BlockSyntax b in nodes.OfType<BlockSyntax>())
{
//where I plan to put code to check references to the fields
}
});
}
}
}
More specifically, I’d like to be able to ensure everything highlighted by the reference highlighter (at least that’s what Microsoft seems to call it) is inside a lock block, while overloaded parameters do not have to.
using System;
using System.Linq;
using System.Activities;
using System.Activities.Statements;
using System.Data.SqlClient;
namespace Sandbox
{
partial class Program
{
private int xe = 0, y = 0;
public Program(int xe)
{
this.xe = xe;
}
void bleh()
{
if (xe == 0)
{
xe = xe + 1;
}
}
static void Main(string[] args)
{
Program p0 = new Program(5),
p1 = new Program(p0),
p2 = new Program(p0.xe);
Console.WriteLine(p1.xe);
Console.Read();
}
}
partial class Program
{
public Program(Program p) : this(p.xe) { }
}
}
The Research:
Here, Josh Varty [1] suggests I use SymbolFinder.FindReferencesAsync, which requires a Solution object. Jason Malinowski [2] says that I shouldn’t use do this in an analyzer, since making a MSBuildWorkspace to get a Solution object is too slow, while this person [3] offers an incomplete/missing workaround to the slowness issue (the link to ReferenceResolver seems to be broken).
I have also looked into DataFlowAnalysis (SemanticModel.AnalyzeDataFlow()), but I can’t find any particular methods there that obviously let me guarantee that I’m referencing the field xe, and not the local variable xe.
The Question:
I do feel like there is something monumentally obvious I’m missing. Is there some elegant way to implement this that I’ve overlooked? It’d be preferable if the answer uses the semantic model, since I expect I have to use it in other analyzers to figure out where data/references come from, but I realize there are limitations, so any answers without the semantic model are also fine.
Notes:
Apparently, this issue was also encountered at Github [4], but apparently it’s still being tracked there, and they don’t know if the analyzer should analyze on the project level or not. It still hasn’t been resolved. For the purposes of this analyzer, I will assume that the entire class contained in a single .cs file. Small steps first, eh?
I also searched through John Koerner's website [5] and Josh Varty's website [6], and couldn’t find anything relevant to both analyzers and DataFlowAnalysis.
The trick is to invert how you're asking the question. Go from:
How do I find all the references to this symbol that I want to ensure is synchronized?
but instead
How, upon looking at the use of a symbol, determine if this should be inside of a lock statement?
Because this offers a course of action: your analyzer should instead look at each identifier in a method body that's not in a lock statement, call SemanticModel.GetSymbolInfo(), get the symbol that's being referenced, and then check if that field is one that's "synchronized" via your logic (private, etc.). At that point, then since you're looking at the use, you can flag that particular use.
This inversion is how we expect analyzers to be written, and it's not an accident. The reason is largely performance. Imagine your analyzer is running inside Visual Studio, and you delete a line of code. If analyzers were written in the model of "look at a symbol, now ask for all uses", it means any and all analyzers that did that potentially have to rerun from scratch. That's not great for your CPU or battery life. When the question is inverted like this, it means we only have to reanalyze that specific file, since you're not expanding to "give me everything".
I have classes that are fluent and follow the builder pattern. For example a typical class might look like this:
public class ItemBuilder
{
private string _id = "SMITH-1001001";
//code for implementing the builder omitted for brevity
public ItemBuilder WithId(string id)
{
this._id = id;
return this;
}
}
Now it is not uncommon to be implementing a builder object for some poco that has multiple private fields (the one I'm staring at has 66) and I need to have a method as seen above for modifying each one if altering from the default.
I know how to create a snippet to generate a single method and tab through changing values as appropriate. I can also highlight a chunk of code and chose the snippet to wrap with try block.
So what I am wondering is if there is a way to mass generate the methods since they are 100% predictable.
For example I could highlight all 66 fields and choose my snippet which would generate 66 methods.
TIA
So the answer is....you can't do this via snippets. However the objective can still be met. What I ended up doing was writing a regular expression that parsed out the values then inserted them into a string. So I would copy all the private fields I wanted to use from vs to notepad ++. I then did a ctrl-h and put the regex in the find and the replacement string in the replace. From there it generated my methods and I cut and paste back to vs. Not 100% smooth but far better than manually typing them all.
I am working on an application that has been edited by various programmers over the past few years and I have stumbled across a problem with using String Literals to access MenuItems.
For Example: in many places there is code like
mainMenu.MenuItems[1].MenuItems[0].Visible=true;
or
mainMenu.MenuItems["View"].MenuItems["FullScreen"].Visible=true;
how do I change the Strings used to identify the MenuItem and catch all of the places that it is being used for access? The menus and menuitems are declared as public and are used throughout this large application
What is the right way prevent the use of these magic indexes from being used. I forsee things being broken everytime a new item is added or the name is changed.
P.S. I have started using an enumerated dictionary approach in which every menuItem is paired with a key. but this still does not force other developers to use my implementation nor is it the most elegant solution to question 2
Give each menu item a name in the WinForms designer (I assume), and then refer to it by that name.
Then just use this in your code:
menuExit.Visible = false;
If the menu items are added programmatically, do this:
class MyForm : Form
{
private MenuItem menuExit;
...
myMenu.Items.Add(menuExit = new MenuItem(...));
...
}
and then still access it by the menuExit name. The key to avoiding magic numbers and strings is to just keep a direct reference to whatever it is you want to refer to. As a bonus, you can now rename this vairable safely using F2.
Romkyns answer is the correct one for this scenarion however if you do need to use string literals in your code I would alwasy keep them in public static classes such as:
public static class Constants
{
public static class Menu
{
public static readonly string FirstMenuName = "Menu 1";
...
}
public static class OtherCateogry
{
...
}
}
You can then access them by Constants.Menu.FirstMenuName.
As for definitively preventing other devs from using literals throughout code - you might have to make recourse to the Rod of Correction (sturdy metal ruler) ;).
Our system complexity has risen to the point that we need to make permission names tied to the client from the database more specific. In the client, permissions are referenced from a static class since a lot of client functionality is dependent on the permissions each user has and the roles have a ton of variety. I've referenced this post as an example, but I'm looking for a more specific use case. Take for instance this reference, where PermissionAlpha would be a const string:
return HasPermission(PermissionNames.PermissionAlpha);
Which is great, except now that things are growing more complex the classes are being structured like this:
public static class PermissionNames
{
public static class PermissionAlpha
{
public const string SubPermission = "PermissionAlpha.SubPermission";
}
}
I'm trying to find an easy way to reference PermissionAlpha in this new setup that will act similar to the first declaration above. Would the only way to do this be to resort to pulling the value of the class name like in the example below? I'm trying to keep all the names in one place that can be reference anywhere in the application.
public static class PermissionAlpha
{
public static string Name { get { return typeof(PermissionAlpha).Name; } }
}
** Edit ** - Added missing permission name.
Maybe this would be too big of a change for you with the size of your project, but we have all of our business objects split into partial classes. One is for manual changes and one gets generated. During code-generation, we write the permission keys into the generated side of the partial classes from our "single source of truth". We're using a set of classes as our source of truth and CodeDom to generate, but you could also use a database as your source and use T4, CodeSmith, or others to generate.
Why not create reflectable attribute(s) on the classes in question? That way one can add all the extra information required. I provide a way of divining attributes on my blog article entitled:
C# Using Extended Attribute Information on Objects
HTH