Routed Event in WPF – Introduction

Till date we were acquainted with normal event which are basics of Win Form Applications.WPF introduces a new concept called as Routed Event .So here we will have a brief intro for this new feature and comparison between CLR Events and Routed Events.We will not start with definition , instead we will go back to old methods of CLR event and try to achieve something funny but logically meaningful.

Track Mouse Challenge (My niece 6 yrs old was tester , Still i failed  )

So a very simple logic , Whenever the mouse moves with in the panel the Status Label should display as “With in Panel” or else “Outside Panel”.So what we need to do is ,track it with Mouse Move and Mouse Leave events .The logic and code follows as bellow.

SNAGHTML1cffb48

Code Snippet
  1. private void pnlContainer_MouseMove(object sender, MouseEventArgs e)
  2. {
  3. pnlContainer.BackColor = Color.Red;
  4. lblMouseLocation.Text= “With in Panel”;
  5. }
  6. private void pnlContainer_MouseLeave(object sender, EventArgs e)
  7. {
  8. pnlContainer.BackColor = Color.Cyan;
  9. lblMouseLocation.Text = “Ouside Panel”;
  10. }

Very Simple .Lets Run.But the results are not as of requirement .So

My Niece’s Bug Report

When Ever the Mouse moves over the Black Board (Image Control) , status (Label Control) shows Outside Panel “ and that too logged on High Priority mode :).image Logically it should not happen .To patch it up in the end i attached event handler to the Image control .But suppose the panel contains more than one image or controls then how pathetic it will be to attach event to all .

Year 2010 , I tried to implement same logic with WPF and it surprised me.

Track Mouse Challenge  , in WPF

Now with WPF i emulate the same logic as in my previous WinForm application and it worked .
image and the code followed exactly same as above.

Code Snippet
  1. private void pnlContainer_MouseMove(object sender, MouseEventArgs e)
  2. {
  3. pnlContainer.Background = Brushes.Red;
  4. lblMouseLocation.Content = “With in Panel”;
  5. }
  6. private void pnlContainer_MouseLeave(object sender, MouseEventArgs e)
  7. {
  8. pnlContainer.Background = Brushes.Cyan;
  9. lblMouseLocation.Content  = “With in Panel”;
  10. }

e

Download the compiled programs and Check it.

Track Mouse Program (Simple WithOut WPF) Download
Track Mouse Program (Simple in WPF) Download

This is exactly where WPF introduces you to Routed Event.

What Is Routed Events

Routed events are the events that travel through the parent/ Child container of a control with raising  their events .The movement logic known as Routing Strategy (We will Digg into it in my next posts).

So events can also be captured at parent or child container instead of the particular control which invokes it.

Scenario Of Use

I know you will not agree with the scenario as mentioned above .

So some practical usage ,Consider a case of a normal calculator which contains 10 Numeric Button and Logical Operations .It is normal to write behind each control event , but what about code readability and scattered logic.Why should not we write a common logic part behind the parent container.

Another simple usage is YEs,No,Cancel button used in all our form.image I can handle events of buttons in the container Boarder.

Technical Difference From CLR Events

WPF UI is a composite architecture based  , means a control can be consists of several other controls or resource .Lets have a look at the document outline of the TrackMouse application.The Border (Resembles to Panel in Winform) contains the image control element. image The events are also followed as of the VisualTree above .The events of Image Element can be handled at its parent element Border.In Mouse Track program , Mouse Move of Image is a Routed event which invokes the parent Border Mouse move event also.Try to debug the code .

image I know the Technical details are not sufficient and the scope of the particular post doesn’t allow it .In my next posts i will cover the Routing Events and Routing Strategy in depth.

Code for this Article -Routed Event Intro Download

That’s it for now , i hope you liked my niece’s intelligence :).

, , , , ,

1 Comment

Event Handling in WPF

Events in WPF works same as in Win Form application except some new concept such as  Routed Event  ( I will blog it in next post).So directly we can jump to the code to add simple events to application as well as Window(Forms in WPF are called as Window ,for XBAP it called as Page).

There are 2 ways of adding events

  1. Declarative Way ( XAML Approach )
  2. Code Way (Conventional as in Win form / Code Approach)

