2 Prize Winner @DotnetFunda

Hi Guys,

After talking so much about tech stuffs, its time to relax a bit. Few days back I have told you guys that a site called www.dotnetfunda.com has launched a new competition for us. You can have a look into that post here. While sharing with you all those articles, I found few of them are pretty cool and many of my readers appreciated them. As a matter of fact, I win few prizes. Here are the prizes that I won :


1. IPod Shuffle / Videocon 1455 Phone

2. Free License from DevExpress


3. Free License from SmartOutline.

4. One Year Subscription from LearnVisualStudio.net

5. One year license from 10Tec. 

The prizes are nominated for "2nd Prize of Best Article" and "Maximum number of Good Articles".

I am really happy to receive these awards. I am thankful to Dotnetfunda.com, Sheo Narayan, and all my readers who like my posts. I hope I could produce more of these articles for you guys in near future.  Let us list the articles that might produced these prizes.

Articles : 

  1. WPF Tutorial - A Beginning
  2. Change Notification For Objects and Collections
  3. Design Pattern Implementation using C# 
  4. WPF Tutorial - Layout-Panels-Containers & Layout Transformation 2 
  5. Pluggable Styles and Resources in WPF with Language Converter Tool 
  6. WPF Tutorial - TypeConverter & Markup Extension 4 
  7. C# 2010 - A look 
  8. Lazy Initializer : C# 4.0

I hope you have already read those articles, if not, I would like you to read them. Thank you all.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

C# 4.0 Features

C# is a language we work on regularly, it is a language that we love the most. It is always good to see updates to such a lovely language which is very common to most of us. C# 4.0 after its release, comes with certain features that I think would love to know about. In this article I have discussed these common facts on C# 4.0 updates which you might find interesting.

Introduction


C# as a language is getting richer day by day whilst we are introduced with newer releases of .NET framework. Recently pronounced .NET 4.0 comes with lots of new features on different aspect of programming world. Some relates to technology, while some directly changes the basic API of the language structure. C# as a language is not deprived from those changes, and hence it is time to go on and understand few of the basic changes that are made in the C# language.

In this article, I will introduce the basic changes to C# 4.0. To start lets jot down the topics which I will discuss in this article first.

  1. Named and Optional Parameters
  2. Dynamic Keyword
  3. Co-Variance and Contra-Variance
  4. Event Object Locking Changed

These are not the only feature that is introduced with .NET 4.0. There are lots of others too. But to start with it, in this article I have talked about these heads. We will talk about others later on. Lets get started.


Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Lazy Initializer to defer expensive Object creation

.NET 2010 comes with lots of new features. Some relates to Technology while other relates to language enhancements. The huge class library that is there with .NET framework is also enriched with new classes. In .NET 4.0 there is a new set of classes which introduces a new concept called Lazy initializes. In this article I am going to discuss how simply you can use Lazy initialize to defer the execution of a method or property for values to whenever it is required.

Introduction

It is true that we often use Lazy initializer in our code  by restricting the load of objects using Properties. Thus unless the property is called from the code, the object will not created. A sample of it is :

private List<string> lazystrings = null;
        public List<string> LazyStrings
        {
            get
            {
                if (this.lazystrings == null)
                    this.lazystrings = this.GetLazyStrings();
                return this.lazystrings;
            }
        }

        private List<string> GetLazyStrings()
        {
            List<string> lazystrings = new List<string>();
            for (int i = 0; i < 30; i++)
            {
                lazystrings.Add(string.Format("Item {0}", i));
            }
            return lazystrings;
        }

In this case we have wrapped the loading of a List inside a property and hence the object will be loaded only when the object calls the property.  This is very common scenario of our daily programming needs.
Microsoft introduces a new technique called LazyInitializer that enables to do this in the same way as we do with the code above, but Microsoft recommends to use Lazy instead as becausee it is ThreadSafe. In this article we will see how to implement Microsoft's Lazy initializers.


Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Article Selected @asp.net

Hi guys,

Hope everyone is doing well. In this post I must mention that recently one of my article is been published to ASP.NET, the official Microsoft ASP.NET site. I am very pleased and thankful to everybody who supported me, especially my friend Abhijit Jana, and also Sheo Narayan and all the members of DotNetFunda Team. I also much congratulate codeproject as well, from where I started writing.




The article deals with the new concept of ASP.NET 4.0 which enables you to manipulate ClientId, the various mode on how you can handle these situations and also the way to make predictable clientID rendering.

You can read the whole article from :
ASP.NET 4.0 : Manipulate ClientID using ClientIDMode

I hope you will like this article as well.

Visit my site regularly for more updates, and also feel free to write comment/feedback to the posts.

Thanks.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Type Converters and Markup Extensions

