Naveen's Weblog

Bridge to future

Data Triggers and Usage in XAML

Posted by codingsense on November 25, 2009

Hi,

DataTrigger represents a trigger that applies property values or performs actions when the bound data meets a specified condition.

In this sample we will explore how this property can be utilized on how we need it to behave. In this sample I will concentrate on Style Triggers and apply them on the datagrid, in similar fashion it can be applied to any of the container control.

Till now I have been using Data Triggers in many of the places in my project. Combining all the solutions I have made a sample in which i will be describing all the types of usages of Data Triggers.

Let us imagine a collection of Fathers which hold FirstName of fathers. Each father has a kids collection where all his kids names are stored.
The collection are displayed in a datagrid and the rows are displayed using a Listview and a gridview.

<my:DataGrid AutoGenerateColumns="False" Margin="28,39,33,21" Name="dataGrid1">············
<my:DataGrid.RowDetailsTemplate>················
<DataTemplate>····················
<ListView Name="Kids" ItemsSource="{Binding Kids}">························
<ListView.View>····························
<GridView>································
<GridViewColumn  Header="Kids" DisplayMemberBinding="{Binding Name}"/>····························
</GridView>························
</ListView.View>····················
</ListView>················
</DataTemplate>············
</my:DataGrid.RowDetailsTemplate>············
<my:DataGrid.Columns>················
<my:DataGridTextColumn Header="Father Name" Binding="{Binding FirstName}"/>············
</my:DataGrid.Columns>········
</my:DataGrid>

Now lets create some scenarios in our project in the format the details are to be displayed
Scenario1: Make the families background red where there are no kids
Scenario 2: Hide the families where the name of the father is less than 8 chars
Scenario 3: Make the font bold where the fathers name is greater than 8 chars and there are 2 kids

Download Source Code – 423Kb

Make the families background red where there are no kids
Binding is very flexible in WPF you can easily bind to any of the properties available in the class. Like in this scenario we need to check if the kids count in the family is 0. For this we need to declare a style and bind our RowStyle of the grid to the defined style. Lets work on it.
Lets declare a style and name it as CheckKids and check for the kids.count condition for 0.

········
<Style x:Key="CheckKids" TargetType="{x:Type my:DataGridRow}">············
<Style.Triggers>················
<DataTrigger Binding="{Binding Kids.Count}" Value="0">····················
<Setter Property="Background" Value="Red"/>················
</DataTrigger>············
</Style.Triggers>········
</Style>

In the collection Mr.Ramiayaa has no kids so background of his row is made red.

Hide the families where the name of the father is less than 8 chars
Now comes the challange how will you check fatherName < 8 in XAML. Pretty tricky right. Here is a simple method to be followed. What if we have another property in our class which returns true or false by checking the fathername.length. It will help us to acheive our goal.

Lets Declare a property in Father class and name it as IsLengthLessThanEight, which will return if the father name is less than 8 char or not. It will look like

public bool IsLengthLessThanEight
{
get { return (FirstName.Length < 8); }
}

By this we can be very sure that we can write our own properties and bind it to make anything possible.
Now lets declare the style and name it FatherNameLessEightChar and bind it to our declared property IsLengthLessThanEight
and check the desired condition.

········
<Style x:Key="FatherNameLessEightChar" TargetType="{x:Type my:DataGridRow}">············
<Style.Triggers>················
<DataTrigger Binding="{Binding IsLengthLessThanEight}" Value="True">····················
<Setter Property="Visibility" Value="Hidden"/>················
</DataTrigger>············
</Style.Triggers>········
</Style>

In the collection we have only one father who has the name less than 8 that is Mr.Rocky that name is to be hidden.


Make the font bold where the fathers name is greater than 8 chars and there are 2 kids
Here comes the next challange how will we check more than one condition in XAML. Is it possible or should we declare another property and check 2 conditions in our class. For this we have MultiDataTrigger which will help us to check multiple conditions in XAML and set property accordingly. Cool.
Lets declare a style and name it CheckNameAndKidsCount and use the MultiDataTrigger.