So consider  the scenario bellow and the way to do it in both ways

Scenario 1 –: On Start of our Application we will show the application details.

Through XAML

As we should on load of application the event must be declared in the app.XAML or app.xaml.cs.Write the the event name we want to invoke , the intellisense will prompt as follows

www.manaspatnaik.com/blog Once you click image , it will add a handler to the app.xaml.cs .And there we will have the application information.

Basics What is  Event Handler ?
Code Snippet
  1. /// Interaction logic for App.xaml
  2. /// </summary>
  3. public partial class App : Application
  4. {
  5. private void Application_Startup(object sender, StartupEventArgs e)
  6. {
  7. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
  8. ,“My First WPF Application”);
  9. }
  10. }

Through CODE –:

As the OnStartup is application related event we will override in the app.xaml.cs.

image

Code Snippet
  1. protected override void OnStartup(StartupEventArgs e)
  2. {
  3. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
  4. , “My First WPF Application”);
  5. }

Scenario 2 –: On Button Click display application information (Attaching a event to a method)

Through XAML –:

First we will create a EventHandaler in the the window , as bellow .

Code Snippet
  1. public partial class MyFirstWindow : Window
  2. {
  3. public MyFirstWindow()
  4. {
  5. InitializeComponent();
  6. }
  7. private void ShowApplicationInfo(object sender,RoutedEventArgs e)
  8. {
  9. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
  10. ,“My First WPF Application”);
  11. }
  12. }

Now we will attach the event to the button click in through xaml .

image So the final Xaml code will look like this.

Code Snippet
  1. <Grid>
  2. <Label>My First WPF Application</Label>
  3. <Button Content=”Show About” Height=”50″ HorizontalAlignment=”Left” Margin=”71,78,0,0″
  4. Name=”btnShowAbout” VerticalAlignment=”Top” Width=”143″
  5. Click=”ShowApplicationInfo”
  6. />
  7. </Grid>

Through CODE–:

Code way is same as previous we need to attach the event to the handler on load.

image and the final code will be

Code Snippet
  1. private void ShowApplicationInfo(object sender,RoutedEventArgs e)
  2. {
  3. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
  4. ,“My First WPF Application”);
  5. }
  6. private void Window_Loaded(object sender, RoutedEventArgs e)
  7. {
  8. btnShowAbout.Click += new RoutedEventHandler(ShowApplicationInfo);
  9. }

That’s it .

,

Leave a comment

Getting Into WPF

Learning a new programming platform is never easy until unless somebody is really inspired.WPF (Windows Presentation Foundation ) is  quite convincing if you look at its prospective and the capability it gives to user.This new graphical subsystem from Microsoft relies on Direct X for rendering instead of GDI.So the advantage this  declarative programming model is Resolution Independent provides extensive integration with independent technology (Text to speech , 3d animation ,video etc),Hardware acceleration with Direct 3d and most useful complete customization of controls.

Wpf applications development  can be of two type

  • Windows Based Application
  • Browser Based Application (XBAP)
1285599500_package_edutainment What is Declarative Programming ?

This Blog post is about my experience with first WPF application , a simple application with basic understanding.

Create a WPF Project :

Open Visual Studio and Select WPF Application .Provide a Name “StartWithWpf” and click Ok .

Create a WPF Project

Have a look at the source folder , It contains a default MainWindows.xaml and App.xaml.So the XAML Markup drives WPF application with similar syntax of XML (Read More about XAML and Syntax) .A complied form of XAML is known as BAML.

r.2625741350 App.Xaml
  • App.xaml is a class(Singleton Pattern) which encapsulate the application specific functionality and resource handling such as
    • Application Lifetime
    • Application Windows,property
    • Resource Management
    • Command Line Parameter
    • Navigation
Digging Into APP.Xaml:

The App.Xaml (Application class )is the entry point for the application .We can write as code behind application class or in the mark-up.The declarative Mark-up is must for XBAP.

Code Snippet

  1. <Application
  2. xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
  3. xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
  4. x:Class=”StartWithWpf.App”
  5. StartupUri=”MainWindow.xaml”>
  6. </Application>