TypeConverters and MarkupExtension are two concepts that are very popular when you work with XAML. When you first started learning XAML, the first thing that you might have noticed is Markup Extensions. So it is very essential to learn the use of Both the concepts like Markup Extension and Type Converters.

In this article, I have discussed how you might use Markup Extension and Type Converters to handle varied situation and also to create a rich client applications.

You can read the full article from :
Type Converters and Markup Extensions

I hope you will like it.

Thanks for reading.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Validate your application using IDataErrorInfo

As we move ahead  with WPF, we find lots of flexibilities that WPF provides for UI development. One of such is to define ValidationRule to work with controls bound with Data elements. In this article, I will discuss how easily you can impose custom validation to your DataElements by doing the entire thing from within the class itself.

First let us create the DataElement for which I need to use Data validation. As we know Binding needs few things like INotifyPropertyChanged event to handle binding, it needs IDataErrorInfo to handle ValidatesOnDataErrors calls. So the first thing that you need to do is to create a class from IDataErrorInfo interface.

Implementation

public class Contact : IDataErrorInfo
    {
        private string _Name;
        private string _desig;

        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        public string Designation
        {
            get { return _desig; }
            set { _desig = value; }
        }

        #region IDataErrorInfo Members

        public string Error
        {
            get { return "Error occurred"; }
        }

        public string this[string columnName]
        {
            get 
            {
                return this.GetResult(columnName);
            }
        }

        private string GetResult(string columnName)
        {

            PropertyInfo info = this.GetType().GetProperty(columnName);
            if (info != null)
            {
                string value= info.GetValue(this, null) as string;
                if (string.IsNullOrEmpty(value))
                    return string.Format("{0} has to be set", info.Name);
                else if(value.Length &lt; 5)
                    return string.Format("{0}'s length has to be at least 5 characters !", info.Name);
            }
            return null;
        }
        #endregion
    }

In this class you can see I have implemented it from IDataErrorInfo which lets me to impose Validation on Text that binds these properties. To induce this bindings, you need to use :

<Window.Resources>
        <AppCode:Contact x:Key="dsContact"/>  
</Window.Resources>

<TextBox BorderBrush="Black" Margin="80,54.04,19,74.96" Height="22" 
                 Name="txtLastName" Grid.Row="1" VerticalAlignment="Top" Text="{Binding Source={StaticResource dsContact}, UpdateSourceTrigger='LostFocus', Path=LastName, ValidatesOnDataErrors=True}">


Thus the data is bound with the Properties. The ValidatesOnDataErrors will automatically invoke indexer for Errors and gets the message based on when Data is modified inside the control.

To show the error message you can create a style which highlights the errorinfo over the control. I have used the general style to do so.

<Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
                    <Setter Property="Control.Background" Value="Pink" />
                </Trigger>
            </Style.Triggers>
        </Style>
Thats it, you are done with it. I will discuss more about this later.
Thanks for reading.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Troubleshoot Grapics Rendering issues in WPF

WPF renders everything using either using Hardware or Software or partial to both. If your computer is capable of rendering graphics using Hardware acceleration it goes with it to produce superior graphics and also getting input for Graphics Storage. Producing graphics using hardware generally be faster and smoother as it can register the memory of graphics and hence the application memory remains unaltered. Using hardware rendering technique is always better for an application, but while sometimes you see some weird issue regarding the hardware acceleration. Lets discuss about the issue.

A few days back, I found my application cannot display few text in some computers. I have a Tablet which runs Windows XP professional, and when I run my application there, text which have Gradient in it, doesn't display at all. I was really surprised to see it, but I found that sometimes when the graphics drivers are not installed properly in the machine, the drivers cannot produce gradient graphics properly, and hence there will be an issue with Text Rendering.

To fix the issue there are few techniques that you can follow. The first and most likely troubleshoot might be to install latest drivers for your Graphics card. But this makes you to learn more about your existing graphics drivers and its capabilities. Sometimes it might require that your own graphics driver does not support the gradient rendering. Then this will not be possible for you to change your graphics driver to solve this issue.

So I thought a way to the users to disable the Hardware acceleration.
To Disable Hardware Acceleration just follow the steps :



1. Go to Windows Desktop, Right click on blank area and select properties.

2. A new popup will open(as in fig 1).
3. Select Settings - > Advanced button.

4. On the Advanced dialog, please choose TroubleShoot, and drag the scroller that says Hardware Acceleration to None.


And then when I run your application, I think your issue must fix.

If you are a doing application in .NET, please read on.

Now this is not a solution for my problem. I cannot tell all of my people to do this crap to each of those computer where it creates issues. Thus I tried to programmatic solution to handle these myself.