<Style x:Key="CheckNameAndKidsCount" TargetType="{x:Type my:DataGridRow}">············
<Style.Triggers>················
<MultiDataTrigger>····················
<MultiDataTrigger.Conditions>························
<Condition Binding="{Binding IsLengthLessThanEight}" Value="False"/>························
<Condition Binding="{Binding Kids.Count}" Value="2"/>····················
</MultiDataTrigger.Conditions>····················
<Setter Property="FontWeight" Value="Bold"/>················
</MultiDataTrigger>············
</Style.Triggers>········
</Style>


Here we check both the conditions i.e First we check if father name is greater than 8 char with the help of the IsLengthLessThanEight that we have defined and next condition we check if the kids count is 2 or not. If both the conditions are satisfied then the font of the family is made bold.
In our collection we have Mr.Balasubramanyam whose name is greater than 8 char and has 2 childrens so his row should be made bold.

Wow all the scenarios have completed and we have got the desired output for all of them. Thanks to DataTrigger for simplifying the life. In this similar fashion we can declare style trigger and data trigger to make various styles depending on the data that is bound.

References :
http://msdn.microsoft.com/en-us/library/system.windows.datatrigger.aspx

Cheers :)
Naveen Prabhu

Posted in WPF | Tagged: , , | Leave a Comment »

Refresh UI elements on collection changed using ObservableCollection in WPF

Posted by codingsense on November 16, 2009

Hi,

In windows application when we would bind a list with any UI control, on changing of the list we should have refreshed the UI element or reload the list into the UI element. Imagine how tiresome it was if the list was referenced in many UI elements.
In WPF if we are implementing the same structure then we can use INotifyPropertyChanged or INotifyCollectionChanged to minimize our work.
If we are working on a list then we can inherit the list from ObservableCollection which in turn implements the 2 interface mentioned above. By using ObservableCollection we can notify the controls that the list to which they are bound has been changed and ask them to refresh their selves. This will minimize the work to maximum extent and the same time can be utilized for better activities.

In this post let me demonstrate you on how ObservableCollection can be implemented and how the changes to list can automatically refresh the UI element.

Download Source Code (11 KB)

Let me brief on the key things
Bind Textbox to a property of another UI element (Listbox) that returns Object in SelectedItem:
The text box is bound to ListBox.SelectedItem but the selected item will return a object of type PersonName. That is to be split into FirstName and LastName and shown in txtFirstName and txtLastName respectively. Here you have a good option while binding the textbox and the engine will take care of the splitting you can just bind as follows
For txtFirstName I have used binding as

Text="{Binding Path=SelectedItem.FirstName, ElementName=MyListBox, Mode=TwoWay, UpdateSourceTrigger=Explicit}"

As you can see i have specified SelectedItem.FirstName and at runtime the selectedItem will change to the object that is focused. Similarly we can bind to txtLastName.


UpdateSourceTrigger:

In UpdateSourceTrigger you have 3 options PropertyChanged, LostFocus, Explicity. I have used Explicity to handle our own customizations before updating the actual source and the customization can be handled in the save event.

NameList nameList = MyGrid.GetValue(Grid.DataContextProperty) as NameList;
PersonName currentPersonName = MyListBox.GetValue(ListBox.SelectedItemProperty) as PersonName;
PersonName NewPersonName = new PersonName(txtFirstName.Text, txtLastName.Text );
int IndexOfOriginal = nameList.IndexOf(currentPersonName);
nameList[IndexOfOriginal] = NewPersonName;

By just changing the List the newer values are reflected in the UI elements those are bound to the list.
For any clarifcation please feel free to comment.

References: http://msdn.microsoft.com/en-us/library/ms668604.aspx

Happy Learning :)
Codingsense

Posted in WPF | Tagged: , | 1 Comment »

Customized animating listbox WPF

Posted by codingsense on November 1, 2009

Hi All,
I had seen some of the 3rd party controls and was wondering what these people do in attaining good graphics in those controls. After carefully studying i got some tricks from which you can acheive the same styles.

Just have a look at this one, by just modifying some property i make the listbox to display items like a rack of books in a shelf .

Items of list box like Books in a Rack

And when you hover the mouse over it, the book will open and show you the details. Isnt it great

Books opens up when mouse hovers on it

Download source code – 210 Kb