So the app.xaml need above lines to run a project.These are the Attributes of Application .

xmlns –:Defines the Namespace for the Application

xmlns : x-:Defines the additional namespace for the application

Basics of XAML Syntax

Above both attributes direct to the specification required to be referenced for xaml.You can find out some additional references as you add your some custom namespaces.

Custom Namespace in WPF

Adding a Form:

Now lets add a Form , here it is Windows (instead of Form as in WinApp).So adding a Window named “MyFirstWindow”.Add new WPF Window

Now the look at the Window , we have added.

Wpf Window

I will change the Title property and add a label to the Grid Layout.(Layouts are very important in WPF ).

Code Snippet
  1. <Window x:Class=”StartWithWpf.MyFirstWindow”
  2. xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
  3. xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
  4. Title=”Home” Height=”300″ Width=”300″
  5. >
  6. <Grid>
  7. <Label> My First WPF Application </Label>
  8. </Grid>
  9. </Window>

Now to Run the application i will go to App.xaml and Change the StartUpUri attribute to “MyFirstWindow.xaml”.Lets run it and you are ready with your first WPF application.A simple but fair start  :).

, ,

1 Comment

Bing With HTML 5

Bing in HTML5 could be Microsoft’s response to Google’s instant search, and we could likely see this being released by the first quarter of next year, right around the Internet Explorer 9 launch.

 

Watch it :

Bing in HTML5

Leave a comment

Start With SQL Compact Edition (SQL CE)

Hi Further on my previous article for introduction to SQLCE (Check it), i am going to walk you through to SQLCE with a very simple application.This sample will guide you from adding a local database to creating a connection and some CRUD operations.

Adding a SQLCE database to Project

  • Add a new Item to the project .

AddSQLCEDB_1

  • Select the DATA option and select  local Database option.Provide a database name and click OK

AddSQLCEDB

  • You can find the local Database as bellow.

AddSQLCEDB_3

  • You need to have a reference to the SqlServerce.dll .

AddSQLCEDB_Reference

  • To browse the Database , Right Click on Model.sdf and click Open.Then you will be able to get the table details.To add a new table Right click on Tables and click on Add table.In this case i have created 2 tables as shown in figure.

AddSQLCEDB_SDFExplorer

Creating a connection from C# project

