Threads and Timers are the most common things that you need for your application. Any work that needs to be done in background without intervening the work that is running in the foreground needed to be done using a Thread. We create Threads to delegate a long running process in background so that the UI remains unblocked. Timers on the other hand is a special module which runs after a certain interval of time in background. So you would think Timers will also create a new Thread in background and runs the module associated with it after a certain time. This is not always true.
In this post, I will compare most of the timers available with .NET right now, and later on discuss about DispatcherTimer in WPF.
Difference between Concurrency and Asynchrony?
Now if you look back when Microsoft introduced async CTP in PDC 2010, or my own article on Async, it is clearly stated that Asynchrony and Concurrency are two different concepts. Asynchrony means running a job without blocking the Thread where it is working at. Concurrency is actually a special kind of asynchrony where it is achieved by creating a new Thread. Hence you can say, all sorts of concurrency is asynchrony while all asynchrony is not concurrency. You can have asynchrony without concurrency and it is really worth doing that, as you all know it is not good to put every work in Separate thread. ThreadPools could somewhat help by allowing you to manage threads but still Threads are for long running background processes, so beware to use it only when you absolutely require it.
Going ahead with this thought, lets compare the existing Timers.There are a number of Timers available with .NET before. Many of us might not know what is the basic difference between them. Lets put a comparative analysis on them one by one.
Handy Tricks and Tips to do your .NET code Fast, Efficient and Simple. Some common questions that comes into mind. Please check if you could find them listed or not.
Showing posts with label WinForms. Show all posts
Showing posts with label WinForms. Show all posts
Monday, March 7, 2011
Sunday, February 13, 2011
Code Contracts in .NET 4.0 & its Internals
After I have introduced you the Internals of Exception handling, I have mentioned that I will cover some of the features that is coming as an improvement to it. Code Contract in .NET 4.0 is one among them. In this post, I will cover how you could use code contract in your application and also take the way through to its internals later on.
One can argue with me, that code contract is a part of unit testing and might be included as a part of.NET test projects, but according to me, it is not restricted only for testing frameworks, you could use it more likely for your own libraries so that you could have better code handling and also some way of separation between the validation logic for which the library is built in and how you would react with the outside world. Now let us discuss, how to use it in your program, and later on I will build an application to use it.
One can argue with me, that code contract is a part of unit testing and might be included as a part of.NET test projects, but according to me, it is not restricted only for testing frameworks, you could use it more likely for your own libraries so that you could have better code handling and also some way of separation between the validation logic for which the library is built in and how you would react with the outside world. Now let us discuss, how to use it in your program, and later on I will build an application to use it.
Sunday, February 6, 2011
Internals of Anonymous Types
.NET comes with lots of new features as it introduces new features. Many of them are quite useful while others might be very specific to an issue. One of the features that came up recently with the introduction of .NET 3.5 in C# is anonymous method. Anonymous means an object with no name. Before .Net 3.5 we had concept of anonymous delegates in C#. If you read about internals of delegate, you must already know how anonymous delegates are declared to CLR. In fact, there is no concept of anonymous in MSIL. Hence everything that you see as anonymous is actually a level of abstraction to us, and lets us to avoid the complexity to maintain unnecessary types to our program. In this post, I will discuss about anonymous type in terms of MSIL.
The Basics
Anonymous types are those types which are not declared before they are used. Say while you are doing your program, you want a temporary storage of your data, what you need to do, you need either declare a concrete class for the storage of the same, or you can use any collection like ArrayList, HashTable etc to store the key value collection. C# 3.5 and onwards allows you to dynamically create a type and use it directly in your program. You can use ‘var’ or implicit type declaration to ensure you could use the properties just like normal types.
In the above example I have created one anonymous type using var. The var will give you a chance to get intellesense in your code. You can see the variable holds an object of an anonymous type generated runtime. The power of var in code can also be tested. Just hover over the var keyword and you will see that the type is defined as anonymous.
The Basics
Anonymous types are those types which are not declared before they are used. Say while you are doing your program, you want a temporary storage of your data, what you need to do, you need either declare a concrete class for the storage of the same, or you can use any collection like ArrayList, HashTable etc to store the key value collection. C# 3.5 and onwards allows you to dynamically create a type and use it directly in your program. You can use ‘var’ or implicit type declaration to ensure you could use the properties just like normal types.
var myruntimeObject = new { FirstProperty = 10, SecondProperty = new DateTime(), ThirdProperty = "string type" }; Console.WriteLine("Type of myruntimeObject is {0}", myruntimeObject.GetType().Name); Console.WriteLine("Type of FirstProperty is {0}", myruntimeObject.FirstProperty.GetType().Name); Console.WriteLine("Type of SecondProperty is {0}", myruntimeObject.SecondProperty.GetType().Name); Console.WriteLine("Type of ThirdProperty is {0}", myruntimeObject.ThirdProperty.GetType().Name); Console.Read();
In the above example I have created one anonymous type using var. The var will give you a chance to get intellesense in your code. You can see the variable holds an object of an anonymous type generated runtime. The power of var in code can also be tested. Just hover over the var keyword and you will see that the type is defined as anonymous.
Saturday, February 5, 2011
Get Reflected use TypeDescriptor
Hi there. Reflection is one of the major library that runs over the CLR which lets you get information about a CLR type or an object during runtime. A large number of application which is built today is taking advantage of Reflection to make their 3rd party codes plugin to their application dynamically. The Reflection lets you explain objects and its behavior dynamically and without any static binding available to any of those objects.
But if you just need to get information about the objects at runtime, Reflection APIs needs a hands experience and a lot of heck to do a job. A number of classes that is built over the Reflection APIs can be used to make your life easier while you code. One of the few libraries that are available with you that I must address is the classes within ComponentModel namespace. In this post I will give you a sample demonstration of how you could use Descriptor types to get information about Properties, Attributes, Events etc without invoking a single line of Reflection calls. I hope you could use the code later while building your library.
But if you just need to get information about the objects at runtime, Reflection APIs needs a hands experience and a lot of heck to do a job. A number of classes that is built over the Reflection APIs can be used to make your life easier while you code. One of the few libraries that are available with you that I must address is the classes within ComponentModel namespace. In this post I will give you a sample demonstration of how you could use Descriptor types to get information about Properties, Attributes, Events etc without invoking a single line of Reflection calls. I hope you could use the code later while building your library.
Thursday, August 12, 2010
Garbage Collection Notifications in .NET 4.0
Memory management is primary for any application. From the very beginning, we have used destructors, or deleted the allocated memory whilst using the other programming languages like C or C++. C# on the other hand being a proprietor of .NET framework provides us a new feature so that the programmer does not have to bother about the memory deallocation and the framework does it automatically. The basic usage is :
These questions might come to any developer who has just came to .NET environment. As for me too, I was doing the application just blindly taking it account that this might be the basic usage of .NET applications, and there might be a hidden hand for me who works for me in background. Until after few days, I got an alternative to call the Garbage collection using
But according to the documentation, GC.Collect() is a request.It is not guaranteed that the Collection process will start after calling the method and the memory is reclaim So, there is still uncertainty whether actually the Garbage Collection will occur or not.
Why GC.Collect is discouraged ?
GC.Collect actually forces the Garbage collection to invoke its collection process out of its regular cycle. It potentially decreases the performance of the application which calls it. As GC.Collect runs in the thread on which it is called, it starts and quickly finishes the call. In such phase of GC collection, actually the memory is not been reclaimed, rather it just produces a thorough scan on objects that are out of scope. The memory ultimately freed whenever Full Garbage collection takes place.
For reference you can read Scotts blog entry.
Whats new in .NET 4.0 (or .NET 3.5 SP1)
Well, GC is changed a bit with the introduction of .NET 4.0, so that the programmer have better flexibility on how to use GC. One of such changes is the signature of GC.Collect()
- Always leave local variable.
- Set class variables, events etc to null.
These questions might come to any developer who has just came to .NET environment. As for me too, I was doing the application just blindly taking it account that this might be the basic usage of .NET applications, and there might be a hidden hand for me who works for me in background. Until after few days, I got an alternative to call the Garbage collection using
GC.Collect()
But according to the documentation, GC.Collect() is a request.It is not guaranteed that the Collection process will start after calling the method and the memory is reclaim So, there is still uncertainty whether actually the Garbage Collection will occur or not.
Why GC.Collect is discouraged ?
GC.Collect actually forces the Garbage collection to invoke its collection process out of its regular cycle. It potentially decreases the performance of the application which calls it. As GC.Collect runs in the thread on which it is called, it starts and quickly finishes the call. In such phase of GC collection, actually the memory is not been reclaimed, rather it just produces a thorough scan on objects that are out of scope. The memory ultimately freed whenever Full Garbage collection takes place.
For reference you can read Scotts blog entry.
Whats new in .NET 4.0 (or .NET 3.5 SP1)
Well, GC is changed a bit with the introduction of .NET 4.0, so that the programmer have better flexibility on how to use GC. One of such changes is the signature of GC.Collect()
Labels:
.NET 3.5,
.NET 4.0,
.NET Memory Management,
C#,
CodeProject,
Finalize,
LOH,
Memory Allocation,
WinForms
Sunday, August 8, 2010
Garbage Collection Algorithm with the use of WeakReference
We all know .NET objects deallocates memory using Garbage Collection. Garbage collection is a special process that hooks in to the object hierarchy randomly and collects all the objects that are not reachable to the application running. Let us make Garbage collection a bit clear before moving to the alternatives.
Garbage Collection Algorithm
In .NET, every object is allocated using Managed Heap. We call it managed as every object that is allocated within the .NET environment is in explicit observation of GC. When we start an application, it creates its own address space where the memory used by the application would be stored. The runtime maintains a pointer which points to the base object of the heap. Now as the objects are created, the runtime first checks whether the object can be created within the reserved space, if it can it creates the object and returns the pointer to the location, so that the application can maintain a Strong Reference to the object. I have specifically used the term Strong Reference for the object which is reachable from the application. Eventually the pointer shifts to the next base address space.
When GC strikes with the assumption that all objects are garbage, it first finds all the Strong References that are global to the application, known as Application Roots and go on object by object. As it moves from object to object, it creates a Graph of all the objects that it finds from the application Roots, such that every object in the Graph is unique. When this process is finished, the Graph will contain all the objects that are somehow reachable to the application. Now as the GC already identified the objects that are not garbage to the application, it goes on Compaction. It linearly traverses to all the objects and shifts the objects that are reachable to non reachable space which we call as Heap Compaction. As the pointers are moved during the Heap compaction, all the pointers are reevaluated again so that the application roots are pointing to the same reference again.
WeakReference as an Exception
On each GC cycle, a large number of objects are collected to release the memory pressure of the application. As I have already stated, that it finds all the objects that are somehow reachable to the Application Roots. The references that are not collected during the Garbage Collection are called StrongReference, as by the definition of StrongReference, the objects that are reachable to the GC are called StrongReference objects.
This creates a problem. GC is indeterminate. It randomly starts deallocating memory. So say if one have to work with thousand bytes of data at a time, and after it removes the references of the object it had to rely on the time when GC strikes again and removes the reference. You can use GC.Collect to request the GC to start collecting, but this is also a request.
Now say you have to use the large object once again, and you removed all the references to the object and need to create the object again. Here comes huge memory pressure. So in such situation you have :
Download Sample Application - 27 KB
Garbage Collection Algorithm
In .NET, every object is allocated using Managed Heap. We call it managed as every object that is allocated within the .NET environment is in explicit observation of GC. When we start an application, it creates its own address space where the memory used by the application would be stored. The runtime maintains a pointer which points to the base object of the heap. Now as the objects are created, the runtime first checks whether the object can be created within the reserved space, if it can it creates the object and returns the pointer to the location, so that the application can maintain a Strong Reference to the object. I have specifically used the term Strong Reference for the object which is reachable from the application. Eventually the pointer shifts to the next base address space.
When GC strikes with the assumption that all objects are garbage, it first finds all the Strong References that are global to the application, known as Application Roots and go on object by object. As it moves from object to object, it creates a Graph of all the objects that it finds from the application Roots, such that every object in the Graph is unique. When this process is finished, the Graph will contain all the objects that are somehow reachable to the application. Now as the GC already identified the objects that are not garbage to the application, it goes on Compaction. It linearly traverses to all the objects and shifts the objects that are reachable to non reachable space which we call as Heap Compaction. As the pointers are moved during the Heap compaction, all the pointers are reevaluated again so that the application roots are pointing to the same reference again.
WeakReference as an Exception
On each GC cycle, a large number of objects are collected to release the memory pressure of the application. As I have already stated, that it finds all the objects that are somehow reachable to the Application Roots. The references that are not collected during the Garbage Collection are called StrongReference, as by the definition of StrongReference, the objects that are reachable to the GC are called StrongReference objects.
This creates a problem. GC is indeterminate. It randomly starts deallocating memory. So say if one have to work with thousand bytes of data at a time, and after it removes the references of the object it had to rely on the time when GC strikes again and removes the reference. You can use GC.Collect to request the GC to start collecting, but this is also a request.
Now say you have to use the large object once again, and you removed all the references to the object and need to create the object again. Here comes huge memory pressure. So in such situation you have :
- Already removed all references of the object.
- Garbage collection didnt strike and removed the address allocated.
- You need the object again.
Download Sample Application - 27 KB
Labels:
.NET,
.NET 3.5,
.NET 4.0,
.NET Memory Management,
C#,
CodeProject,
dotnetfunda.com,
IDisposable,
Memory Allocation,
SOH,
WinForms
Monday, July 5, 2010
Dynamic Behaviour on Objects at Runtime With Custom ExpandoObject
.NET 4.0 comes with lots of new features. One of the interesting things that it comes with is the Dynamic Behaviour of an object. If you have already read my article on C# 4.0 you know the basics of how to work with dynamic keyword in your application. In this post I will introduce how you could use ExpandoObjects, a new way of writing your truly dynamic code and also take you deep into how you could create your own ExpandoObject.
Being C# a strongly typed language, you might wonder how you could make it dynamic. In C# everything that we define will have a strong signature. There are numerous languages available like Python, Ruby, and most notably Javascript which are not strongly typed and you can change the object anytime whenever you require. C# 3.5 or below doesn't support changing the type dynamically during runtime. But as a developer we generally miss this flexibility of the language. But seriously that shouldn't change the class of the language like what C# is. I mean, by adding up features like dynamic language we shouldn't be compromise with C# as a strongly typed language.
Microsoft introduced dynamic in C# with C# 4.0. But believe me, C# is not a truly a dynamic language now. Hopefully they will introduce it in .NET 5.0. Let us talk about dynamic keyword a bit for time being.
Difference Between Object and Dynamic
When I first came across with dynamic in C# 4.0, I have wonder why do we require this. We have object which can hold any objects into it as it is called as mother of all objects. Objects can hold anonymous types or even call properties or methods of an anonymous type easily, so what exactly do we require for dynamic. To demonstrate the situation let us take the example on how you can call properties or methods of an object for which you don't know the exact type.
Let I have a class Person which looks like :
Now let our method GetObject returns an object of Person class as object. So to call properties or Methods we would write like :
This is really what you expect to write. Does it looks complex to you? Yes, it is. Probably if you have more flexibility like Static Method, or multiple argument for a method, or even an indexer your code will look horrendous.
dynamic keyword helps you in this regard. Yes, you can simply call methods and properties in your code without writing the whole Reflection methods, and the compiler will do them for us. So doing the same thing with dynamic the code will look like :
So the code looks the simplest and same as to known types. Actually if you see through the reflector, you will see that the same code is created by the compiler for us. So dynamic keyword makes our code look simple for dynamic types and also make the code easy to understand.
So, are you thinking this is the end of this ? Nope... Its the beginning of capabilities of dynamic. Let us discuss the true feature of dynamic in detail.
ExpandoObject, A true Dynamic Object
ExpandoObject is a new class added to enhance the dynamic capabilities of C# 4.0. ExpandoObject lets you to add methods or members to an object dynamically during runtime. Let us discuss this in detail using an example :
Let us create our class Person dynamically in runtime using ExpandoObject. To do this, we just need to write:
So here you can see, the object ExpandoObject is extended in runtime to add properties and methods dynamically.Isn't it cool. Now the language is truly flexible and dynamic in true sense.
If you are wondering how it is possible, or the depth behind creating the ExpandoObject class, lets read further to create your own Dynamic object.
Create Object that Extend in RunTime(Custom ExpandoObject)
To understand how a statically typed language can extend properties and class in runtime, or how this could be made possible, you need to delve deep into the internal structure of ExpandoObject.
Actually ExpandoObject is a Collection of KeyValuePair where the Key represents the interface through which the objects are called for and the Value is the object which might be a string, an object or a method depending on what you pass. When we pass the methods, properties to an ExpandoObject it actually adds those as a KeyValuePair into its collection, and when the object is invoked it calls up the method or property dynamically.
Now to create your own Custom ExpandoObject you need to inherit your class from IDynamicMetaObjectProvider. This interface has a method called GetMetaObject, which you need to implement to create DynamicMetaObject from the Linq expression. On the first instant, it seemed to me as a trivia, but it is not. You actually need to parse the complex Linq Expression to create your Meta object. I must thank Microsoft for giving an implementation of IDynamicMetaObjectProvider as DynamicObject. So for simplicity, you can inherit your class from DynamicObject and do your job done.
Let us implement our class from DynamicObject :
Here we have overridden Methods
Now to remove a member you just need to use
So this is it. Now you can handle your ExpandoObject yourself.
Download Sample Application
For further Reference :
http://tomlev2.wordpress.com/2009/10/08/c-4-0-implementing-a-custom-dynamic-object/
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx
http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx
I hope you like this article. Please put your comment. Thanks for reading.
Being C# a strongly typed language, you might wonder how you could make it dynamic. In C# everything that we define will have a strong signature. There are numerous languages available like Python, Ruby, and most notably Javascript which are not strongly typed and you can change the object anytime whenever you require. C# 3.5 or below doesn't support changing the type dynamically during runtime. But as a developer we generally miss this flexibility of the language. But seriously that shouldn't change the class of the language like what C# is. I mean, by adding up features like dynamic language we shouldn't be compromise with C# as a strongly typed language.
Microsoft introduced dynamic in C# with C# 4.0. But believe me, C# is not a truly a dynamic language now. Hopefully they will introduce it in .NET 5.0. Let us talk about dynamic keyword a bit for time being.
Difference Between Object and Dynamic
When I first came across with dynamic in C# 4.0, I have wonder why do we require this. We have object which can hold any objects into it as it is called as mother of all objects. Objects can hold anonymous types or even call properties or methods of an anonymous type easily, so what exactly do we require for dynamic. To demonstrate the situation let us take the example on how you can call properties or methods of an object for which you don't know the exact type.
Let I have a class Person which looks like :
internal class Person { public string Name { get; set; } public int Age { get; set; } public double Weight { get; set; } public string GreetMe() { return string.Format("Hello {0}", this.Name); } }
Now let our method GetObject returns an object of Person class as object. So to call properties or Methods we would write like :
public void ResolveStatic(object obj) { PropertyInfo pinfo = obj.GetType().GetProperty("Name"); //To Get from a property Name object value = pinfo.GetValue(obj, null); string content = value as string; Console.WriteLine(content); // To Set to Property Name pinfo.SetValue(obj, "Abhijit", null); //Invoke a method MethodInfo minfo = obj.GetType().GetMethod("GreetMe"); string retMessage = minfo.Invoke(obj, null) as string; Console.WriteLine(retMessage); }
This is really what you expect to write. Does it looks complex to you? Yes, it is. Probably if you have more flexibility like Static Method, or multiple argument for a method, or even an indexer your code will look horrendous.
dynamic keyword helps you in this regard. Yes, you can simply call methods and properties in your code without writing the whole Reflection methods, and the compiler will do them for us. So doing the same thing with dynamic the code will look like :
public void ResolveDynamic(dynamic obj) { Console.WriteLine(obj.Name); obj.Name = "Abhijit"; Console.WriteLine(obj.GreetMe()); }
So the code looks the simplest and same as to known types. Actually if you see through the reflector, you will see that the same code is created by the compiler for us. So dynamic keyword makes our code look simple for dynamic types and also make the code easy to understand.
So, are you thinking this is the end of this ? Nope... Its the beginning of capabilities of dynamic. Let us discuss the true feature of dynamic in detail.
ExpandoObject, A true Dynamic Object
ExpandoObject is a new class added to enhance the dynamic capabilities of C# 4.0. ExpandoObject lets you to add methods or members to an object dynamically during runtime. Let us discuss this in detail using an example :
Let us create our class Person dynamically in runtime using ExpandoObject. To do this, we just need to write:
dynamic d = new ExpandoObject(); d.Name = "Abhishek Sur"; d.Age = 26; d.Weight = 62.5d; d.GreetMe = new Action(delegate() { Console.WriteLine("Hello {0}", d.Name); }); p.ResolveDynamic(d);
So here you can see, the object ExpandoObject is extended in runtime to add properties and methods dynamically.Isn't it cool. Now the language is truly flexible and dynamic in true sense.
If you are wondering how it is possible, or the depth behind creating the ExpandoObject class, lets read further to create your own Dynamic object.
Create Object that Extend in RunTime(Custom ExpandoObject)
To understand how a statically typed language can extend properties and class in runtime, or how this could be made possible, you need to delve deep into the internal structure of ExpandoObject.
Actually ExpandoObject is a Collection of KeyValuePair
Now to create your own Custom ExpandoObject you need to inherit your class from IDynamicMetaObjectProvider. This interface has a method called GetMetaObject, which you need to implement to create DynamicMetaObject from the Linq expression. On the first instant, it seemed to me as a trivia, but it is not. You actually need to parse the complex Linq Expression to create your Meta object. I must thank Microsoft for giving an implementation of IDynamicMetaObjectProvider as DynamicObject. So for simplicity, you can inherit your class from DynamicObject and do your job done.
Let us implement our class from DynamicObject :
public class CustomExpando : DynamicObject { public IDictionary<string, object> Dictionary { get; set; } public CustomExpando() { this.Dictionary = new Dictionary<string, object>(); } public int Count { get { return this.Dictionary.Keys.Count; } } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (this.Dictionary.ContainsKey(binder.Name)) { result = this.Dictionary[binder.Name]; return true; } return base.TryGetMember(binder, out result); //means result = null and return = false } public override bool TrySetMember(SetMemberBinder binder, object value) { if (!this.Dictionary.ContainsKey(binder.Name)) { this.Dictionary.Add(binder.Name, value); } else this.Dictionary[binder.Name] = value; return true; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (this.Dictionary.ContainsKey(binder.Name) && this.Dictionary[binder.Name] is Delegate) { Delegate del = this.Dictionary[binder.Name] as Delegate; result = del.DynamicInvoke(args); return true; } return base.TryInvokeMember(binder, args, out result); } public override bool TryDeleteMember(DeleteMemberBinder binder) { if (this.Dictionary.ContainsKey(binder.Name)) { this.Dictionary.Remove(binder.Name); return true; } return base.TryDeleteMember(binder); } public override IEnumerable<string> GetDynamicMemberNames() { foreach (string name in this.Dictionary.Keys) yield return name; } }
Here we have overridden Methods
- TryGetMember : Called when Get method of a Property is called. If returned true the value in result will be returned.
- TrySetMember : Called when Set method of a property is called. If returned true the value in result will be set to the member.
- TryInvokeMember : Called when a delegate/method is called. The result will be returned.
dynamic expandoObject = new CustomExpando(); expandoObject.Name = "Akash"; expandoObject.CallMe = new Func<string, string>(delegate(string name) { expandoObject.Name = name; return expandoObject.Name; }); Console.WriteLine(expandoObject.Name); Console.WriteLine(expandoObject.CallMe("Hello"));
Now to remove a member you just need to use
expandoObject.Dictionary.Remove("Name");
So this is it. Now you can handle your ExpandoObject yourself.
Download Sample Application
For further Reference :
http://tomlev2.wordpress.com/2009/10/08/c-4-0-implementing-a-custom-dynamic-object/
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx
http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx
I hope you like this article. Please put your comment. Thanks for reading.
Labels:
.NET,
.NET 4.0,
ASP.NET 4.0,
C#,
CodeProject,
WinForms,
WPF
Monday, June 7, 2010
Pluggable Resource for WPF ResourceDictionary using Reflection
Plugins are the external dlls or modules that runs on an application without having strong relationship with it. Means you can easily uninstall a plugin by just deleting the specified files related to the plugin without affecting the whole application. In .NET technology we have a concept of Assemblies. You can reference an assembly when you want the assembly to be totally dependent on the other one. These are called Dependent assemblies. Plugins do not have direct reference while it is being referenced directly from a specific folder, so that the necessary plugins could be added dynamically to the application. In this article I am going to discuss how we can create plugins to load Themes, styles, Languages, and Objects.
As we go ahead with WPF, there are lots of problems we face which are such basic but with lots of importance. In my last application with WPF, I found that it is very essential to build a solid foundation to Styles and Themes which we can use in our application. While we build our application, we create resources. Some of them we place in resource dictionary while others in the window itself. Thus when we finally release our code, we find that changing the theme is to be a huge task altogether. In this article I will discuss, the steps how you can easily manipulate styles by placing the ResourceDictionary objects into another library and use .NET Reflection to plugin the Resource directly into your application.
To read the Full Article please visit:
Pluggable Styles & Resources in WPF
I hope you will like this article too. Thank you for reading
Introduction
As we go ahead with WPF, there are lots of problems we face which are such basic but with lots of importance. In my last application with WPF, I found that it is very essential to build a solid foundation to Styles and Themes which we can use in our application. While we build our application, we create resources. Some of them we place in resource dictionary while others in the window itself. Thus when we finally release our code, we find that changing the theme is to be a huge task altogether. In this article I will discuss, the steps how you can easily manipulate styles by placing the ResourceDictionary objects into another library and use .NET Reflection to plugin the Resource directly into your application.
To read the Full Article please visit:
Pluggable Styles & Resources in WPF
I hope you will like this article too. Thank you for reading
Saturday, May 22, 2010
Creating Splash Screen (Without Code)
Creating splash screen is very important for every good windows application. We work so hard while creating a beautiful splash screen. WPF introduces a very simple and easy approach to create a splash screen with lightening speed. Lets see how you can create one.
Why you need Splash Screen (Cold Start & Warm Start)?
This is very important to know why you need splash screen. Basically when WPF window loads for the first time, which is basically called as Cold Start; the WPF framework needs to load pages required such as code, static data, registry etc. Those are not present in memory whenever the application framework loads after reboot. So, user will find at least 4 seconds are required to load the window for the first time. This is very annoying on the part of the user. User might double click on the window for more than once just after seeing the delay of load. This delay will not occur for the next time onwards when all the necessary framework elements are already loaded into memory, popularly known as Warm start.
So it is very essential to load a splash screen, so that user will see that the application has already started loading.
How to create Splash Screen ?
Splash screen should be created using Unmanaged Code. This is very important. We create splash screen to give the user an indication that the application has started loading. So if we do this using WPF code, there will be a delay in loading the splash screen as well, which is not what we needed.
Steps to create SPLASH SCREEN :
This is the easiest approach of creating a splash screen. The image will be loaded using GDI unmanaged code before the WPF framework modules are fully loaded. So you can see this only when the application is loading. Once the Application is successfully run, the Splash screen will automatically disposed.
Download the source code from here.
Thank you for reading.
Why you need Splash Screen (Cold Start & Warm Start)?
This is very important to know why you need splash screen. Basically when WPF window loads for the first time, which is basically called as Cold Start; the WPF framework needs to load pages required such as code, static data, registry etc. Those are not present in memory whenever the application framework loads after reboot. So, user will find at least 4 seconds are required to load the window for the first time. This is very annoying on the part of the user. User might double click on the window for more than once just after seeing the delay of load. This delay will not occur for the next time onwards when all the necessary framework elements are already loaded into memory, popularly known as Warm start.
So it is very essential to load a splash screen, so that user will see that the application has already started loading.
How to create Splash Screen ?
Splash screen should be created using Unmanaged Code. This is very important. We create splash screen to give the user an indication that the application has started loading. So if we do this using WPF code, there will be a delay in loading the splash screen as well, which is not what we needed.
Steps to create SPLASH SCREEN :
- Create your own WPF application.
- Create an image which you want to display when the application loads up.
You must remember, creating splash screen this way will make the splash screen static. That means you cannot interact with the splash screen in this way. I will discuss a better way to create splash screen later. - Add a the image in to your application.
- Select the Image and from properties window choose Build action as Splash Screen as shown in the figure.
- You are done. You can now run your application, and you will see the splash screen to appear before the application loads up.
This is the easiest approach of creating a splash screen. The image will be loaded using GDI unmanaged code before the WPF framework modules are fully loaded. So you can see this only when the application is loading. Once the Application is successfully run, the Splash screen will automatically disposed.
Download the source code from here.
Thank you for reading.
Wednesday, May 12, 2010
New WPF Learning Series
Hi Guys,
After writing so much about WPF, I have just began writing a very basic Beginners series of Articles that will help you out in learning WPF which is the future of Widnows programming as of now.
The Articles published as of now are listed below:
WPF Tutorial - A Beginning : 1
WPF Tutorial - Layout-Panels-Containers & Layout Transformation 2
WPF Tutorial : Fun with Border & Brush 3
WPF Tutorial - TypeConverter & Markup Extension 4
WPF Tutorial - Dependency Property 5
WPF Tutoriall - Concept Binding 6
WPF Tutorial - Styles, Triggers & Animation
I am hoping you will like this series. Keep posting your feedback.
Thank you.
After writing so much about WPF, I have just began writing a very basic Beginners series of Articles that will help you out in learning WPF which is the future of Widnows programming as of now.
The Articles published as of now are listed below:
WPF Tutorial - A Beginning : 1
WPF Tutorial - Layout-Panels-Containers & Layout Transformation 2
WPF Tutorial : Fun with Border & Brush 3
WPF Tutorial - TypeConverter & Markup Extension 4
WPF Tutorial - Dependency Property 5
WPF Tutoriall - Concept Binding 6
WPF Tutorial - Styles, Triggers & Animation
I am hoping you will like this series. Keep posting your feedback.
Thank you.
Labels:
.NET,
.NET 3.5,
C#,
dotnetfunda.com,
windowsclient.net,
WinForms,
WPF
Saturday, May 8, 2010
How to escape {} in XAML
Escape sequences are very important part for any programming language. XAML which is been widely used nowadays in form of Silverlight and WPF, has some literals that are of special meaning. While working with XAML, you often need those special characters to be treated as literals.
In case of XAML { --- } is treated as a markup extension. While parsing the XAML, the renderer finds { --- } and try to create an instance of an object just between the Curl braces. The object should be a markup extension. Thus if you want to use the braces like {Anything} as the content of a textbox, it will just strip the curl braces leaving only Anything.
This is where you need Markup extension.
This will produce the output as "this is my name" (with no braces around my. To solve this issue, WPF has escape sequence.
While WPF renders the output, it tries to find "{" (curl bracket) to declare the Markup extension. Now when the opening curl bracket is found, XAML checkes the very next character to see if this is an escape sequence or not. If the markup has "{}" (without anything inside curl braces), it will treat it as an escape sequence. Thus to escape the curl bracket you need to put "{}" just before putting the actual content. So the above textblock could be changed as :
and the output will be "this is {my} name".
In case of XAML { --- } is treated as a markup extension. While parsing the XAML, the renderer finds { --- } and try to create an instance of an object just between the Curl braces. The object should be a markup extension. Thus if you want to use the braces like {Anything} as the content of a textbox, it will just strip the curl braces leaving only Anything.
This is where you need Markup extension.
<textblock text="this is {my} name">
This will produce the output as "this is my name" (with no braces around my. To solve this issue, WPF has escape sequence.
While WPF renders the output, it tries to find "{" (curl bracket) to declare the Markup extension. Now when the opening curl bracket is found, XAML checkes the very next character to see if this is an escape sequence or not. If the markup has "{}" (without anything inside curl braces), it will treat it as an escape sequence. Thus to escape the curl bracket you need to put "{}" just before putting the actual content. So the above textblock could be changed as :
<textblock text="{}this is {my} name">
and the output will be "this is {my} name".
Monday, April 12, 2010
Screen Capture in WPF & WinForms Application
I was wondering how one can capture screenshot from an application. I saw many application was doing them. This thought made me interested to write an application that can take ScreenShot. In this article, I will demonstrate how one can take screenshot directly from the Desktop area using WinForms and WPF.
WinForms Application
In WinForms application, it is very easy to grab a screen snapshot. To do this you only need to create an object of Bitmap, on which you want to draw the image, get Graphics object from the Bitmap and then use CopyFromScreen method to actually draw the image into the Bitmap. To demonstrate let us consider this method :
The above code takes Start X, Start Y, width and height and saves the image into the disk. In this method, I created an object of Bitmap where I would be going to draw the image. There are large number of PixelFormat supported by the Bitmap object. You can choose anyone of them which suits you. As I am working on 32 Bit true color environment, I used Format32bppArgb.
After doing this, you need to actually draw into the Bitmap object. To do this, you need to get graphics object from the image. I used Graphics.FromImage(image) to grab the graphics object from the image, so that the graphics could draw into the Bitmap object.
Finally I called g.CopyFromScreen which actually captures the screen snapshot, just like what Screenshot does and writes on the Bitmap. The argument that I have passed determines the dimension of the image. The x, y, width and height determines where from the screen the snapshot should start and its width and height upto which it must go. At last, I used image.Save to save the image in Png format in the disk.
You should note, if you want transparency in your image, you should use PNG, as it supports transparency.
A little Depth
If you want to know what exactly happens in background, let us use DllImport to demonstrate the concept. Actually Screen capture is made using a API call to BitBlt. This method can be called with appropriate dimension just as the managed method CopyFromScreen, and get the image.
To implement using Native code :
The NativeMethod BitBlt actually the most useful method in this context. To grab the image using this you can use :
In this function, I am doing the same thing that I did for the earlier. The difference is that, here I ma using NativeMethod to invoke the BitBlt directly rather than using the Managed code CopyFromScreen method.
If you want to capture the whole working area, you can use
Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
Screen.PrimaryScreen.Bounds.Width, and
Screen.PrimaryScreen.Bounds.Height
as its arguments.
Sample Application
In this sample application, you will find a WPF application that allows you to capture a part of the screen. Lets look how it works :
1. Run the application, you will be provided with a screen where you can drag mouse to take screenshot.
2. After you drag the mouse and Release the mouse, you will see a dialog box to save the image.
3. Finally after you save, you will see the snapshot in png format.
Thus it is very easy to work with Screen capture.
I hope you will like this application.
Download the Sample Application - ScreenShotSample.Zip(50KB)
WinForms Application
In WinForms application, it is very easy to grab a screen snapshot. To do this you only need to create an object of Bitmap, on which you want to draw the image, get Graphics object from the Bitmap and then use CopyFromScreen method to actually draw the image into the Bitmap. To demonstrate let us consider this method :
public void CaptureScreen(double x, double y, double width, double height) { int ix, iy, iw, ih; ix = Convert.ToInt32(x); iy = Convert.ToInt32(y); iw = Convert.ToInt32(width); ih = Convert.ToInt32(height); Bitmap image = new Bitmap(iw, ih, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(image); g.CopyFromScreen(ix, iy, ix, iy, new System.Drawing.Size(iw, ih), CopyPixelOperation.SourceCopy); SaveFileDialog dlg = new SaveFileDialog(); dlg.DefaultExt = "png"; dlg.Filter = "Png Files|*.png"; DialogResult res = dlg.ShowDialog(); if (res == System.Windows.Forms.DialogResult.OK) image.Save(dlg.FileName, ImageFormat.Png); }
The above code takes Start X, Start Y, width and height and saves the image into the disk. In this method, I created an object of Bitmap where I would be going to draw the image. There are large number of PixelFormat supported by the Bitmap object. You can choose anyone of them which suits you. As I am working on 32 Bit true color environment, I used Format32bppArgb.
After doing this, you need to actually draw into the Bitmap object. To do this, you need to get graphics object from the image. I used Graphics.FromImage(image) to grab the graphics object from the image, so that the graphics could draw into the Bitmap object.
Finally I called g.CopyFromScreen which actually captures the screen snapshot, just like what Screenshot does and writes on the Bitmap. The argument that I have passed determines the dimension of the image. The x, y, width and height determines where from the screen the snapshot should start and its width and height upto which it must go. At last, I used image.Save to save the image in Png format in the disk.
You should note, if you want transparency in your image, you should use PNG, as it supports transparency.
A little Depth
If you want to know what exactly happens in background, let us use DllImport to demonstrate the concept. Actually Screen capture is made using a API call to BitBlt. This method can be called with appropriate dimension just as the managed method CopyFromScreen, and get the image.
To implement using Native code :
internal class NativeMethods { [DllImport("user32.dll")] public extern static IntPtr GetDesktopWindow(); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr hwnd); [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] public static extern IntPtr GetForegroundWindow(); [DllImport("gdi32.dll")] public static extern UInt64 BitBlt(IntPtr hDestDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, System.Int32 dwRop); }
The NativeMethod BitBlt actually the most useful method in this context. To grab the image using this you can use :
public void SaveScreen(double x, double y, double width, double height) { int ix, iy, iw, ih; ix = Convert.ToInt32(x); iy = Convert.ToInt32(y); iw = Convert.ToInt32(width); ih = Convert.ToInt32(height); try { Bitmap myImage = new Bitmap(iw, ih); Graphics gr1 = Graphics.FromImage(myImage); IntPtr dc1 = gr1.GetHdc(); IntPtr dc2 = NativeMethods.GetWindowDC(NativeMethods.GetForegroundWindow()); NativeMethods.BitBlt(dc1, ix, iy, iw, ih, dc2, ix, iy, 13369376); gr1.ReleaseHdc(dc1); SaveFileDialog dlg = new SaveFileDialog(); dlg.DefaultExt = "png"; dlg.Filter = "Png Files|*.png"; DialogResult res = dlg.ShowDialog(); if (res == System.Windows.Forms.DialogResult.OK) myImage.Save(dlg.FileName, ImageFormat.Png); } catch { } }
In this function, I am doing the same thing that I did for the earlier. The difference is that, here I ma using NativeMethod to invoke the BitBlt directly rather than using the Managed code CopyFromScreen method.
If you want to capture the whole working area, you can use
Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
Screen.PrimaryScreen.Bounds.Width, and
Screen.PrimaryScreen.Bounds.Height
as its arguments.
Sample Application
In this sample application, you will find a WPF application that allows you to capture a part of the screen. Lets look how it works :
1. Run the application, you will be provided with a screen where you can drag mouse to take screenshot.
2. After you drag the mouse and Release the mouse, you will see a dialog box to save the image.
3. Finally after you save, you will see the snapshot in png format.
Thus it is very easy to work with Screen capture.
I hope you will like this application.
Download the Sample Application - ScreenShotSample.Zip(50KB)
Monday, August 3, 2009
UnCommon C# keywords - A Look
This is really a weird topic to start with. But still I would like to give you an insight on some of the uncommon things that you may not have noticed while doing programming. I have framed them in 2 sections.
1st one for Undocumented Keywords, which you will not find anywhere, not even in MSDN Documentation, which are not listed to intellesense menu in visual studio.
2nd one for Documented Keywords which are uncommon or just being introduced to C#. Documented keywords which are uncommon can be found over MSDN.I have also made a sample application where I have given some demonstration of each of the topics mentioned here in this article. If you want to test these, please download the sample application from here :
1st one for Undocumented Keywords, which you will not find anywhere, not even in MSDN Documentation, which are not listed to intellesense menu in visual studio.
2nd one for Documented Keywords which are uncommon or just being introduced to C#. Documented keywords which are uncommon can be found over MSDN.I have also made a sample application where I have given some demonstration of each of the topics mentioned here in this article. If you want to test these, please download the sample application from here :
Subscribe to:
Posts (Atom)
Author's new book
Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!
Grab it now !!!