CodeRush indents property initializers during "Introduce Local" - coderush

When I use the "Introduce Local" refactoring, CodeRush changes the indentation of my code. For example, before:
DoSomething(new MyObject
{
PropertyA = "A",
PropertyB = 2,
PropertyC = true
});
After:
MyObject newMyObject = new MyObject
{
PropertyA = "A",
PropertyB = 2,
PropertyC = true
};
DoSomething(newMyObject);
What I want:
MyObject newMyObject = new MyObject
{
PropertyA = "A",
PropertyB = 2,
PropertyC = true
};
DoSomething(newMyObject);
I would like for CodeRush to respect my formatting. At the very least, I should be able to tell it how I prefer to indent my initializers. Are there any options that could help me?

Yes, inside the CodeRush Options Dialog (DevExpress | Options...), navigate to the Editor | Code Formatting section and tweak the desired settings. Look for the "Array, object and collection initializer" options. The options can be found on the Indentation, Line Breaks and Wrapping/Alignment option pages.
You may also want to play with options on the General options page to preserve the existing formatting.

Related

How to shadow a record in F# Program.fs?

I'm following the F# book Get Programming with F# and got to the part about shadowing. The simplest example they provide doesn't seem to be possible, so I'm wondering if either this syntax was removed or changed for F# 6 shadowing? I haven't been able to find anything stating that or how to do what the book offers as shadowing a record.
type Address =
{ Street: string
Town: string
City: string }
let home = { Street = "123 Main Street"; Town = "The Town"; City = "The City" }
let home = { home with City = "Second City" }
let home = { home with City = "Third City" }
When trying to build get an error stating: Duplicate definition of value 'home'
Edit
So after searching for answers without success as to why this doesn't work I tried putting the above into a function like so:
let testFunction =
let home = { Street = "123 Main Street"; Town = "The Town"; City = "The City" }
let home = { home with City = "Second City" }
let home = { home with City = "Third City" }
0
and it worked just fine. So my question now is why does shadowing work within a function but not outside? Is there a conflict with scoping on a module level that doesn't happen within a function's scope?
To add some more detail to the existing answers, there are four different cases.
Local definitions. If you are inside a function body, you can use shadowing and this is quite useful when doing a computation in multiple steps:
let adjust index =
let index = max 0 index
let index = min 100 index
index
Local definitions inside class. You are similarly allowed to shadow local definitions inside a class:
type A() =
let foo = 1
let foo = 2
member x.Foo = foo
Top-level in a script file. If you are at the top level in a script file (something.fsx) then you are allowed shadowing. The idea with script files is that they would be run manually, so it is useful to have multiple different versions - you just run the one you want by hand:
let test = calculation1 ()
let test = caluclation2 ()
Top-level in a module (source file). The only case where shadowing does not work is when you are in a module (or .fs file which becomes a module implicitly). In a module, definitions are public and they are compiled as static members of a class, so there is also a technical limitation (you cannot have multiple class members of the same name).
module Constants =
let answer = 1
let answer = 42 // error FS0037: Duplicate definition of value
Why shadowing is limited to function body?
There are probably some technical reasons. But the core reasons are IMO:
Naming is hard. Shadowing eases the pain but it can be confusing.
Also F# supports "tick naming" (home') to have a similar but different name. It's a kind of safer shadowing.

Convert a method call or assignment to a function in F#

I would like to use some object-oriented code in a more functional way.
My current approach has been the following:
let addControl (child: Control) (parent: Control) =
parent.Controls.Add child
parent
let setDock dock (control : Control) =
control.Dock <- dock
control
form |> addControl button
button |> setDock DockStyle.Fill
Is there a simpler way I can define these functions?
If I take the JS approach I could define something like the following:
const fixMethod = name => value => parent => (parent[name](value), parent)
const resumeLayout = fixMethod("ResumeLayout")
resumeLayout(true)(form)
const fixAssign = name => value => parent => ({...parent, [name]: value})
const setDock = fixAssign("Dock")
setDock(DockStyle.Fill)(button)
There are various tricks you could do in F#, but none of those will make your code much nicer - I would say that most tricks you can do will actually only make it more complex and unidiomatic.
There is nothing wrong with writing some imperative-looking code if that's what the underlying libraries look like. F# does have a few features that make this easier - you can, for example, specify mutable properties directly when calling a constructor, so you can set Dock as follows:
let button = new Button(Dock = DockStyle.Fill)
let form = new Form()
form.Controls.Add(button)