Steps taken to acheive the above effects,

  • Databind a listbox using the xml file given in the project
  • Right click on the listbox and navigate to Edit other template -> Edit layout of items -> Edit a copy -> Enter any name you want to define -> click ok
  • In object and timeline in interaction window ( if not found click window menu -> interaction) click virtualizationStackPanel -> In properties( if not found click window menu -> properties) make orientation to horizontal from vertical
  • Click the return button in objects and timeline to return to the main page.
  • Select the listBox right click it and navigate to Edit Other Templates -> Edit generatated items -> Edit a copy
  • In the opened screen go to objects and timeline window (interaction window)
  • Select the stack panel and go to its properties, change the background that you want to apply to each item in the list box
  • Go to Transform group in properties and in RenderTransform
  • Select the rotate tab. Give an angle of -50
  • Select the skew tab and enter X value as -50, you will see the transform in each listbox item
  • Now just we need to remove the space between the items and its pretty much easier just give ve value in right margin. Eg: Give -30 in the right margin. This will bring all the items closer.

Now only we have to implement is Animation.First we shall create a story board

  • Click + on in the object and timeline to create a new story board, enter OnMouseIn and click ok
  • Select the stack panel
  • In timeline set the current time to 0.5 sec and Record a keyframe to indicate the initial state of our item.
  • Next we will tell the timeline what should happen after 0.5 sec. Move the timeline pointer to 1 Sec
  • And open the properties of stack panel and set the following values, -10 to right margin, 0 to angle and 0 to x in skew.
  • Run the timeline and see what happens and do any modification if it can enhance the animation.
  • Stop the timeline recording.

Next we need to define another storyboard that will move the list item back to the original position

  • So click Add new story board, Give it a name OnMouseOut and click ok
  • Take the current timeline to 1sec and insert a keyframe to indicate the final position of our animation.
  • Move the current pointer to 0.5 sec and set the properties, -30 as right margin, -50 as angle and -50 as x in skew.
  • Now since our animation is ready we just need to bind an event to invoke the story board, for that follow the setps.
  • In triggers click the +Event and select the target element Ismouseover event and set the value true.
  • In actions when activating select OnMouseIn begin
  • In actions when deactivating select on MouseOut begin
  • Run the application

Happy Learning :)
Naveen Prabhu

 

Posted in WPF | Tagged: , , | Leave a Comment »

Hosting WCF and ASP.NET application under same virtual directory in IIS

Posted by codingsense on October 28, 2009

Hi,

I had created a WCF service and an ASP.NET application which would consume the service, I hosted both in separate virtual directories and it was working very fine. After some days and lots of changes I noticed that the dlls and other common files used in both WCF and ASP.net application, had to be replaced in both the virtual directories to synchronize them.

So I planned to see if it’s possible to host both the application under same virtual directory and got a solution of merging the web.Config files of both the application. Now I have to replace the necessary assemblies or files in only one virtual directory and it has made my job lot easier.

Following are the steps that were followed.
Note: At the end I removed the WCF virtual directory and made my ASP.Net virtual directory to host both the application.

  • Copy the required files (Except Config file) from WCF virtual directory and place them appropriately in the structure in ASP.net virtual directory. (Eg: .svc file in the main folder and other required dlls into the bin folder)
  • Now we have all files in appropriate locations, just we need to do is to merge the web.config files to contain both Service as well as client configuration.
  • Open the web.Config file that was in WCF virtual directory and copy the <services> tag and <behaviour> tag with all its contents.
  • WebConfig

  • Open the web.Config file of ASP.net application and paste the copied contents in the <system.serviceModel> tag.
  • Copy the new path of the service by brosing the .svc file from IIS manager (inetmgr.exe) Note: If it wont run successfully check for required setting for the service in web.Config.
  • In the web.Config in the ASP.net virtual directory and change the address of all the endpoints to point to the new location of service.
  • Run the main application.

After following the above procedure I successfully hosted both applications under same virtual directory.

If you have any problem while following the steps or any other problem related to WCF or IIS you can please share it with me.

Happy Learning :)
Naveen Prabhu

Posted in WCF | Tagged: , , | Leave a Comment »

N-Tier basic 3D WPF Application

Posted by codingsense on October 20, 2009


Hi All,

