|
|
.NET programming Questions and Answers
|
|
.NET is a common purpose programming platform. It can be used for any workload or any sort of application where general purpose solutions are used. Questions include code examples that enough to understand the problems.
|
|
|
Sometimes you have C# code and when it runs, it throws a NullReferenceException with the following error message: "Object reference not set to an instance of an object" What does this mean? How can we handle that?
Update the GUI from another thread
What is the easiest way to update a Label control on a form from another thread in C#?
Random number generator generats only one random number
Random does not make any guarantees of thread-safety. To prevent that we may synchronize so that we do not access it at the same time from different threads, or use different Random instances per thread.
How to use the reflection to call a generic method?
Sometimes we have to figure out a right way to call a generic method when the type parameter is not known at compile time, but instead is obtained dynamically at runtime.
Properly clean up Excel interop objects
In your .NET app the Excel interop process is still in the background even after you close Excel. It is only released once your .NET application is closed manually.
Control accessed from a thread other than the thread it created on since Cross-thread operation not valid
Sometimes when you are trying to use multi-threading in a winforms app so that while it is running a long process, UI would get locked up. However after the task has finish and it try to update the UI you may get the error: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on when you try to execute a C# windows application.
Clone or deep copy an object
We are creating a child object of some data type object. How to make possible to clone / deep copy an object so that the deep copied object can be modified without any changes being reflected in the initial object?
Create Excel (.XLS and .XLSX) file using C#
Create an Excel Spreadsheet in .NET without requiring Excel to be installed on the PC that is executing the application.
The actual problem with mutable structs
Mutable objects usually have multiple properties. Is this an actual problem with C# structs mutability?
Convert Hexadecimal String to Byte Array, and vice versa
Any hex string that validly represents a byte array must have an even character count. Using Substring is the best option in combination with Convert.ToByte.
IndexOutOfRangeException and how to fix it?
Some .NET app code when executes gives you an IndexOutOfRangeException, with the message: "Index was outside the bounds of the array". What does this mean? How can you handle that?
Is Application.DoEvents() useful in C#?
Can we use the Application.DoEvents() in C#? Is this function a method to allow the GUI to catch up with the whole .NET application?
Dynamic LINQ OrderBy on IEnumerable<T>
You will need the dynamic LINQ library to implement LINQ ordering functionality on IEnumerable<T>.
How to encrypt and decrypt a string?
The troublesome part about string encryption actually deals with the keys and not the algorithms. You should be worry about where you store your keys, and if you have to, how you exchange them.
Send email in .NET via a public email account like Yahoo or Gmail
Instead of sending emails from your host, you may suggest of sending your email messages though a public account (Gmail, Yahoo, etc.). How to implement such emailing jobs?
The difference between String and string in C#
What is the differences between: string s = "Hello world!"; and String S = "Hello world!";? What are the directions for the use of each?
How to use the IDisposable interface correctly?
The main use of the IDisposable interface is to clean up unmanaged resources.
How to check if a file is in use?
Sometimes you are in need to repeatedly regenerate, access, and then close the same binary temp file. Usually it works without problem. However if PC runs slow, it will try to access the file before it has been stored back to the hard drive with the following error message: "File in use by another process".
|
|
Update the GUI from another thread
What is the easiest way to update a Label control on a form from another thread in C#?
Run the following code:
|
Then call that by using the following code:
|
this.ThreadCall(() => this.Label1.Text = "Write New Text Here");
|
|
Random number generator generats only one random number
Random does not make any guarantees of thread-safety. To prevent that we may synchronize so that we do not access it at the same time from different threads, or use different Random instances per thread.
|
Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the initial instance.
|
So Next is going to change the internal state of the Random instance. If we do that at the same time from multiple threads, you may reason "I just have made the output even more random", but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since Random does not make any guarantees of thread-safety.
|
|
How to use the reflection to call a generic method?
Sometimes we have to figure out a right way to call a generic method when the type parameter is not known at compile time, but instead is obtained dynamically at runtime.
|
What is the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?
Consider the following sample code: within the Example() function, what is the most concise way to invoke GenericMethod<T>() using the Type stored in the newType param?
|
You need to use reflection to get the method to start with, then create that by sending type params with MakeGenericMethod:
|
For a static method, pass null as the first argument to Invoke. That is nothing to do with generic methods cause that is a normal reflection.
|
|
Properly clean up Excel interop objects
In your .NET app the Excel interop process is still in the background even after you close Excel. It is only released once your .NET application is closed manually.
|
Excel does not quit because .NET application is still holding references to COM objects. When your app is invoking at least one member of a COM object without assigning it to a variable. In the following code the excelApp.Worksheets object which is directly used without assigning it to a variable:
|
The .NET code internally created a wrapper for the Worksheets COM object which did not get released by the code and was the cause why Excel was not unloaded.
The sheets variable in the code below has a COM reference that will not be released until its garabage was collected. The rule is: never use 2 dots with com objects!
Always create a sheet, and call ReleaseComObject() on the sheets.
|
|
Control accessed from a thread other than the thread it created on since Cross-thread operation not valid
Sometimes when you are trying to use multi-threading in a winforms app so that while it is running a long process, UI would get locked up. However after the task has finish and it try to update the UI you may get the error: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on when you try to execute a C# windows application.
|
Please use an extension method and lambdas to make your code much cleaner.
|
Now please use InvokeEx on any ISynchronizeInvoke and be able to access the properties and fields of implementing class.
|
this.InvokeEx(f => f.listView1.Items.Clear());
|
|
Clone or deep copy an object
We are creating a child object of some data type object. How to make possible to clone / deep copy an object so that the deep copied object can be modified without any changes being reflected in the initial object?
|
One way to guarantee that an object will be cloned exactly how you want it is to manually clone every field in the object. The disadvantage to this method is it's tedious and error prone: if you add or change a field in the class, chances are you will forget to update the Clone method. Note that care must be taken to avoid an infinite loop when cloning referenced objects that may refer back to the original object. Here is a simple example that performs a deep copy:
|
Another way is to Clone with MemberwiseClone. MemberwiseClone is a protected method in the Object class that creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. For value-type fields, this performs a bit-by-bit copy. For reference-type fields, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object. Note this works for all derived classes, and hence you only need to define the Clone method once in the base class. Take a look at the simple code below:
|
|
The actual problem with mutable structs
Mutable objects usually have multiple properties. Is this an actual problem with C# structs mutability?
|
Consider this code which is trying to mutate a readonly mutable struct. What the output is expected to be?
|
This code will print 1, 1, 1. Because accessing a value type gives you a copy of the value. When you say t.m, you get a copy of whatever is presently stored in m. The m is immutable, but the copy is not. The copy is then mutated, and the value of x in the copy is returned. But m remains non-modified.
This is yet another reason why mutable value types are evil. Try to always make value types immutable.
|
|
Convert Hexadecimal String to Byte Array, and vice versa
Any hex string that validly represents a byte array must have an even character count. Using Substring is the best option in combination with Convert.ToByte.
|
It is easy. First, Byte Array to String:
|
Revers conversion, String to Byte Array:
|
|
IndexOutOfRangeException and how to fix it?
Some .NET app code when executes gives you an IndexOutOfRangeException, with the message: "Index was outside the bounds of the array". What does this mean? How can you handle that?
|
The exception's error message says that you are trying to access a collection item by its index, using an invalid index. An index number value is incorrect when it is greater than (or equal) the collection's number of elements it contains or lower than to the collection?s lower bound. For example you have declared an array as:
|
string[] stringArray = new string[5];
|
You can access the string array from 0 to 4. Any numeric values outside this range will generate the IndexOutOfRangeException. Do not forget that when you declare and access an array in your code.
|
|
Is Application.DoEvents() useful in C#?
Can we use the Application.DoEvents() in C#? Is this function a method to allow the GUI to catch up with the whole .NET application?
|
The usage of Application.DoEvents is an indication of a bad .NET application design. You should consider to do some code in separated threads instead.
You may call the static DoEvents method on the Application class in the System.Windows.Forms namespace. Application.DoEvents() is used to pump messages in the UI thread when performing a long-running task in the UI thread. This is almost always not the best way to do things. The better solution would be to do all of your application interface actions on another thread, and then run the Invoke method on a control, passing a delegate to update the UI when necessary. This will cause a message to be sent to the UI thread to update itself, but since you are handling all of the processing on the other thread, it should be updated immediately.
|
|
Dynamic LINQ OrderBy on IEnumerable<T>
You will need the dynamic LINQ library to implement LINQ ordering functionality on IEnumerable<T>.
|
Make a reference to the System.Linq.Dynamic.dll library. Then put the using System.Linq.Dynamic; declaration into the declarative region in which the using declarations appear in your .NET code. To code the LINQ ordering functionality write down in your code something like the following:
cars = cars.AsQueryable().OrderBy("Make ASC, Year DESC").ToList();
If you are going to do the ordering without the dynamic LINQ library, you will need to implement the below code. This covers most common scenarios including nested properties. To get it working with IEnumerable<T> you could add some wrapper methods that go via AsQueryable, but the presented code is the core Expression logic needed.
|
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "OrderBy");
}
public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "OrderByDescending");
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "ThenBy");
}
public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "ThenByDescending");
}
static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName) {
string[] props = property.Split('.');
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
foreach(string prop in props) {
// use reflection (not ComponentModel) to mirror LINQ
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
object result = typeof(Queryable).GetMethods().Single(
method => method.Name == methodName
&& method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] {source, lambda});
return (IOrderedQueryable<T>)result;
}
|
|
How to encrypt and decrypt a string?
The troublesome part about string encryption actually deals with the keys and not the algorithms. You should be worry about where you store your keys, and if you have to, how you exchange them.
|
We will not bother and go deep into the jungle. We will just show you how to decrypt and encrypt a string by using a wrapper object to access the cryptographic service provider (CSP) version of the Data Encryption Standard (DES) algorithm.
|
public string EncryptString(string inputString){
MemoryStream ms = null;
try{
byte[] IV = {12, 43, 67, 27, 17, 21, 57, 35};
string encryptKey = "password"; // 8 characters key
byte[] key = {};
key = Encoding.UTF8.GetBytes(encryptKey);
byte[] byteInput = Encoding.UTF8.GetBytes(inputString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ms = new MemoryStream();
ICryptoTransform transform = provider.CreateEncryptor(key, IV);
CryptoStream cryptoStream = new CryptoStream(ms, transform, CryptoStreamMode.Write);
cryptoStream.Write(byteInput, 0, byteInput.Length);
cryptoStream.FlushFinalBlock();
}
catch (Exception ex){
Response.Write(ex.Message);
}
return Convert.ToBase64String(ms.ToArray());
}
public string DecryptString(string inputString){
MemoryStream ms = null;
try{
byte[] IV = {12, 43, 67, 27, 17, 21, 57, 35};
string decryptKey = "password"; // 8 characters key
byte[] key = {};
key = Encoding.UTF8.GetBytes(decryptKey);
byte[] byteInput = new byte[inputString.Length];
byteInput = Convert.FromBase64String(inputString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ms = new MemoryStream();
ICryptoTransform transform = provider.CreateDecryptor(key, IV);
CryptoStream cryptoStream = new CryptoStream(ms, transform, CryptoStreamMode.Write);
cryptoStream.Write(byteInput, 0, byteInput.Length);
cryptoStream.FlushFinalBlock();
}
catch (Exception ex){
Response.Write(ex.Message);
}
Encoding encoding1 = Encoding.UTF8;
return encoding1.GetString(ms.ToArray());
}
|
|
Send email in .NET via a public email account like Yahoo or Gmail
Instead of sending emails from your host, you may suggest of sending your email messages though a public account (Gmail, Yahoo, etc.). How to implement such emailing jobs?
|
Use Gmail Smtp client which allows you to send email messages by using SMTP Protocol.
|
|
The difference between String and string in C#
What is the differences between: string s = "Hello world!"; and String S = "Hello world!";? What are the directions for the use of each?
|
The string is an alias in C# for System.String. So technically, there is no difference.
So the String stands for System.String and it is a .NET Framework type. string is an alias in the C# language for System.String. Both of them are compiled to System.String in MSIL (Intermediate Language), so there is no difference. Choose what you like and use that.
We can mention the same about (int, System.Int32)
Howevere... :)
string is a reserved word, but String is just a class name. This means that string cannot be used as a variable name by itself.
If for some reason you wanted a variable called string, you would see only the first of these compiles:
|
StringBuilder String = new StringBuilder(); // compiles
StringBuilder string = new StringBuilder(); // does not compile
|
If you really want a variable name called string you can use @ as a prefix:
|
StringBuilder @string = new StringBuilder();
|
|
How to use the IDisposable interface correctly?
The main use of the IDisposable interface is to clean up unmanaged resources.
|
IDisposable is often used to operate the using statement and take advantage of an easy way to do deterministic cleanup of managed objects.
|
|
How to check if a file is in use?
Sometimes you are in need to repeatedly regenerate, access, and then close the same binary temp file. Usually it works without problem. However if PC runs slow, it will try to access the file before it has been stored back to the hard drive with the following error message: "File in use by another process".
|
You can accomplish that creating checks by using exception handling only.
|
|