Constant with all items of an enum in Delphi

Is it possible to have a constant set of all items of an enumerated type in Delphi?
type
TItems = (
iOne,
iTwo,
iThree
);
TItemsSet = set of TItems;
const
SOMEITEMS: TItemsSet = [iTwo, iThree];
ALLITEMS: TItemsSet = ?????
I would like ALLITEMS to always hold all members of TItems. And I would prefer to have this as constant.
Edited:
And what, if my enum looks like this:
TItems = (
iOne = 1,
iTwo = 2,
iThree = 5
);
(From the comments)
[Low(T)..High(T)] works for any type T that is small enough to be used as a set, to include all items that can be included in the set.
As noted in the comments, this is enough for the enumeration in the question, but in general, may include constants that aren't defined as part of the enumeration.

Static list of data for dropdown list MVC

I want to have a static list of data in a model that can be used in a viewmodel and dropdown on a view. I want to be able to use it in this way in my controller:
MaintenanceTypeList = new SelectList(g, "MaintenanceTypeID", "MaintenanceTypeName"),
and access it in my view like this:
#Html.LabelFor(model => model.MaintenanceTypeID)
#Html.DropDownListFor(x => x.MaintenanceTypeID, Model.MaintenanceTypeList, "-- Select --", new { style = "width: 150px;" })
#Html.ValidationMessageFor(x => x.MaintenanceTypeID)
I am currently using a repository pattern for data in the database, but don't want to put this data in the database because it will never change. I still want it in a model though. Basically, my dropdown list should offer the following:
Value Text
-------------------------------------
Calibration Calibration
Prevent Preventative Maintenance
CalibrationPrevent PM and Calibration
Any help or examples of static lists using models/oop is appreciated
You can use a list initializer:
public static SomeHelperClass{
public static List<SelectListItem> MaintenanceTypeList {
get {
return new List<SelectListItem>
{ new SelectListItem{Value = "Calibration", Text = "Calibration"}
,new SelectListItem{ Value = "Prevent", Text = "Preventative Maintenance" }
,etc.
};
}
}
}
Hopefully I didn't miss a curly brace somewhere. You can google "C# list initializer" for more examples. I don't remember off top of my head what the actual collection to is for a SelectListCollection is, but I know there is a overload of DropDownList that accepts List as I often just have a collection of keyvaluepairs or something else, and then in my view I convert it to SelectListItems: someList.Select(i => new SelectListItem { Value = i.Key, Text = i.Value })
Note that another option is to place your values in an enum. You can then use a Description attribute on each enum value:
enum MaintenanceType {
[Description("Calibration")]
Calibration = 1,
[Description("Preventative Maintenance")]
Prevent = 2
}
Then you can do things like
Enum.GetValues(typeof(MaintenanceType )).Select(m=>new SelectListItem{ Value = m, Text = m.GetDescription()} ).ToList()
That last line was a little off the top of the head, so hopefully I didn't make a mistake. I feel like an enum is more well structured for what you're trying to do.

Grails validation fails after interchanging unique attribute values