WPF (Windows Presentation Foundation) has given us a hand to move in 3D world. Great graphics and GUI can be attained using WPF. I have worked on several graphical projects in WPF, but was wondering whether the performance and ease will remain the same when building a big application, so was working on the same and until now i have found it very easy in deploying any kind of application. So i planned to expose my application to all of you so that you can use it any way, here is the project. This is just a basic sample and I am sure you will find more ways after exploring this application.

Contact Management

Version : 1.0.0.0
Date : 20/Oct/2009

Download Source Code and database – 344 Kb
Download Application and database – 341 Kb

Prerequisites:

  • .Net Framework 3 or above.
  • SQL server 2005 or above
  • better the system configuration better the graphics
  • To view source files you will need VS 2008 SP1 and for better understanding design, 3D and animations you will need Expression blend 2 or higher

In the Contact Management i have tried to explore many concepts in which we can acheive good graphical interfaces and flexible data binding.

Let me show you some of the snapshots of the application.

Login Screen

Login Screen with Pattern using Drawing brushes

Login Screen with Pattern using Drawing brushes

Main screen

Customized listbox to show data in horizontal view with good looking mouse hover to move scroll bar and 3D rotation.

Customized listbox to show data in horizontal view with good looking mouse hover to move scroll bar and 3D rotation.

Add New contact

Add new contact to your list

Add new contact to your list

Transparent About Screen with animating text

Transparent about screen with animating text

Transparent about screen with animating text

Here are some of the key features explored. In coming posts we will explore each one of the features and do’s and dont’s of them.

  1. Customizing a control
  2. Data binding from various datasources
  3. Animating a control with Event Trigger and Propery Trigger
  4. Creating 3D graphichs and brief on Viewport 3D
  5. Creating resources and using them in whole application
  6. Creating Themes or Skins and change whole interface depending on the selection
  7. IValueConverter – bringing data from many child table depending on the parent data selection.
  8. Path – change shapes of any control or window
  9. Transoform propery

If you find any of the above topics very interesting or want to know about it, then please post a comment with specific topic name. I will make sure you get it.

I have also plans to take this project further.You can expect the future versions of Contact Management to have the following

  1. Email a friend
  2. Capture image of a friend and display it in very unique way
  3. Exploring on customizing a control and much better 3D ways to display it
  4. Creating, Changing and moving 3D objects in runtime

If you are finding any other problem in WPF or in Expression Blend or even if you find anything needs to improve in the application then you can always feel free to post a comment.

Happy Learning :)
Naveen Prabhu

Posted in WPF | Tagged: , , | Leave a Comment »

An attempt to attach an auto-named database for file xxxx.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

Posted by codingsense on October 20, 2009


I got this error while opening a connection. So i googled for the solution and found that some changes are to be done in config file. But nothing happened after changing it as mentioned.

Then i noticed the error correctly and it was pointing correct MDF file but the path was wrong. Eventhough it was correctly mentioned in Config file.

Solution :
So i went to Properties folder -> Settings.Settings and saw that the connection string was not refreshed in it. Then i manually changed it to point to proper location of MDF file and all went right.

Thanks
Naveen Prabhu

Posted in Solutions | Tagged: | Leave a Comment »

Performance difference between For and Parallel.For

Posted by codingsense on October 17, 2009

Hi,
I was really happy when i heard of the concept of Parallel.For that is introduced in new version of .Net. I tried it in framework 4.0 in visual studio 2010.
Here is the sample that i ran to see how the performance will vary on my system ( Core 2 duo).

class Program
    {
        static void Main(string[] args)
        {
            long[] a = new long[1000000];

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            Parallel.For(0, 1000000, delegate(long i)
            {
                a[i] = i * i;
            });

            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);

            watch.Start();

            for (long I = 0; I < 1000000; I++)
            {
                a[I] = I * I;
            }

            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);
            Console.Read();
        }
    }

What i saw is always there is a differnce in value depending on the work load on each core. But to my surprise i found that in all the 10-15 cases that i ran, for loop took less time to execute than Parallel.For.
I think there might be some other things that needs to be done to make use of Parallel.For to make it more efficient than For or there might be some specific tasks where Parallel.For should be used.
Will try to find it out and get back to you soon.

Naveen Prabhu

Posted in C# | Tagged: | Leave a Comment »

IIS 6.0 proper Installation and hosting ASP.NET(2.0/3.0/3.5) projects

