Visual Studio 2015 Encapsulate Field - c#

In Visual Studio 2013 when I encapsulate a field starting with i letter. It generates a property with starting letter I
int inside = 0;
public int Inside
{
get { return inside; }
set { inside = value; }
}
But in Visual Studio 2015 if I encapsulate the same field it generates a property starting with İ letter. Applying some indentation rules and adding a space between get and set modifiers
int inside = 0;
public int İnside
{
get
{
return inside;
}
set
{
inside = value;
}
}
How can I change this behaviour? I am using a Turkish keyboard if it is relevant and system culture is Turkish

You typed the Turkish i by mistake, instead of the English i.
It seems this is a debug of the refactoring code, which doesn't handle the user's culture in a safe way when converting the first letter to uppercase.
The Turkish i is one of the most common examples used to demonstrate the differences between cultures, as I is the upper case of `ý. Check for example the Writing Culture-Safe Managed Code article in MSDN.
Make sure you've switched your keyboard to English when you want to type Latin variable names.
As the OP commented, the outcome isn't affected by the keyboard language but the user's locale. This means that the Roslyn refactoring responsible for encapsulating fields perform a ToUpper call using the current CultureInfo instead of the invariant one.
Roslyn refactorings are available as open source so it's easy to find the relevant code. In AbstractEncapsulateFieldService.cs, the GeneratePropertyName method makes a call to char.ToUpper without specifying a culture:
return char.ToUpper(baseName[0]).ToString() + baseName.Substring(1);
It should be easy to change this to :
return char.ToUpper(baseName[0],CultureInfo.InvariantCulture).ToString()
+ baseName.Substring(1);
UPDATE
I opened an issue on the Roslyn site.
UPDATE 2
Unfortunately, the issue was closed as "By Design". It seems that whoever closed it confused the user's locale settings with the language used when writing text

Related

how to store "file://" in string format in c#

i want to store file:// as constant string to check is a particular String is URL.
public readonly String[] URLHEAD = { "http://", "https://","file://","\\\\" };
but but am not able to do it.
It's just the coloring indicating that it's a clickable link, exactly as if you start typing www after http://.
I wonder what made you think that you were unable to do something. You could compile and run your code anyway!
I highly suggest you try to pay more attention, as this "issue" was NOT really worth a question here.
Your code will work even if the color is blue. It is just an IDE setting as #Backs mentioned. But if you are really concerned with how it is marked up in your IDE then you can turn off the setting.
I'm assuming you are using Visual Studio.
Go to Tools\Options\Text Editor\C#\General\Enable single click URL navigation

An easy way to refactor Enums to include numeric value?

I`ve got a bunch of Enums that have been generated from an XSD. They have formats like the following (enums with names, but not numeric values):
public enum MyEnum
{
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("001")]
Item001,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("002")]
Item002,
.... // etc.
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("199")]
Item199,
}
What I would like is a simple way to refactor these as follows:
public enum MyEnum
{
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("001")]
Item001 = 1,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("002")]
Item002 = 2,
.... // etc.
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("199")]
Item199 = 199,
}
I need this in order to parse integer values (from a config-file or a DB) into enum values. Note that the needed int values are found both in the XmlEnumAttribute, and in the enum value name itself - just not as a numeric value.
Any ideas for performing this refactoring quickly would be greatly appreciated.
Example and extra background info:
I want to do:
var myEnumValue = (MyEnum) integerFromDb;
I realize that I could probably solve this by creating a method that appends the int value of each piece of data to the string Item, and parses it to an enum using the resulting name, but that has a couple of weaknesses:
Feels like a dirty hack
Might not work properly for names like MyEnum.Item02 and MyOtherEnum.Item002
It would not allow me to refer to enum values using the integer values that are defined outside my system (i.e. this would not be in proper compliance with the rules in the XSD that my enums are based on).
You can use Visual Studio's search-and-replace feature to do this without too much trouble (note…I am assuming VS2013 here, which uses the standard .NET regex syntax; earlier versions of VS can do this also, but they use a custom regex syntax, which you can look up yourself if needed):
Open your source file. Make sure every enum value is declared identically; in particular, put a comma after even the last one.
Press Ctrl+H to show the search-and-replace UI
Enter Item(\d+), as your text to find, and Item$1 = $1, as the replacement text.
Make sure the scope is set to "Current Document".
Press Alt+A. This will replace all matches in the file.
This actually is enough to get the code to compile as you want. But you may prefer to remove leading 0 digits. You can again use the search-and-replace to do that:
Enter = 0 as the text to find, and = as the replacement text.
Press Alt+A twice (because you have at most two leading zeroes)
Finally: as far as your idea of handling it in run-time only, converting via the value name would indeed be potentially problematic, given the dependency on the exact formatting of the name. But note that you have a true parseable integer here, in the [XmlEnum] attribute.
So if you wanted to create the necessary dictionaries for converting (you wouldn't want to keep inspecting the attribute itself, as reflection is slow), you could enumerate the enum type via reflection, get the attributes for each value, parse the string found in the XmlEnumAttribute.Name property, and use that to create dictionary entries, i.e. in a Dictionary<int, MyEnum> and Dictionary<MyEnum, int> to facilitate conversion in either direction.
I've already accepted the answer by Peter Duniho, but would like to expand a little more on it here, since I used a couple of variations:
In my generated file, most of the enums were in the same file, and for some of them, then values had already been replaced. Running the "Replace All" procecure would therefore cause other problems.
Replace next
Therefore, instead of Alt + A (replace all) to replace all matches, I used Alt + R (replace next) repeatedly to loop through and replace only those matches necessary. This let me quickly loop through all my code, without messing up what was already fixed.
F3 (Find Next) can be used as in a normal search, to skip matches that should not be altered.
Leading zeros
I didn't want to remover the 0 in e.g. Item010 = 0, which would be invalid, so I used the following search term instead: = 0\d, which finds only leading zeros (i.e. zeros followed by another number).

Guid.Parse failure with valid Guid - Encoding issue?

So, I have a valid GUID string below
Guid.Parse("e6f85ae0-f479-4e98-9287-98f7e62ba083") // Parses just fine
This parses to a GUID in .NET4.0 / 4.5
However this code
// Copy paste this line in VS Immediate window. Does not parse!!
Guid.Parse("e6f85ae0‐f479‐4e98‐9287‐98f7e62ba083")
Does not parse. The Guid strings are identical, or so I thought. Try it, in the immediate window of Visual Studio, the first does not parse, but second one does!
You can also verify with this code
var string1 = "e6f85ae0-f479-4e98-9287-98f7e62ba083";
var string2 = "e6f85ae0‐f479‐4e98‐9287‐98f7e62ba083";
bool isSame = string1.Equals(string2); // Equals false!! :/
Could this be an encoding issue? Is there any way to detect this issue and correctly parse the GUID?
I'm half convinced this is a trolling question, but in case it is an honest problem:
Those strings are not identical. the second one uses the so called 'narrow hyphen' ('\u2010'), which is a completely different character than the regular hyphen ('\u002D') and as such it is not parsed correctly.
As decPL already said the the strings are not identical due to different hyphens used, So Guid.Parse will definitely fail. To detect that the GUID is computer readable you can use Guid.TryParse Method.
bool isValidGUID = Guid.TryParse(string2, null);
And there is nothing called human readable If you are going to replace 'narrow hyphen' then in case it contains some other symbol your code will fail.
Instead of using workaround I suggest you the debug the cause for getting the 'narrow hyphen'
GUID also supports various formats. If you want to validate a specified format then you can use Guid.TryParseExact Method.

find all occurrences of comparison with == in visual studio

I made the mistake of using == for comparing IP addresses instead of using the equals() method of the IPAddress class in C#, which will result in the comparison of references instead of values.
Since the solution I am currently working on is very large for a one-man project (> 100.000 lines of source code), I am very sure that I still have some of these wrong statements in my code.
Is there any possibility to tell Visual Studio to find all occurrences of == operations on a specific class for me, so that I can find and clean up the bugged comparisons?
with best regards, emi
It's a bit of a hack but you can temporarily add this class to your project:
namespace System.Net
{
class IPAddress
{
[Obsolete]
public static bool operator ==(IPAddress a, IPAddress b) { return true; }
[Obsolete]
public static bool operator !=(IPAddress a, IPAddress b) { return true; }
}
}
Compile and look for warnings about using obsolete methods:
Warning 'IPAddress.operator ==(IPAddress, IPAddress)' is obsolete
Once you have fixed the code, remove the class definition.
You could always use a find / replace on "==". You can use the filters to determine what / where you want to search or just use the Entire Solution.
You might be able to use .NET Reflector or maybe the Visual Studio call hierarchy window to look for calls to the operator== method of the IPAdress class. I don't know if this is possible, just throwing out an idea.
If you know the name of the variable representing the IP address over your code, then yes, it is possible with some workaround. Say your variable is called 'ipAddress'. Then do this:
Using wildcards search for:
ipAddress*==
Then loop through the results and make a macro that make the change for you. For example, let's suppose your statement looks like this:
if (ipAddress == anotherIpAddress) {
Then you make a micro as follows:
Start Recording
Press Home # This will go to the beginning of the line
Ctrl+Right Three Times # This will keep the cursor on the beginning of anotherIpAddress
Backspace # This will remove the space
.equals( # This will write .equals(
Del Three Times # This will delete the == and the space after it
Ctrl+Right # This will keep you at the closing bracket ).
) # This will write another closing bracket for the equals functions.
Stop Recording
Now you have a macro that change the line for you. All you have to do is to repeatedly press F4 then Ctrl^P. Pressing F4 moves you to the next results in Find in Files (I suppose you will use this), and pressing Ctrl^P executes the macro.
There is a better solution actually using regular expressions but I am not sure whether it works with visual studio. Basically, it groups elements in Find and use them in Replace. So you search for something like "ipAddress == ( < my variable pattern > )" and replace it with "ipAddress.equals(\1)", the one here refers to the first group.
Hope that helps!
You might subclass IPAddress and override the == operator. This of course depends on how easily you can replace the references. Once you've done that, you could stop there or replace all instances of your == operator with .Equals()

Character / Language

I just developed a simple asp.net mvc application project for English only. I want to block user's any input for a language other than English. Is it possible to know whether user inputs other languages when they write something on textbox or editor in order to give a popup message?
You could limit the input box to latin characters, but there's no automatic way to see if the user entered something in say English, Finnish or Norwegian. They all mostly use a-z. Any character outside of a-z could give you an indication, but certain accents needs to be allowed in English as well, so it's not 100%.
Google Translate exposes a javascript API to detect the language of text.
Use the following code:
<p>Note that this community uses the English language exclusively, so please be
considerate and write your posts in English. Thank you!</p>
there are two tests you can do. one is to find out what the cultureinfo is set on the users machine:
http://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture.aspx
this will give you their current culture setting, which is a start. of course, you can have your setting as 'english' but still typing in russian, and most of the letters will be the same..
so the next step is to discover the language using this: http://www.google.com/uds/samples/language/detect.html
it's not the greatest, according to online discussions, but its a place to start. I'm sure there are better natural language identifiers out there, though.
Checking for Latin 26
If you wanted to ensure that any non-English letters were submitted, you could simply validate that they fall outside the A-Z, a-z, 0-9 and normal punctuation ranges. It sounds like you want the regular non-Latin characters to be detected and rejected.
Detecting the user's OS settings, keyboard settings isn't the best way, as the user could have multiple keyboards attached, and have use of copy/paste.
UI Validation
At the user interface level, you could create a jQuery method that would check the value of a textbox for a value other than your acceptable range. Perhaps that's A-Z, a-z and numeric. You could do this on event onBlur. Remember that you might want to allow ', .
$('#customerName').blur(function() {
var isAlphaNumeric;
//implementation of checking a-z, A-Z, 0-9, etc.
alert(isAlphaNumeric);
});
Controller Validation
If you wanted to ALSO implement this at the controller level, you could run a regex on the incoming values.
public ActionMethod CreateCustomer(string custName)
{
if (IsAcceptableRange(custName))
{
//continue
}
}
public bool IsAcceptableRange(string input)
{
//whitelist all the valid inputs here. be sure to include
//space, period, apostrophe, hypen, etc
Regex alphaNumericPattern=new Regex("[^a-zA-Z0-9]");
return !alphaNumericPattern.IsMatch(input);
}
Google Translate was quoted in two answers, but I want to add that Microsoft Word API may also be used to detect language, just like Word does for check spelling.
It is for sure not the best solution, since language detection by Microsoft Office doesn't work very well (IMHO), but may be an alternative if doing web requests to Google or other remote service on every posted message is not a solution.
Also, check spelling through Microsoft Word API can be useful too. If a message has a huge number of misspelled words when checking in English, it's probably because the message is written in another language (or the author of the message writes too badly, too).
Finally, I completely agree with Matti Virkkunen. The best, and maybe the only way to ensure that messages will be written in English is to ask the users to write in English. Otherwise, it's just as bad as implementing obscenity filters.

Categories