Grails validation fails after interchanging unique attribute values
Hi, I am trying to create an interface where users can create some custom enumeration with translations for different languages. For example the user can create an enumeration "Movie Genre". For this enumeration there might be an enumeration-value "Comedy" for which there might exist one ore more enumeration-value-translations for several languages.
As there must only be one translation for a specific language, I added a unique constraint to the enumeration-value-translation domain class. These are my domain classes right now:
class Enumeration {
String label
List<EnumerationValue> enumerationValues = new ArrayList<EnumerationValue>()
static hasMany = [ enumerationValues: EnumerationValue ]
static constraints = {
label(nullable: false, blank: false)
enumerationValues(nullable: true)
}
}
class EnumerationValue {
String label
List<EnumerationValueTranslation> enumerationValueTranslations = new ArrayList<EnumerationValueTranslation>()
static belongsTo = [ enumeration: Enumeration ]
static hasMany = [ enumerationValueTranslations: EnumerationValueTranslation ]
static constraints = {
label(nullable: false, blank: false, unique: 'enumeration')
enumeration(nullable: false)
enumerationValueTranslations(nullable: false)
}
}
class EnumerationValueTranslation {
String value
Language language
static belongsTo = [ enumerationValue: EnumerationValue ]
static constraints = {
value(nullable: false, blank: false)
language(nullable: true, unique: 'enumerationValue')
enumerationValue(nullable: false)
/* unique constraint as mentioned in description text */
language(unique: 'enumerationValue')
}
}
This works pretty fine so far. My problem occures when I update two enumeration-value-translations of the same enumeration-value in a way that the languages interchange. For example I have an
enumeration-value: "Comedy"
and some translations where the language is "accidentally" mixed up
translations for "Comedy"
language: german, value: "Comedy"
language: english, value "Komödie"
if the user recognizes that he mixed up the language, he might want to swap the languages and save the enumeration again. And this is where my error occures, because after swapping the languages the enumeration-value-translations unique constraint validates to false.
To debug this i simply tryed to print out the error causing translations before and after i processed the params, so:
Enumeration enumeration = Enumeration.get(params['id']);
println "before:"
enumeration.enumerationValues.each() { enumValue ->
enumValue.enumerationValueTranslations.each() { enumValueTr ->
println enumValueTr;
if(!enumValueTr.validate()) {
// print errors...
}
}
}
// swap languages:
// (this are the lines of codes that are actually executed, and cause the
// error. The actual processing of params looks different of course...)
// sets the language of "Comedy" to English
EnumerationValueTranslation.get(5).language = Language.get(1);
// sets the language of "Komödie" to German
EnumerationValueTranslation.get(6).language = Language.get(2);
println "after:"
enumeration.enumerationValues.each() { enumValue ->
enumValue.enumerationValueTranslations.each() { enumValueTr ->
println enumValueTr;
if(!enumValueTr.validate()) {
// print errors...
}
}
}
wich results to:
before:
EnumerationValueTranslation(value: Fantasy, language: en_US, enumerationValue: Fantasy)
EnumerationValueTranslation(value: Phantasie, language: de_DE, enumerationValue: Fantasy)
EnumerationValueTranslation(value: Comedy, language: de_DE, enumerationValue: Comedy)
EnumerationValueTranslation(value: Komödie, language: en_US, enumerationValue: Comedy)
after:
EnumerationValueTranslation(value: Fantasy, language: en_US, enumerationValue: Fantasy)
EnumerationValueTranslation(value: Phantasie, language: de_DE, enumerationValue: Fantasy)
EnumerationValueTranslation(value: Comedy, language: en_US, enumerationValue: Comedy)
validation fails: Property [language] of class [Translation] with value [Language(code: en_US)] must be unique
EnumerationValueTranslation(value: Komödie, language: de_DE, enumerationValue: Comedy)
validation fails: Property [language] of class [Translation] with value [Language(code: de_DE)] must be unique
at this state i havend deleted, or saved (or flushed in any way) anything - this is just the result after altering the objects. And as you can see, there really is no inconsistency in the actual data and the validation should'nt fail.
Might there be a mistake in the way i change the translations? I just fetched them by ID and simply updated the language - i tryed that out in a minimalistic example and it worked there...
It also works if i just create a deep copy of all enumeration-values and enumeration-value-translations and store that instead (which means that the validation really should'nt fail), but i think this is really not the way it should be done...
Another strange thing is, that the validation only fails if I iterate through the data. If i dont touch the data at all, no error occures, but the data isn't saved too, meaning that the folowing lines are causing the validations to be evaluated at all:
enumeration.enumerationValues.each() { ev ->
ev.enumerationValueTranslations.each() { evt ->
}
}
thats why i strongly believe that there must be some non-trivial problem... please let me know if there is anything else you need to know.
thanks for any help
Let me take another try :)
I'm looking at UniqueConstraint.processValidate(), and can suppose that its logic does not consider the exchange case.
Particularly, the code
boolean reject = false;
if (id != null) {
Object existing = results.get(0);
Object existingId = null;
try {
existingId = InvokerHelper.invokeMethod(existing, "ident", null);
}
catch (Exception e) {
// result is not a domain class
}
if (!id.equals(existingId)) {
reject = true;
}
}
else {
reject = true;
}
should iterate the obtained results and verify that the field value STILL violates uniqueness. In case of exchange, the other instance should be picked from a cache and have a new field value.
So I'd suggest you create an own descendant of UniqueConstraint and use it, unless anyone's going to patch Grails.

Resources