The System.Data.SqlServerCe namespace is the .NET Compact Framework Data Provider for SQL Server CE.  WithSystem.Data.SqlServerCe, you can create and manage SQL Server Mobile databases on a smart device and also establish connections to SQL Server databases.

  1. public void Connect()
  2.  {
  3. 	 string FileName="Model.sdf";
  4. 	SqlCeConnection con=new SqlCeConnection(@"Data Source=|DataDirectory|\"+ filename 	+".sdf;Password=123"          );
  5. 	con.Open();
  6. }

Retrieving Data

The following code perform simple Data retrieval from the SDF file based on the sqlcecommand.

  1. private void RetriveData()
  2. {
  3. string FileName="Model.sdf";
  4. SqlCeConnection con = new SqlCeConnection(@"Data Source=|DataDirectory|\" + FileName + ".sdf;Password=123");
  5. con.Open();
  6. SqlCeCommand comm = new SqlCeCommand("Select * from EmployeeMaster", con );
  7. SqlCeDataAdapter sqlceda = new SqlCeDataAdapter(comm);
  8. DataSet dsData=new DataSet("EMPLOYEE");
  9. sqlceda.Fill(dsData);
  10. gvEmpMaster.DataSource = ds.Tables[0];
  11. }

Get the sample Application code

The sample application stimulate a typical windows based application using sql CE.This application consist of a wireframe database (model.sdf) which will be used to create other files and based on it the user can insert data and later retrieve it.

Sample Application Download

5 Comments

SQL Server CE (compact Edition)

Good news for small application developers , Microsoft released compact version of SQLSERVER (SQLCE 4.0 CTP1 ) for desktop ,web as well as for mobiles.This embedded database format is a huge relief from cumbersome and hectic installation of sql server .Although this was from long back still its reliability and features introduced in 4.0 CTP1 is awesome.I would like to introduce the some review and remarks on it in a very short manner.

Sql Server Compact Edition(SQLCE) is a embedded database for Mobile,Desktop and Asp.Net based projects.

For Whom :

  • If you are going to develop small/Mid level office application.
  • If you want hassle free installation of Database (Copy and Paste option)

What is the Latest Version :

Latest Version : 4.00 CTP1 Download

Last Release : 3.5 SP 2 Download

Some Facts -:

  • Supports Data up to 4 GB.
  • File based code free Database
  • Supports concurrent multiple connection from .
  • Runs in process of Application (Other MS sql Editions used to have separate services)
  • SQL CE databases reside in a single .sdf file.
  • The .sdf files / Database can be password protected as well as encrypted.
  • SQL CE databases are ACID-compliant. Like Microsoft SQL Server,
  • SQL CE supports transactions, referential integrity constraints, locking as well as multiple connections to the database store

Advantages

  • Very Small footprint(2 to 2.05 MB).
  • File based Database with enhanced security option.
  • All you need is Copying of binary to your installation path.
  • Easily Upgradeable to higher versions (MSSQL Express etc..)

Limitations

  • Doesn’t support Stored Procedures, also they don’t have plan for it. Go through the nice article from Steve.Lasker Read it.

Just have a look at the detailed comparison matrix with sqlExpress Edition.

Feature
SQL Server Compact Edition
SQL Server
Express Edition
Deployment/Installation Features
Installation size 1.7mb download size

1.8mb expanded on disk

53.8mb download size

~197mb expanded on disk

ClickOnce deployment clip_image002 clip_image002[1]
Privately installed, embedded, with the application clip_image002[2] clip_image004
Non-admin installation option clip_image002[3] clip_image004[1]
Runs on Windows Mobile platform clip_image002[4] clip_image004[2]
Installed centrally with an MSI clip_image002[5] clip_image002[6]
Runs in-process with application clip_image002[7] clip_image004[3]
64-bit support clip_image002[8] clip_image002[9] Windows on Windows (WOW)
Runs as a service clip_image004[4] In process with the application clip_image002[10] N + 1
Data file features
File format Single file Multiple files
Data file storage on a network share clip_image002[11] clip_image004[5]
Support for different file extensions clip_image002[12] clip_image004[6]
Database size support 4GB 4GB
XML storage clip_image002[13] stored as nText clip_image002[14]
Code free, document safe, file format clip_image002[15] clip_image004[7]
Programmability
Transact-SQL
Common Query Features
clip_image002[16] clip_image002[17]
Procedural T-SQL

Select Case, If, features

clip_image004[8] clip_image002[18]
Remote Data Access (RDA) clip_image002[19] clip_image004[9]
ADO.NET Sync Framework clip_image002[20] clip_image004[10] Planed support with a future version
Subscriber for merge replication clip_image002[21] clip_image002[22]
Simple transactions clip_image002[23] clip_image002[24]
Distributed transactions clip_image004[11] clip_image002[25]
Native XML, XQuery/QPath clip_image004[12] clip_image002[26]
Stored procedures, views, triggers clip_image004[13] clip_image002[27]
Role-based security clip_image004[14] clip_image002[28]
Number of concurrent connections 256 Unlimited

, , ,

Leave a comment

Hi World ..

Hi all , this is my first blog after a long persue from my friends .It is always good to start late instead of not doing it.Ok my self Manas as you can find from domain name , i  am working in MNC , India as Technology Analyst and loves dancing.

Before i took up blogging i asked my self so many time times  “Why should i blog” .

As i got the answers after a lot of  in fight  with my consensus i want to share with you. As a human and as a engineer you need to improve and you need to excel in what ever you do and this improvement can be achieved if you analyse the work you have done and the experience you learned. I would like to share one quote :

“If you re-read your work, you can avoid a great deal of repetition and can achieve  improvement in future endeavor ”

So thats it 🙂 now i am ready to share it with me as well as  all of you .

I am going to write about my work experience related to Technology , life , business and what ever i feel i need to share with all.Of course i need you feed back and one line comment that will help me to do better .

Keep Reading .

Leave a comment

Hello world!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

1 Comment

Design a site like this with WordPress.com
Get started