This might be a lazy request, but is there a way to generate multiple class properties at the same time? Currently, I have a large list of undefined properties and I can simply go through the list, one by one, and generate a property - but it would be ideal to highlight them all and generate one for each, example illustration below...
You can see here that prop1, prop2...etc have errors since the properties don't yet exist, but you can generate a property with resharper...
However, this seems to be one-at-a-time, I was wondering if I am missing a setting?
I've been using Resharper for 5+ years and I'm using Resharper 9.1.3 Ultimate and I don't think what you want is possible.
The only way to make ReSharper create multiple properties at once is to have it implement missing properties from an interface. It might be worth creating a feature request!
Related
Using Protobuf-net, I want to know what properties of an object have been updated at the end of a merge operation so that I can notify interested code to update other components that may relate to those updated properties.
I noticed that there are a few different types of properties/methods I can add which will help me serialize selectively (Specified and ShouldSerialize). I noticed in MemberSpecifiedDecorator that the ‘read’ method will set the specified property to true when it reads. However, even if I add specified properties for each field, I’d have to check each one (and update code when new properties were added)
My current plan is to create a custom SerializationContext.context object, and then detect that during the desearalization process – and update a list of members. However… there are quite a few places in the code I need to touch to do that, and I’d rather do it using an existing system if possible.
It is much more desirable to get a list of updated member information. I realize that due to walking down an object graph that may result in many members, but in my use case I’m not merging complex objects, just simple POCO’s with value type properties.
Getting a delta log isn't an inbuilt feature, partly because of the complexity when it comes to complex models, as you note. The Specified trick would work, although this isn't the purpose it was designed for - but to avoid adding complexity to your own code,that would be something best handled via reflection, perhaps using the Expression API for performance. Another approach might be to use a ProtoReader to know in advance which fields will be touched, but that demands an understanding of the field-number/member map (which can be queried via RuntimeTypeModel).
Are you using habd-crafted models? Or are you using protogen? Yet another option would be to have code in the setters that logs changes somewhere. I don't think protogen currently emits partial method hooks, but it possibly could.
But let me turn this around: it isn't a feature that is built in right now, and it is somewhat limited due to complexity anyway, but: what would a "good" API for this look like to you?
As a side note: this isn't really a common features in serializers - you'd have very similar challenges in any mainstream serializer that I can think of.
I use VS2012 and ReSharper 7 to write C# code. My projects are rarely so large or complicated as to require thinking about granular access levels. It's usually easier for me to just make everything public, instead of spending time and effort to figure out what should be open to access by what. In any case, I am the only one using my code.
I realize this does not apply to everyone, and I realize that access modifiers are important features of the language and should be used carefully. But in my current situation, it doesn't matter and everything might as well be public (in practice I do make them public). I suspect this applies to many other programmers, especially non-enterpise ones.
However, the tendency of VS2012 is to default to the lowest access level. For instance, if I add a new field by typing int id_number;, the moment I put the semicolon in private is added to the field, then I have to go back and change it to public if that was my intention (it usually is).
How can I make VS/ReSharper generate classes, fields, methods and so on with the highest possible access level (essentially, make everything public)?
You can't.
Resharper adds private, because that's the default if you wouldn't specify any access modifier.
So, Resharper doesn't change the access level of your field. It just makes it explicit and because of that, Resharper doesn't have any functionality to change the access level automatically.
But you could easily use automatic properties. There even is a live template for it. Just type prop and hit TAB.
For classes and interfaces (typing class MyClass will cause ReSharper to recongnize "class" as a shortcut, and insert the template class MyClass { } as opposed to public class MyClass { }) it's possible to edit the template through ReSharper -> Template Explorer.
Things such as generated methods which are created by Extract... commands appear to be determined by Visual Studio's code snippets. The location of these can be found in the Code Snippet Manager (Ctrl+K, B). Each snippet is an XML file, this MSDN page describes editing them.
My project manager last week hinted at using ndoc on properties within a class. Is this something that should be done? Is it considered best practice to do this or not? I am currently expanding all my ndoc for the section of a project that I am working on but do not know how deep I need to go with it. I have of course provided summaries, params, returns and remarks to the class and each method but do properties require ndoc too?
Public properties are a contract to the outside world I think they should be documented.
Internal properties will only be used in the same assembly so you could get away with not documenting them.
Protected properties will only be used in derived classes (internal or public) so they might be in need of some documentation.
Private properties will only be used in the class itself so, again, you could get away with it.
Note that "getting away with not documenting it" suggests the way I feel about this: you should document. At the same time I realize that sometimes you need to do one thing or the other...
Perhaps you should ask this on http://programmers.stackexchange.com
Just like any other members, the meaning of properties should be documented. This should include not only what the property does or what it can be used for, but also its initial value, special cases (e.g. values that must not be assigned; values that would cause an exception or automatically be replaced with other values), as well as possibly the ramifications and purpose of overriding the property in a derived class where this is possible.
Public properties should definitely always be documented, whether your chosen documentation workflow uses GhostDoc, NDoc, or whatever. XML comments on public properties and methods show up in Intellisence when people use it, so there's no reason to not add something there. Even if the name of the property explains what it does, it's very nice to have XML comments there to confirm that. There are plenty of gotchas in plenty of code, so it's courteous to let the people who use your code know they're not walking into one.
Private properties can go either way. I'd hesitate to call it a particular best practice since to see the comments you have to be in the class, at which point you can just look at its usage trivially. That said, I still put XML comments on private properties, if for nobody else then for myself. There's no way you will remember what you were doing 6 months from now and any structural comments you can add will make it easier to pick up where you left off.
I've run into this issue quite a few times and never liked the solution chosen. Let's say you have a list of States (just as a simple example) in the database. In your code-behind, you want to be able to reference a State by ID and have the list of them available via Intellisense.
For example:
States.Arizona.Id //returns a GUID
But the problem is that I don't want to hard-code the GUIDS. Now in the past I've done all of the following:
Create class constants (hard-coding of the worst kind.. ugh!)
Create Lookup classes that have an ID property (among others) (still hard-coded and would require a rebuild of the project if ever updated)
Put all the GUIDS into the .config file, create an enumeration, and within a static constructor load the GUIDS from the .config into a Hashtable with the enumeration item as the key. So then I can do: StateHash[StatEnum.Arizona]. Nice, because if a GUID changes, no rebuild required. However, doesn't help if a new record is added or an old one removed, because the enumeration will need to be updated.
So what I'm asking is if someone has a better solution? Ideally, I'd want to be able to look up via Intellisense and not have to rebuild code when there's an update. Not even sure that's possible.
EDIT: Using states was just an example (probably a bad one). It could be a list of widgets, car types, etc. if that helps.
Personally, I would store lookup data in a database, and simply try to avoid the type of hard coding that binds rules to things like individual states. Perhaps some key property of those states (like .ApplyDoubleTax or something). And non-logic code doesn't need to use intellisense - it typically just needs to list them or find by name, which can be done easily enough however you have stored it.
Equally, I'd load the data once and cache it.
Arguably, coding the logic against states is hard coding - especially if you want to go international anytime soon - I hate it when a site asks me what state I live in...
Re the data changing... is the USA looking to annex anytime soon?
I believe that if it shows up in Intellisense, then, by definition, it is hard-coded into your program.
That said, if your goal is make the hard-coding as painless as possible, on thing you might try is auto-generating your enumeration based on what's in the database. That is, you can write a program that reads the database and creates a FOO.cs file containing your enumeration. Then just run that program every time the data changes.
This cries out for a custom MSBuild task. You really want an autogenerated enum or class in this case; if the IDs are sourced from a database and can/will change, and are not easily predicted. You could then put the task in your project and it would run before each build updating as necessary.
Or start looking at ORMs :)
I have wondered about the appropriateness of reflection in C# code. For example I have written a function which iterates through the properties of a given source object and creates a new instance of a specified type, then copies the values of properties with the same name from one to the other. I created this to copy data from one auto-generated LINQ object to another in order to get around the lack of inheritance from multiple tables in LINQ.
However, I can't help but think code like this is really 'cheating', i.e. rather than using using the provided language constructs to achieve a given end it allows you to circumvent them.
To what degree is this sort of code acceptable? What are the risks? What are legitimate uses of this approach?
Sometimes using reflection can be a bit of a hack, but a lot of the time it's simply the most fantastic code tool.
Look at the .Net property grid - anyone who's used Visual Studio will be familiar with it. You can point it at any object and it it will produce a simple property editor. That uses reflection, in fact most of VS's toolbox does.
Look at unit tests - they're loaded by reflection (at least in NUnit and MSTest).
Reflection allows dynamic-style behaviour from static languages.
The one thing it really needs is duck typing - the C# compiler already supports this: you can foreach anything that looks like IEnumerable, whether it implements the interface or not. You can use the C#3 collection syntax on any class that has a method called Add.
Use reflection wherever you need dynamic-style behaviour - for instance you have a collection of objects and you want to check the same property on each.
The risks are similar for dynamic types - compile time exceptions become run time ones. You code is not as 'safe' and you have to react accordingly.
The .Net reflection code is very quick, but not as fast as the explicit call would have been.
I agree, it gives me the it works but it feels like a hack feeling. I try to avoid reflection whenever possible. I have been burned many times after refactoring code which had reflection in it. Code compiles fine, tests even run, but under special circumstances (which the tests didn't cover) the program blows up run-time because of my refactoring in one of the objects the reflection code poked into.
Example 1: Reflection in OR mapper, you change the name or the type of the property in your object model: Blows up run-time.
Example 2: You are in a SOA shop. Web Services are complete decoupled (or so you think). They have their own set of generated proxy classes, but in the mapping you decide to save some time and you do this:
ExternalColor c = (ExternalColor)Enum.Parse(typeof(ExternalColor),
internalColor.ToString());
Under the covers this is also reflection but done by the .net framework itself. Now what happens if you decide to rename InternalColor.Grey to InternalColor.Gray? Everything looks ok, it builds fine, and even runs fine.. until the day some stupid user decides to use the color Gray... at which point the mapper will blow up.
Reflection is a wonderful tool that I could not live without. It can make programming much easier and faster.
For instance, I use reflection in my ORM layer to be able to assign properties with column values from tables. If it wasn't for reflection I have had to create a copy class for each table/class mapping.
As for the external color exception above. The problem is not Enum.Parse, but that the coder didnt not catch the proper exception. Since a string is parsed, the coder should always assume that the string can contain an incorrect value.
The same problem applies to all advanced programming in .Net. "With great power, comes great responsibility". Using reflection gives you much power. But make sure that you know how to use it properly. There are dozens of examples on the web.
It may be just me, but the way I'd get into this is by creating a code generator - using reflection at runtime is a bit costly and untyped. Creating classes that would get generated according to your latest code and copy everything in a strongly typed manner would mean that you will catch these errors at build-time.
For instance, a generated class may look like this:
static class AtoBCopier
{
public static B Copy(A item)
{
return new B() { Prop1 = item.Prop1, Prop2 = item.Prop2 };
}
}
If either class doesn't have the properties or their types change, the code doesn't compile. Plus, there's a huge improvement in times.
I recently used reflection in C# for finding implementations of a specific interface. I had written a simple batch-style interpreter that looked up "actions" for each step of the computation based on the class name. Reflecting the current namespace then pops up the right implementation of my IStep inteface that can be Execute()ed. This way, adding new "actions" is as easy as creating a new derived class - no need to add it to a registry, or even worse: forgetting to add it to a registry...
Reflection makes it very easy to implement plugin architectures where plugin DLLs are automatically loaded at runtime (not explicitly linked at compile time).
These can be scanned for classes that implement/extend relevant interfaces/classes. Reflection can then be used to instantiate instances of these on demand.