WPF 4.0 comes with a property called

RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;

But my application is built using WPF 3.5.

To disable hardware acceleration:
[HKEY_CURRENT_USER\Software\Microsoft\Avalon.Graphics]
"DisableHWAcceleration"=dword:00000001

To enable hardware acceleration:
[HKEY_CURRENT_USER\Software\Microsoft\Avalon.Graphics]
"DisableHWAcceleration"=dword:00000000


You can read more from here.

But this would also affect other applications which are using Graphics acceleration.
Knowledge base article like http://support.microsoft.com/kb/963021 comes very helpful when I find issues with these kind of scenarios.

Windows XP also has few problems with layered display. For that, we need
http://support.microsoft.com/kb/937106/en-us
which is said to improve performance of WPF applications. But with all these there is no surety to have my application running properly./ So finally I have fixed by running only my application in Software Mode using the following code :

if (SoftwareRenderingNeeded)
            {

                HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
                HwndTarget hwndTarget = hwndSource.CompositionTarget;
                
                // this is the new WPF API to force render mode.
                hwndTarget.RenderMode = RenderMode.SoftwareOnly;

              }

So I guess the problem is solved for now, until I find another problem in this regard.
Please respond if you have any better solution to this. I would love to see.

Thanks for reading my post.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Smooth Pixel Scrolling in WPF ListView / ListBox

WPF comes with lots of fun and advantages. We can change the look and behavior of a control very easily which would have been very cumbersome when we are in normal winforms applications. WPF has few flexibilities like Superior Binding capabilities, Animation, Transformation, Virtualizations etc. Each of these made the framework richer in all respect.

In WPF, ListBox and ListView scrolls based on the items. The Scrolling on those controls are not smooth as the ScrollBar doesnt animate the scroller as we do with other controls. Sometimes you will also see the scroller is produced with incorrect size. I mean to say, the same scroller when it is in the top, the size is different than when its in the bottom. This happens basically because of Virtualization implemented on those controls.

ListBox and ListView actually has VirtualizingStackPanel enabled by default. This means, WPF will not actually create all the items and hence determine the scrollbar, rather the size of the ScrollBar is calculated based on the average multiple of items in its display with the number of items actually there in the CollectionView.  Thus if you have items which are in display bigger than which are not in view, you will see the size of the ScrollBar increased abruptly whenever you scroll down a bit.


You can see in the above snap, the irregular sized items will make the scrollbar to behave strange.

The easiest fix to this issue is you set
ScrollViewer.CanContentScroll = false

This will make the scrollviewer to disable the scrolling and hence the ListBox scroller appear.
The main problem with this approach is that, if you Disable the ContentScroll property of the ScrollViewer, it means it will completely stop Virtualizing. And hence if you have a big dataItems, it will cause huge performance issue.

You can also create your own scroolViewer using IScrollInfo. You have to create your custom panel to implement your scroller. This will be best.
I am also thinking to build one panel which might use Virtualizing as well. I will give you the idea when I finish.

For time being you can use CanContentScroll = false.

Thank you for reading.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

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.

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
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Resource Generator Tool

In my latest work, I have to implement the capability to have support for more than one language. Microsoft has come up with few tricks for doing that, but I devise my own logic to implement the same. As languages are actually string data which I want to present on the WPF applications, we can easily introduce individual resource files for data related to a particular Language.

Now when the program loads, we can easily go on and add the one that I need to add for the current CultureInfo. I have introduced the same in an article :
Simplest Way to implement Multilingual Application

Later on in my article Pluggable Resource for WPF ResourceDictionary, I have introduced the way by which you could plug - in the Resources into external assemblies.

So to summarize, whenever I need to use a string, I will need to modify the string resource with an appropriate key in the resource file. We need to create new Resource files for each language and also need to map each key with appropriate data.
So instead of Text="My Custom text", I will write something like Text="{DynamicResource rKeyCustomText}" so that the rKeyCustomText will be replaced with the appropriate text during runtime of the project and thus we can maintain language based string resources. To do this, we need to create a schema like :

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:system="clr-namespace:System;assembly=mscorlib">
    <system:String x:Key="rKeyCustomText" >This is my custom Text</system:String>
</ResourceDictionary>

For french we need to recreate the same as :
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                    xmlns:system="clr-namespace:System;assembly=mscorlib">
  <system:String x:Key="rKeyCustomText">C'est mon texte personnalisé</system:String>
</ResourceDictionary>

So the problem is once we declare a resource key we need to instantly convert the string to all the resource files that we need to support for the application and write that. So the work seems to me very boring and laborious. So I thought to build a tool to help you in this regard. Lets talk about how you can use this tool to build your Resource files automatically.


Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

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 !!!