Posted by codingsense on October 15, 2009


For successful hosting of ASP.Net projects in IIS 6.0 we need to install required components and configure IIS properly. The following sections give the steps that need to be followed while Installation and hosting.

There are 3 steps that should be followed they are,

1. Installation of IIS on Windows server 2003
2. Registering Asp.net 2.0
3. Hosting Asp.Net projects
3.1 Create virtual Directory
3.2 Creating our own Application Pool
3.3 Change Setting of Virtual Directory
3.4 Set ASP.Net version for the project

1) Installation of IIS on Windows server 2003

Open add remove programs from control panel
Click Add/Remove windows component on the left bar
When all the components are listed double click on Application Server
Select Application Server Console, ASP.NET and Message Queuing
Double click on Internet Information Services (IIS)
Select All the check Boxes and click OK
Click Ok -> Next -> Starts installing the selected components -> Click Finish

2) Registering Asp.net 2.0

Open command Prompt (Click start menu -> Run -> enter cmd -> Press enter)
Navigate to folder C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
Enter aspnet_regiis -i
Press enter

3) Hosting Asp.Net projects
Open IIS Manger (Click start menu -> run -> inetmgr -> Press enter).

3.1) Create virtual Directory
Expand Local computer -> Web Sites
Right click on Default web site -> New -> virtual Directory
Give the name of the virtual directory that you need to create
Click Next
Select the folder where you have published ASP.NET project
Click Next
Select Read and Read Scripts (Such as ASP)
Click Finish

3.2) Creating our own Application Pool
This will be used if you have hosted projects that are built with framework of different versions
Right click on Application Pools -> New
Enter a name for your Application Pool
If you are running many framework of differn then for each one framework you have to create different Application pool

3.3) Change Setting of Virtual Directory
Right click on created Virtual directory -> Properties
Select Virtual Directory Tab
Check Directory browsing if you need to enable browsing your directory
In Application Settings group -> Click Create
Select Execute permissions -> Script Only
Select Application Pool -> Select the created Application Pool Select depending on your framework version

3.4) Set ASP.Net version
Click ASP.NET tab
In ASP.NET version select 2.0.50727

Note: You need to set ASP.NET version as 2.0.50727 for all the projects built in framework versions 2/3.0/3.5.

This will install all the components and setting that are required to run ASP.NET 2/3/3.5 projects on IIS 6.0.

If any other issues feel free to post a comment.

Happy Learning :)
Naveen Prabhu

Posted in IIS | Tagged: , | Leave a Comment »

Sending Email through Gmail using VB 6.0

Posted by codingsense on July 17, 2009

Hi,

Here is a sample code that is used to send emails from any SMPT server using CDO in Visual Basic 6.0.
Here first i have added a reference to the project by navigating to Project -> references and adding Microsoft CDO for windows 2000 Library.

Sub SendEmail()

Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
Set Flds = iConf.Fields

' send one copy with Google SMTP server (with autentication)
schema = "http://schemas.microsoft.com/cdo/configuration/"
Flds.Item(schema & "sendusing") = 2
Flds.Item(schema & "smtpserver") = "smtp.gmail.com"
Flds.Item(schema & "smtpserverport") = 465
Flds.Item(schema & "smtpauthenticate") = 1
Flds.Item(schema & "sendusername") =  Username@gmail.com
Flds.Item(schema & "sendpassword") = password
Flds.Item(schema & "smtpusessl") = 1
Flds.Update

With iMsg
.To = To
.From = username@gmail.com
.Subject = "Mail from gmail"
.HTMLBody = "Test message using CDO in vb6 from Gmail smtp"
Set .Configuration = iConf
.Send
End With

Set iMsg = Nothing
Set iConf = Nothing
Set Flds = Nothing

End Sub

If you need to send mail from .Net here is the procedure.

Thanks,
Naveen Prabhu

Posted in VB 6.0 | Tagged: | 7 Comments »

Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.

Posted by codingsense on June 25, 2009


Problem :
When we open any dot net exe we can find this error.

Solutions :

There are many possible solutions for the same error arising from different conditions. My problem was solved with the first solution, if still your problem exist check other possible conditions too.

Thanks,
Naveen Prabhu

Posted in Solutions | Tagged: | Leave a Comment »