Showing posts with label Windows Forms. Show all posts
Showing posts with label Windows Forms. Show all posts

Tuesday, October 25, 2016

Update the GUI From a Different Thread in C#

For .NET 2.0:
private delegate void SetControlPropertyThreadSafeDelegate(
    Control control, 
    string propertyName, 
    object propertyValue);

public static void SetControlPropertyThreadSafe(
    Control control, 
    string propertyName, 
    object propertyValue)
{
  if (control.InvokeRequired)
  {
    control.Invoke(new SetControlPropertyThreadSafeDelegate               
    (SetControlPropertyThreadSafe), 
    new object[] { control, propertyName, propertyValue });
  }
  else
  {
    control.GetType().InvokeMember(
        propertyName, 
        BindingFlags.SetProperty, 
        null, 
        control, 
        new object[] { propertyValue });
  }
}
Call it like this:
// thread-safe equivalent of
// myLabel.Text = status;
SetControlPropertyThreadSafe(myLabel, "Text", status);
If you're using .NET 3.0 or above, you could rewrite the above method as an extension method of the Control class, which would then simplify the call to:
myLabel.SetPropertyThreadSafe("Text", status);
For .NET 3.0 you should use this code:
private delegate void SetPropertyThreadSafeDelegate<TResult>(
    Control @this, 
    Expression<Func<TResult>> property, 
    TResult value);

public static void SetPropertyThreadSafe<TResult>(
    this Control @this, 
    Expression<Func<TResult>> property, 
    TResult value)
{
  var propertyInfo = (property.Body as MemberExpression).Member 
      as PropertyInfo;

  if (propertyInfo == null ||
      !@this.GetType().IsSubclassOf(propertyInfo.ReflectedType) ||
      @this.GetType().GetProperty(
          propertyInfo.Name, 
          propertyInfo.PropertyType) == null)
  {
    throw new ArgumentException("The lambda expression 'property' must reference a valid property on this Control.");
  }

  if (@this.InvokeRequired)
  {
      @this.Invoke(new SetPropertyThreadSafeDelegate<TResult> 
      (SetPropertyThreadSafe), 
      new object[] { @this, property, value });
  }
  else
  {
      @this.GetType().InvokeMember(
          propertyInfo.Name, 
          BindingFlags.SetProperty, 
          null, 
          @this, 
          new object[] { value });
  }
}
which uses LINQ and lambda expressions to allow much cleaner, simpler and safer syntax:
myLabel.SetPropertyThreadSafe(() => myLabel.Text, status); // status has to be a string or this will fail to compile
Not only is the property name now checked at compile time, the property's type is as well, so it's impossible to (for example) assign a string value to a boolean property, and hence cause a runtime exception.
Unfortunately, this doesn't stop anyone from doing stupid things such as passing in another Control's property and value, so the following will happily compile:
myLabel.SetPropertyThreadSafe(() => aForm.ShowIcon, false);
Hence I added the runtime checks to ensure that the passed-in property does actually belong to the Control that the method's being called on. Not perfect, but still a lot better than the .NET 2.0 version.

Tuesday, August 2, 2016

Using Extension Methods in C#


Following is an example use of an Extension method in C#.

Imagine you have a class written by someone else and you are not allowed to do any modification to the class.

   public class Class1
    {
        public int MyProperty { get; set; }
    }

You have come up with the following calculation and want to have it in the Class1, so that others could use it without rewriting the calculation.

int sum = p.MyProperty * 5;

Now, incomes the extension method.

public static class myextention
    {
        public static int test(this Class1 p)
        {
           
            return p.MyProperty * 5;
        }
    }

After creating the extension method, you can now call the test function as it’s defined in the Class1 itself.

Class1 c = new Class1();

int extensionSum = c.test();

Saturday, March 16, 2013

Rename Files in C#.NET

There is no separate method for renaming files in .NET. For the purpose of renaming files we can use MOVE() method as in below example
string path = "~/Tiles/";
string FromFile = path+"old.jpg";
string ToFile = path + "new.jpg";
if (File.Exists(Server.MapPath(FromFile)))
File.Move(Server.MapPath(FromFile), Server.MapPath(ToFile));

Thursday, January 31, 2013

Convert DataTable into a String

Following method will convert a DataTable into a string in the format of:

Column Header Name:-:Cell Value##Column Header Name:-:Cell Value##Column Header Name:-:Cell Value.....

public string DataTabletoString(DataTable DT)
{
  StringBuilder SB = new StringBuilder();
foreach (DataRow rowItem in DT.Rows)
{
foreach (DataColumn colItem in DT.Columns)
{
  SB.Append(colItem.ToString()+":- :"+rowItem[colItem].ToString()+"##");
}
}
  return SB.ToString();
}

Monday, January 14, 2013

The Exception Class in C#.NET

Every exception class derives from the base class System.Exception. The .NET Framework is full of predefined exception classes, such as NullReferenceException, IOException, SqlException, and so on. The Exception class includes the essential functionality for identifying any type of error. Below is a list of its most important members.

HelpLink 
A link to a help document, which can be a relative or fully qualified URL (uniform resource locator) or URN (uniform resource name), such as file:///C:/ACME/MyApp/help.html#Err42. The .NET Framework doesn’t use this property, but you can set it in your custom exceptions if you want to use it in your web page code.

InnerException 
A nested exception. For example, a method might catch a simple file IO (input/output) error and create a higher-level “operation failed” error. The details about the original error could be retained in the InnerException property of the higher-level error.

Message 
A text description with a significant amount of information describing the problem.

Source 
The name of the application or object where the exception was raised.

StackTrace 
A string that contains a list of all the current method calls on the stack, in order of most to least recent. This is useful for determining where the problem occurred.

TargetSite 
A reflection object (an instance of the System.Reflection.MethodBase class) that provides some information about the method where the error occurred. This information includes generic method details such as the method name and the data types for its parameter and return values. It doesn’t contain any information about the actual parameter values that were used when the problem occurred.

GetBaseException() 
A method useful for nested exceptions that may have more than one layer. It retrieves the original (deepest nested) exception by moving to the base

When you catch an exception in an ASP.NET page, it won’t be an instance of the generic System.Exception class. Instead, it will be an object that represents a specific type of error. This object will be based on one of the many classes that inherit from System.Exception. These include diverse classes such as DivideByZeroException, ArithmeticException, IOException, SecurityException, and many more. Some of these classes provide additional details about the error in additional properties.

Visual Studio provides a useful tool to browse through the exceptions in the .NET class library. Simply select Debug -> Exceptions from the menu (you’ll need to have a project open in order for this to work). The Exceptions dialog box will appear. Expand the Common Language Runtime Exceptions group, which shows a hierarchical tree of .NET exceptions arranged by namespace (see Figure).


The Exceptions dialog box allows you to specify what exceptions should be handled by your code when debugging and what exceptions will cause Visual Studio to enter break mode immediately. That means you don’t need to disable your error-handling code to troubleshoot a problem. For example, you could choose to allow your program to handle a common FileNotFoundException (which could be caused by an invalid user selection) but instruct Visual Studio to pause execution if an unexpected DivideByZero exception occurs.

To set this up, add a check mark in the Thrown column next to the entry for the System.DivideByZero exception. This way, you’ll be alerted as soon as the problem occurs. If you don’t add a check mark to the Thrown column, your code will continue, run any exception handlers it has defined, and try to deal with the problem. You’ll be notified only if an error occurs and no suitable exception handler is available.

Sunday, January 13, 2013

Using Math Class in C#.NET

In the past, every language has had its own set of keywords for common math operations such as rounding and trigonometry. In .NET languages, many of these keywords remain. However, you can also use a centralized Math class that’s part of the .NET Framework. This has the pleasant side effect of ensuring that the code you use to perform mathematical operations can easily be translated into equivalent statements in any .NET language with minimal fuss. To use the math operations, you invoke the methods of the System.Math class. These methods are static, which means they are always available and ready to use. 

The following code snippet shows some sample calculations that you can perform with the Math class:

double myValue;
myValue = Math.Sqrt(81); // myValue = 9.0
myValue = Math.Round(42.889, 2); // myValue = 42.89
myValue = Math.Abs(-10); // myValue = 10.0
myValue = Math.Log(24.212); // myValue = 3.18.. (and so on)
myValue = Math.PI; // myValue = 3.14.. (and so on)

The features of the Math class are too numerous to list here in their entirety. The preceding examples show some common numeric operations. For more information about the trigonometric and logarithmic functions that are available, refer to the Visual Studio Help reference for the Math class.