Archive for the ‘C# 5.0’ Category
Posted by jpluimers on 2012/12/06
Thanks Nick Craver for answering this on StackOverflow.
Array initializers can be specified in field declarations (§17.4), local variable declarations (§15.5.1), and
array creation expressions (§14.5.10.2).
The array initializer can end in a comma, which makes some things way easier (boy, I wish I had this in other programming languages).
From Nick’s answer:
It has no special meaning, just the way the compiler works, it’s mainly for this reason:
[FlagsAttribute]
public enum DependencyPropertyOptions : byte
{
Default = 1,
ReadOnly = 2,
Optional = 4,
DelegateProperty = 32,
Metadata = 8,
NonSerialized = 16,
//EnumPropertyIWantToCommentOutEasily = 32
}
[/language]By comment request: This info comes straight out of the ECMA C# Specification (Page 363/Section 19.7)
“Like Standard C++, C# allows a trailing comma at the end of an array-initializer. This syntax provides flexibility in adding or deleting members from such a list, and simplifies machine generation of such lists.”
–jeroen
via c# – .NET Enumeration allows comma in the last field – Stack Overflow.
Posted in .NET, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, C++, Delphi, Development, Java, JavaScript/ECMAScript, PHP, Software Development, VB.NET | 5 Comments »
Posted by jpluimers on 2012/12/04
WinForms does not automatically enable Ctrl-A as “Select All” action.
The below code snippet works when you bind it to the KeyDown event of a TextBox (actually the event is on Control).
The e.SuppressKeyPress = true suppresses the bell sound in a multiline TextBox, as e.Handled = true won’t.
private void textBox_KeyDown_HandleCtrlAToSelectAllText(object sender, KeyEventArgs e)
{
TextBox textBox = sender as TextBox;
if (null != textBox)
{
if (e.Control && e.KeyCode == Keys.A)
{
textBox.SelectAll();
e.SuppressKeyPress = true;
}
}
}
–jeroen
Posted in .NET, .NET 1.x, .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0, .NET 4.5, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Software Development | Leave a Comment »
Posted by jpluimers on 2012/11/21
Often when comparing characters with a list of characters, that list does not consist of consts.
It if were, you could make a switch statement:
switch (item)
{
case '/':
case '\\':
case ';':
addSeparator(separatorsUsed, item);
break;
}
But reality is that you cannot do things like this:
switch (item)
{
case Path.AltDirectorySeparatorChar: // Error: A constant value is expected
case Path.DirectorySeparatorChar:
case Path.PathSeparator:
addSeparator(separatorsUsed, item);
break;
}
However, you can perform a small trick and use LINQ to write some pretty elegant code based on Contains.
char[] pathSeparators = { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar, Path.PathSeparator };
// LINQ: http://stackoverflow.com/questions/1818611/how-to-check-if-a-char-in-a-char-array/1818635#1818635
if (pathSeparators.Contains(item))
addSeparator(separatorsUsed, item);
The LINQ logic has the logic backwards (you can think of it like “item in pathSeparators”, but it is far easier to read than this:
if ((item == Path.AltDirectorySeparatorChar) || (item == Path.DirectorySeparatorChar) || (item == Path.PathSeparator))
addSeparator(separatoseparatorsUsedrsInUse, item);
Full source of a demo application: Read the rest of this entry »
Posted in .NET, .NET 3.5, .NET 4.5, C#, C# 3.0, C# 4.0, C# 5.0, Development, LINQ, Software Development, Visual Studio 11, Visual Studio 2008, Visual Studio 2010, Visual Studio and tools | 2 Comments »
Posted by jpluimers on 2012/11/20
A while ago I had a “duh” moment while calling a method that had many overloads, and one of the overloads was using int, not the char I’d expect.
The result was that a default value for that char was used, and my parameter was interpreted as a (very small) buffer size. I only found out something went wrong when writing unit tests around my code.
The culprit is this C# char feature (other implicit type conversions nicely summarized by Muhammad Javed):
A char can be implicitly converted to ushort, int, uint, long, ulong, float, double, or decimal. However, there are no implicit conversions from other types to the char type.
Switching between various development environments, I totally forgot this is the case in languages based on C and Java ancestry. But not in VB and Delphi ancestry (C/C++ do numeric promotions of char to int and Java widens 2-byte char to 4-byte int; Delphi and VB.net don’t).
I’m not the only one who was confused, so Eric Lippert wrote a nice blog post on it in 2009: Why does char convert implicitly to ushort but not vice versa? – Fabulous Adventures In Coding – Site Home – MSDN Blogs.
Basically, it is the C ancestry: a char is an integral type always known to contain an integer value representing a Unicode character. The opposite is not true: an integer type is not always representing a Unicode character.
Lesson learned: if you have a large number of overloads (either writing them or using them) watch for mixing char and int parameters.
Note that overload resolution can be diffucult enough (C# 3 had breaking changes and C# 4 had breaking changes too, and those are only for C#), so don’t make it more difficult than it should be (:
Below a few examples in C# and VB and their IL disassemblies to illustrate their differnces based on asterisk (*) and space ( ) that also show that not all implicits are created equal: Decimal is done at run-time, the rest at compile time.
Note that the order of the methods is alphabetic, but the calls are in order of the type and size of the numeric types (integral types, then floating point types, then decimal).
A few interesting observations:
- The C# compiler implicitly converts char with all calls except for decimal, where an implicit conversion at run time is used:
L_004c: call valuetype [mscorlib]System.Decimal [mscorlib]System.Decimal::op_Implicit(char)
L_0051: call void CharIntCompatibilityCSharp.Program::writeLineDecimal(valuetype [mscorlib]System.Decimal)
- Same for implicit conversion of byte to the other types, though here the C# and VB.NET compilers generate slightly different code for run-time conversion.
C# uses an implicit conversion:
L_00af: ldloc.1
L_00b0: call valuetype [mscorlib]System.Decimal [mscorlib]System.Decimal::op_Implicit(uint8)
L_00b5: call void CharIntCompatibilityCSharp.Program::writeLineDecimal(valuetype [mscorlib]System.Decimal)
VB.NET calls a constructor:
L_006e: ldloc.1
L_006f: newobj instance void [mscorlib]System.Decimal::.ctor(int32)
L_0075: call void CharIntCompatibilityVB.Program::writeLineDecimal(valuetype [mscorlib]System.Decimal)
Here is the example code: Read the rest of this entry »
Posted in .NET, Agile, Algorithms, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, C++, Delphi, Development, Encoding, Floating point handling, Java, Software Development, Unicode, Unit Testing, VB.NET | 1 Comment »
Posted by jpluimers on 2012/11/15
A while ago, one of the users at a client got an error in a .NET 1.1 app of which the sources were not readily available:
“application has generated an exception that could not be handled”
I think it is a e0434f4d exception.
This particular site has very strict rules about what you can and cannot do as a developer. Which means that on a production system, you basically cannot do anything.
A few links that should help me finding the solution, and escalate far enough upstream to get someone with local admin rights to assist me:
If WinDbg is allows to be ran, these should help me:
–jeroen
Posted in .NET, .NET 1.x, .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0, .NET 4.5, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Software Development | Leave a Comment »
Posted by jpluimers on 2012/11/14
Over the course of development time, each suite of projects is bound to get some renames.
Doing that from the Visual Studio IDE is a pain, so I was glad to find Visual Studio Project Renamer by ComVisible.
Though it only supports C# and VB.NET projects (so no solution rename or rename of F#, Database or Reporting Service projects, nor stuff outside of the Microsoft realm like Prism).
These Just geeks: Renaming a Visual Studio Project link led me to the project.
Renaming solutions still is largely a manual operation as it involves renaming directories. You have to re-add some (sometimes all) projects later where this tool can come in handy: CoolCommands by SharpToolbox.
–jeroen
via:
Posted in .NET, C#, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, F#, Prism, Software Development, VB.NET, Visual Studio and tools | Leave a Comment »
Posted by jpluimers on 2012/11/08
Handling names of drives and paths (directories, filenames) is hard in Windows, as both C:myfile.ext and C:\myfile.ext are valid – but potentially different – filenames, C is a valid driveletter, C: and C:\ are valid – but also potentially different – directory names.
This leads into confusion as how Path.Combine behaves.
Part of the confusion comes from the meaning of the absence or presence of the leading DirectorySeparatorChar as explained by user Peter van der Heijden:
C:filename is a valid path and is different from C:\filename. C:filename is the file filename in the current directory on the C: drive whereas C:\filename is the file filename in the root of that drive. Apparently they wanted to keep the functionality of refering to the current directory on some drive.
This behaviour is described here in MSDN
Another oddity is that Path.Combine will only use the drive portion of the left argument when the right argument contains an absolute path.
If you understand the above, then dealing with cross platform directory and path separators, spaces in filenames and UNC path names are peanuts (:
–jeroen
via: .net – Why Path.Combine doesn’t add the Path.DirectorySeparatorChar after the drive designator? – Stack Overflow.
Posted in .NET, C#, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Software Development | Leave a Comment »
Posted by jpluimers on 2012/11/07
A while ago I needed to shorten SqlClient ConnectionStrings. One way to do that is to use the shortest Key for each property (and not use the default key names that are much longer).
I beefed up the code to show you both the shortest and all equivalent keys (a few of the Microsoft exams want you to memorize most of these).
The HTML table below (similar to the huge and therefore hard to read table on MSDN) comes directly from the C# code at the bottom of the post. The only post-editing I did was making the header row bold.
| Key |
ShortesEquivalentKey |
EquivalentKeys |
| Application Name |
app |
Application Name,app |
| ApplicationIntent |
ApplicationIntent |
ApplicationIntent |
| Asynchronous Processing |
async |
Asynchronous Processing,async |
| AttachDbFilename |
AttachDbFilename |
AttachDbFilename,extended properties,initial file name |
| Connect Timeout |
timeout |
Connect Timeout,connection timeout,timeout |
| Connection Reset |
Connection Reset |
Connection Reset |
| Context Connection |
Context Connection |
Context Connection |
| Current Language |
language |
Current Language,language |
| Data Source |
addr |
Data Source,addr,address,network address,server |
| Encrypt |
Encrypt |
Encrypt |
| Enlist |
Enlist |
Enlist |
| Failover Partner |
Failover Partner |
Failover Partner |
| Initial Catalog |
database |
Initial Catalog,database |
| Integrated Security |
trusted_connection |
Integrated Security,trusted_connection |
| Load Balance Timeout |
connection lifetime |
Load Balance Timeout,connection lifetime |
| Max Pool Size |
Max Pool Size |
Max Pool Size |
| Min Pool Size |
Min Pool Size |
Min Pool Size |
| MultipleActiveResultSets |
MultipleActiveResultSets |
MultipleActiveResultSets |
| MultiSubnetFailover |
MultiSubnetFailover |
MultiSubnetFailover |
| Network Library |
net |
Network Library,net,network |
| Packet Size |
Packet Size |
Packet Size |
| Password |
pwd |
Password,pwd |
| Persist Security Info |
persistsecurityinfo |
Persist Security Info,persistsecurityinfo |
| Pooling |
Pooling |
Pooling |
| Replication |
Replication |
Replication |
| Transaction Binding |
Transaction Binding |
Transaction Binding |
| TrustServerCertificate |
TrustServerCertificate |
TrustServerCertificate |
| Type System Version |
Type System Version |
Type System Version |
| User ID |
uid |
User ID,uid,user |
| User Instance |
User Instance |
User Instance |
| Workstation ID |
wsid |
Workstation ID,wsid |
The code below uses a few techniques referenced as StackOverflow links:
- Sorting enumerable strings using LINQ.
- Generating CSV from an enumerable strings using LINQ and string.Join.
- Converting a DataTable to an HTML Table using an ASP.NET DataGrid and HtmlTextWriter to do the rendering.
- Getting a private static field by name using reflection.
Both the main program and the SqlConnectionStringBuilderHelper class are less than 70 lines of code (each about 50 when excluding comments and empty lines).
The SqlConnectionStringBuilderHelper uses the internals of the SqlConnectionStringBuilder class (all DbConnectionStringBuilder descendants I have seen work in a similar way):
- each DbConnectionStringBuilder instance has a public Keys property that exposes the static _validKeywords field of the descendant. It contains all possible keys that can appear in a generated ConnectionString.
- the SqlConnectionStringBuilder class (and other DbConnectionStringBuilder descendants) has a static private property _keywords that maps all possible keyword strings (including equivalents) to an enumerator (which indexes into the Keys property).
Mono uses the same mechanism.
- The trick is to walk the _keywords property and search for equivalent keywords.
- For a list of equivalent keywords, you find the shortest one.
Related:
Enjoy the code: Read the rest of this entry »
Posted in .NET, ASP.NET, C#, C# 3.0, C# 4.0, C# 5.0, CSV, Development, LINQ, Software Development | Leave a Comment »
Posted by jpluimers on 2012/11/06
Boy, was I astonished to see the code fragments below in production apps. It is far more Daily WTF than Coding Horror.
However, it did make debugging the production problem at hand a lot worse than it should be.
First a few short pieces:
private void method(Word.Application objNewDoc, string stringWithCsvSeparatedDotFileNames)
{
char c = char.Parse(",");
string[] wordAddIns = stringWithCsvSeparatedDotFileNames.ToString().Split(c);
}
It took me almost a minute to understand what happened here. Especially because the names of parameters actually were pretty meaningless.
foreach (string sFilename in attachments)
{
Word.Application mailDocument = new Word.Application();
string[] filePath = sFilename.Split('\\');
string tempDirectory = GetTempDirectoryFromConfigFile();
object fileName = tempDirectory + filePath[filePath.Length - 1];
File.Copy(sFile, (string)fileName, true);
// some code that actually does something with the attachment
}
It took me more than a few minutes to realize that:
- The tempDirectory needs to end with a backslash
- mailDocument (not a document, see below), will stay alive when File.Copy(…) throws an exception.
internal virtual bool Method(/* parameters */, Word.Application objDoc)
{
// lots of pre-initialized empty string variables that are used at the very end of the method
Word.Application objNewDoc;
if (objDoc != null)
{
objNewDoc = objDoc;
}
else
{
objNewDoc = new Word.Application();
}
// lots of Object variables for COM, including:
Object missing = Missing.Value;
Object bFalse = false;
try
{
// lots of code that does not use objNewDoc
}
catch (IOException IOex)
{
objNewDoc.Quit(ref bFalse, ref missing, ref missing);
objNewDoc = null;
throw IOex;
}
catch (Exception ex)
{
objNewDoc.Quit(ref bFalse, ref missing, ref missing);
objNewDoc = null;
throw new Exception("Some error message.", ex);
}
finally
{
// empty finally block
}
try
{
// actual coder that does use objNewDoc
}
catch (Exception ex)
{
objNewDoc.Quit(ref bFalse, ref missing, ref missing);
objNewDoc = null;
throw new Exception("Some error message.", ex);
}
return true;
}
I rewrote the whole piece into separate methods.
Luckily the person who wrote this got promoted away from programming a few years ago.
–jeroen
Posted in .NET, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Software Development | Leave a Comment »
Posted by jpluimers on 2012/10/31
The order of events and what you can do in events is very important in Windows applications.
This includes the WinForms applications – still popular for business applications – the first .NET framework that supported building Windows applications.
WinForms has two important event/method combo’s:
In descendants, you override the methods. In the form designer, you use the events.
Both the methods and events rely on Windows messages to get fired. This means they depends on which message loop is active. And this limits in what you can do during them.
One of the things you should not do in Load or Show is perform a MessageBox, ShowDialog or any other form of message pumping (like in COM).
Hans Passant explains it this way:
Avoid using MessageBox.Show() to debug this [ed: debug Shown/Load behaviour]. It pumps a message loop, disturbing the normal flow of events. The Load event is triggered by Windows sending the WM_SHOWWINDOW message, just before the window becomes visible. There is no Windows notification for “your window is now fully shown”, so the WF designers came up with a trick to generate the Shown event. They use Control.BeginInvoke(), ensuring the OnShown() method gets called as soon as the program goes idle again and re-enters the message loop.
This trick has lots of other uses, particularly when you have to delay the execution of code started by an event. However, in your case it falls apart because you use MessageBox.Show(). Its message loop dispatches the delegate registered with BeginInvoke(), causing the Shown event to run before the window is shown.
Krishnan Sriram explains that if you use proper debug logging (see what Hans wrote), you get this order of events:
- Form – Client Size Changed : 8/14/2010 10:40:28 AM
- Form – Control Added – button1 : 8/14/2010 10:40:29 AM
- Form – Constructor : 8/14/2010 10:40:29 AM
- Form – Handle Created : 8/14/2010 10:40:29 AM
- Form – Invalidated : 8/14/2010 10:40:29 AM
- Form – Form Load event : 8/14/2010 10:40:29 AM
- Form – Loaded : 8/14/2010 10:40:29 AM
- Form – Create Control : 8/14/2010 10:40:29 AM
- Form – OnActivated : 8/14/2010 10:40:29 AM
- Form – Shown : 8/14/2010 10:40:29 AM
- Form – OnPaint : 8/14/2010 10:40:29 AM
- Form – Invalidated : 8/14/2010 10:40:29 AM
- Form – OnPaint : 8/14/2010 10:40:29 AM
Finally, Ahmed Said indicates that there can be form size differences in the Load and Shown state:
The Shown event occured after the load event, the main difference is not in the visibility but in state of the form (width,hieght,..etc). I will give you an example to clarify if we create a form with default size 100,200 and set the windowstate = Maximized in the load event the size will be 100,200 but in shown event the size will be your screen size
–jeroen
via: .net – WinForms Load vs. Shown events – Stack Overflow.
Posted in .NET, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Software Development, WinForms | Leave a Comment »