Tuesday, July 7, 2009

How to Setup a Websphere MQ with C# .NET: GUI to Put/Get to Local & Remote Queues

Introduction

This very basic article will show you how to write simple MQ programs in C#.NET as well as how to configure the background IBM Websphere Queue Manager.

Background

This example is more directed towards how to setup the Websphere MQ for communication to/from Local & Remote Queue Managers and how to create a C#.NET GUI. I've included a setup guide for the Queue Manager within the zipped source.

The Websphere DLL is also included within the source code.

Using the code

Create a Windows Application copying the code found in Form.cs. Create the form as shown in the screenshot. The only label not visible is one called lblConnect to hold the results of hitting the Connect button.

The MQTest.cs can be taken and used anywhere communication with a Queue Manager is required.


See full detail: http://www.codeproject.com/KB/cs/MQExample.aspx

Searching, Modifying, and Encoding Text

Searching, Modifying, and Encoding Text

Introduction

The purpose of this article is to help the developer to enhance the text building capabilities of a .NET Framework application via the System.Text namespace. Processing text is one of the most common programming tasks. User input is typically in text format, and it might need to be validated, sanitized, and reformatted. Also, as a developer, you might need to process text files generated from a legacy system to extract important data. These legacy systems often use nonstandard encoding techniques. Moreover, the majority of software development companies maintain large legacy code bases. Finally, a developer might need to output text files in specific formats to input data in a legacy system.

Forming Regular Expressions – The Basics

As I stated earlier, developers often need to process text. For example, you might to process text from a user to remove or replace special characters. A regular expression is a set of characters that can be compared to a string to determine whether the string meets specified format requirements. That is, regular expressions are simply arrangements of text that describe a pattern to match within some input text. Simple variants of regular expressions pop up everywhere. The MS_DOS command ‘dir *.cs’ employs a very simple pattern matching technique much like what regular expressions can do. The asterisk followed by the period and the two letters is a simple wildcard pattern. To use regular expressions for pattern matching, we will create a simple console application named TestRegExp that accepts two strings as input and determines whether the first string (a regular expression) matches the second string. Here is some basic code. The regular expression will not make sense at all, but it should by the end of the article:


See full detail: http://www.codeproject.com/KB/cs/Patterns.aspx

C# 4.0's New Features Explained

Introduction

The Beta for Visual Studio 2010 is upon us and included is the CTP of C# 4.0. While C# 4.0 does not represent a radical departure from the previous version, there are some key features that should be understood thoroughly in order to take advantage of their true potential.

Background

The white paper for C# 4.0's features does a good job of explaining the changes in the language. I thought, however, that some larger code samples and historical perspective would help people (especially new developers) in understanding why things have changed.

Feature Categories

Microsoft breaks the new features into the following four categories so I will maintain the pattern.

  • Named and Optional Parameters
  • Dynamic Support
  • Variance
  • COM Interop

Conventions

Some of the examples assume the following classes are defined:


See full detail: http://www.codeproject.com/KB/cs/CSharp4Features.aspx

CLR Stored Procedures and creating it step by step

Introduction:

We usually face problem in Stored Procedures and other database object when we need to implement some complicated logic within it. We found inefficient performance when we try to implement complex logic & business rules in database objects. In many cases we found C# or VB classes more powerful to implement such things. Microsoft has launched a new concept to resolve such issues with SQL server 2005 called "CLR Stored Procedure".

What is CLR Stored Procedure?

Now, let us understand CLR stored procedure. CLR as most of .Net programmer knows is Common Language Runtime and Stored Procedures are routine stored procedures of database. Thus, CLR Stored Procedures are combination of both. As we all know, Common Language Runtime is core .Net component. The Common Language Runtime is runtime execution environment which supplies managed code with various services like cross language integration, code access security, lifetime management of object, resources management, threading, debugging & type safety etc. So now, CLR Stored Procedures are .Net objects which run in the memory of database.

The very first usage of CLR Stored Procedures can be said accessing system resources. Accessing system resources could also be done using Extended Stored Procedures which are again database object like Stored Procedures, Functions etc. Extended Stored Procedures can do most of the things which a standard executable program can do. Then, why are CLR Stored Procedures? The very first advantage of CLR Stored Procedures is it is a managed object unlike Extended Stored Procedures, which are unmanaged objects. The common thing between them is both runs under database memory. In this way CLR Stored Procedures gives all the benefits of managed objects. Following screen explains memory allocation while execution of CLR Stored Procedure.

When should I use CLR Stored Procedure?

Extended stored procedures run in the same process space as the database engine, memory leaks, bugs etc., can affects the performance of database engine. CLR stored procedures resolves these issues as they are managed object and runs per specifications of Common Language Runtime. CLR Stored Procedures can replace a standard stored procedure that contains complex logic and business rules. CLR Stored Procedures takes benefit of .Net classes and thus makes easy to implement complex logic, calculation, intense string operations, complex iterations, data encryptions etc., that are difficult to obtain in standard stored procedures. Standard stored procedures are still best for data oriented tasks. CLR Stored Procedures not only includes stored procedures but also includes Functions, Triggers etc. CLR Stored Procedures are compiled one so gives better performance.

Benefits of CLR Stored Procedures:

  1. Gives better results while executing complex logic, intense string operation or string manipulations, cryptography, accessing system resources and file management etc.
  2. CLR Stored Procedures are managed codes so ensures type safety, memory management etc.
  3. Better code management and provides object oriented programming capability thus enables encapsulation, polymorphism & inheritance.
  4. Convenient for programmer as CLR Stored Procedures can be written in C#, VB or any other language that .Net Framework supports.
  5. CLR Stored Procedures can also be used with Oracle 10g Release 2 or later versions.

Drawbacks of CLR Stored Procedures:

  1. Not convenient in all contexts for e.g. it should not be used to execute simple queries. In that case standard stored procedures give better results.
  2. Deployment may be difficult in some scenarios.

Standard Stored Procedures vs. CLR Stored Procedures:

You are the best judge when to use regular Stored Procedures and when to use CLR Stored Procedures. CLR Stored Procedures can be used in following scenarios.
  1. When the program requires complex logic or business rules.
  2. When the flow is CPU intensive. CLR Stored Procedures gives better results as they are in complied form and managed one.
  3. The tasks which are not possible in TSQL, accessing system resources, cryptography, accessing web services etc.
  4. In option of Extended Stored Procedures. One should always consider CLR Stored Procedures before going for Extended Stored Procedures.
  5. An operation requires higher data safety.

Creating CLR Stored Procedure step by step:

Let us create one simple CLR Stored Procedure which fetches all the rows from one table of the database. I have listed all SQL statement used for creating database, creating table, inserting dummy records in the table etc., under "SQL statements used in the demo" section. Application development specification:
  • IDE: Visual Studio 2008
  • Framework: 3.5 with SP 1
  • Language: C# 3.0
  • Database MS SQL Server 2005 Express edition
Steps to create CLR Stored Procedure: 1) Open Microsoft Visual Studio >> Click on New Project >> Select Database Projects >> SQL Server Project.

2) You can choose reference of existing database connection or click on Add New Reference.

3) If you selects from existing references skit step 3 else add new database reference as shown in following image and click on Test Connection to test the connection.

4) On clicking on OK button, Visual Studio will ask you to enable SQL/CLR debugging on the selected connection. You can select "Yes" to enable debugging or "No" to disable the same.

5) Once the database reference and debugging option is selected, the project will be displayed in Solution Explorer. Select the project and right click on Solution Explorer >> Click on Add >> Stored Procedure.

6) Add new procedure from the installed templates as shown in following screen. Give proper name to it.

7) Once you select the template, it will create .cs file with the content shown in following image.

8 ) Add following code in the method already created. Pass "context connection=true" as connection string in the constructor while creating new SqlConnection. This CLR stored procedure is going to be the part of the database, so it will be the internal part of database so no need to connect database externally. So, no need to provide connection string that we usually provide in applications. Then Click on Build menu >> Click on Build Solution. Also click on Build menu >> Deploy solution. This will deploy the assembly to the database for which we have made connection initially.

9) Now, select the database >> Programmability. Right click on Stored Procedures >> Click on Refresh. The list of Stored Procedures should show one newly added stored procedure. Also right click on Assemblies >> click on Refresh. This should show newly added Assembly. Also, enable CLR Stored Procedure by following query.

sp_configure 'clr enabled', 1

Run following query to take effect or above query.

RECONFIGURE

Now, execute the stored procedure. It should give similar results shown in following screen.

SQL statements used in the demo:


See full detail: http://www.codeproject.com/KB/cs/CLR_Stored_Procedure.aspx

Document Preview Application

Introduction

Document Preview is an application that allows users to preview their files such as Pdf, Doc, Xls, Jpg, Mp3, Avi while browsing with an interface like Windows Explorer but without opening an extra application. It also allows users to move, copy, delete folders or files.

The idea to develop this software came up to my mind while trying to find a pdf document that contained specific information. My goal was to develop this application with techniques like Abstract Classes, Inheritance, Interfaces, Linq and provide community samples about usages of these techniques.

Background (optional)

Here are some controls that I used to provide Preview functionality.


See full detail: http://www.codeproject.com/KB/cs/DocumentPreviewApp.aspx

Build your own Windows Security Center

Introduction

Windows Security Center in Windows® XP was made and designed to monitor three different security essentials, Windows Firewall status, Windows Updates settings and antivirus product status. The Windows Security Center has succeeded in protecting and keeping the user updated about each security essential.


1.png
Figure A: The Windows Security Center in Windows® XP.

The Windows Security Center User Interface

Windows Security Center has a very simple and basic graphic user interface (GUI). As described below.

2.png
Figure B: The Windows Security Center user interface described.

The Windows Security Center user interface is very easy to understand. But at the same time Windows Security Center user interface still advanced. However, each message alerts and describes something.

3.gif If you're using the Windows Firewall or [3rd party firewall], have Automatic Updates turned on, and use an antivirus program all windows should show on with a green light.

4.gif You will see this if Automatic Updates or the Windows Firewall is turned off [or if you aren't using a 3rd party one].

5.gif You will see this if an antivirus program isn't found.

6.gif You will see this if you've told Windows Security Center to not monitor your Windows Firewall [or you’re 3rd party firewall] or antivirus settings.

How does Windows Security Center Work?

In order to build your own Windows Security Center, you should first understand how an already working security center works. The Windows Security Center in Windows® XP was the first security center Microsoft made. The Windows Security Center finds information about the three security essentials like this:

  • Windows Firewall Status: Windows Security Center finds the Windows Firewall settings through the Windows Firewall API. The file that has these is: hnetcfg.dll.

    However, we need the Class Identifier (CLSID) which also is required to obtain a reference to the Windows Firewall Manager class.

    CLSID = {304CE942-6E39-40D8-943A-B913C40C9CD4}

    Registry path: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Classes\CLSID\{304CE942-6E39-40D8-943A-B913C40C9CD4}
  • 3rd Party Firewall Status: The Windows Security Center finds 3rd party firewalls through the Windows Management Instrumentation (WMI), from the Security Center WMI root path.

    WMI root path: \\HOSTNAME\ROOT\SecurityCenter:FirewallProduct

  • Windows Updates Status: Windows Security Center finds the automatic update settings through the Windows Registry.

    Registry path: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\

    Key: AUOptions

  • Antivirus Status: Windows Security Center finds the antivirus product through the Windows Management Instrumentation (WMI), from the Security Center WMI root path.

    WMI root path: \\HOSTNAME\ROOT\SecurityCenter:AntiVirusProduct

  • The Windows Security Center, in fact, does not have these three security status essential functions inside its self. However, the real fact is that Windows Security Center keeps monitoring the three security essentials thanks to its Windows Security Center Service running in the background.

You can also look at the architecture illustration below, to gain better understanding.
WindowsSecurityCenter.png
Illustration: The way Windows Security Center in Windows® XP works. Windows Security Center checks and monitors all the three security essentials.
(I used some nice icons here to make a better illustration).

Build your Own Windows Security Center

Now, to the final: we are going to build our own Windows Security Center.
Starting off with the Windows Forms GUI, I added about 8 panel controls. I also added some labels, pictureboxes and three timers.

Add the Windows Firewall API

To control the Windows Firewall from your windows application you need to add some references.


See full detail: http://www.codeproject.com/KB/cs/xpsecuritycenter.aspx

Introducing WF4.0: Building Distributed Apps with WF 4.0 and WF 4.0 Services

Introduction

In 2006, Microsoft released .NET Framework 3.0, which basically consisted of extensions to .NET Framework 2.0. WCF was the biggest hit back then and gained the most attention. That even continued with the 3.5 release of the framework.

With .NET Framework 4.0, Microsoft made WF the major focus, and with the many enhancements they have in place, it is evident the importance that WF 4.0 will have for building .NET-based applications.

What is WF?

Well, answering this question is not the scope of this article. Understanding what WF is and when to use it is something you can get from various online resources – or even books. For example, one of the great early publications on WF 4.0 is David Chappell’s paper on MSDN; reading it will be more than enough to understand what is and when to use WF 4.0. You can find it here: http://msdn.microsoft.com/en-us/library/dd851337.aspx.

So what is this article about?

In summary, this article has two main objectives:

  1. Gives a first look on WF 4.0 (beta1 as of this writing).
  2. Shows how we can use WF 4.0 to build distributed applications via WF 4.0 Services.
  3. Using .NET 4.0 Data Services for performing data access.

Note: A nice post about the differences between WF 4.0 and WF 3.5 can be found here: http://bloggingabout.net/blogs/pascal/archive/2009/05/20/wf-4-0-what-is-different-from-3-x.aspx.

Application architecture

The application demonstrates a demo-worthy Car Rental system. The image below shows the design of the application.

1.JPG

The scenario is as follows: A car rental company has its information in a SQL Server database. They need to build an application which allows employees to check car prices and then book cars to clients based on the client input. For that, a WF 4.0 Service which contains the business logic is hosted over HTTP where clients can ask it to do two operations: CheckPrice and BookCar. The WF 4.0 Service – being a business process – is not allowed to access the database directly; instead, it communicates with an ADO.NET Data Service which performs database CRUD operations (more on that later). What client types does the system support? The answer is just about any client. In this example, we will see a .NET Windows client, and more interestingly, a WF 4.0 client.

Any similarities spotted…?

Examining the above architecture should definitely trigger in your development sense the concept of n-tier applications. In fact, the above design is nothing more than the traditional and beloved three tier design. Let’s do the matching:

  • Data Access Layer: ADO.NET Data Services is used instead of the traditional DAL class libraries with the famous SQLHelper class.
  • Business Layer: A WF 4.0 Service is used as the business layer instead of the BAL class libraries we used to write.
  • Presentation Layer: A WF 4.0 console client application is used instead of a .NET console application. Now, this is tricky; in this example, no user interface is required, so a console WF application was sufficient. However, in cases where a GUI is needed, a Windows (or web) client application is used easily…after all, the business logic is hosted in a WF Service, and can be consumed by any client just as if you were using an XML Web Service, for example.

So in a more traditional design, the architecture would be like something in the figure below:

2.JPG

So, the advent of the new technologies allowed for better designs. How the new WF-based design tops the old traditional one is something you will see as we go in this article…

Source xode

The source code can be downloaded from the link above. I will use the solution components as we go through the article. It would have been impossible to show a step by step approach on how I built the application, so as we go, I will refer to the various components of the solution and explain each and every one of those components.

Prerequisites

The sample is built on top of .NET 4.0 and VS 2010 Beta1 release. You can download them from here: http://www.microsoft.com/downloads/details.aspx?familyid=3296BB4F-D8BA-4CFD-AA95-A424C5913F6B&displaylang=en. You will also need SQL Server 2000/2005. Let’s roll…

Part 1: The database

As with any data-centric approach, the application design usually starts with the database and then goes up through layers. We will follow the concept here. Luckily, for our example, the database is as simple as a single table called Cars, shown below:

3.JPG

The CarId column holds the names of some famous manufacturers like Honda and Mercedes. The Day_UnitPrice column holds the daily renting amount fee, and finally, the Quantity column holds the available number of cars for renting.

In the attached files, you will find a file called CarStore.bak; restore that to your SQL Server.

Part 2: The ADO.NET Data Service

Data Services follow the Representational State Transfer (REST) design paradigms. This design depends entirely on the plain HTTP verbs: POST, GET, PUT, and DELETE to perform Create, Read, Update, and Delete (CRUD) operations, respectively. With REST, you enjoy simplicity and ease, and is most suitable when you are in no need to the complexity (yet sometimes absolute must) of SOAP with XML Web Services or WCF. When you do not need SOAP encryption, WS-routing, WS-addressing, and any other WS-* standards, then Data Services can be the best choice for performing CRUD operations.

There are many great sources online debating the REST vs. SOAP subject, which I encourage you to read and get more insights about when to use each.

First thing to do when creating an ADO.NET Data Service is exposing the data source. I used the Entity Framework to do just that. So, follow these steps to set up the Data Service project:

  1. Create an empty VS 2010 solution and call it “CarRentalDemo”.
  2. In the attached files, you will find a folder “CarRentalDataService“. Copy this file into your intepub/wwwroot folder, and from within IIS, create its application.
  3. Add the “CarRentalDataService” project as an existing web site into the “CarRentalDemo” solution.

Now, let’s examine what makes the Data Service project. From within VS, you will see the following files:

  1. CarRental.edmx: This will create an object representation of the CarStore database. Before exposing a database via REST style in a Data Service, we need to have the object model of that database. This object model is best represented using the ADO.NET Entity Framework.
  2. CarRentalService.svc and CarRentalService.cs: Now with the object model ready, we need to create the Data Service itself. CarRentalService.cs is used to indicate what the Entity Model is which we are exposing, and CarRentalService.svc is the physical Data Service pointing to the CarRentalService class.

That’s all that is required in order to build a Data Service. Now, from within Visual Studio, you can right click CarRentalService.svc and select Browse, and you will be able to query the data source in a REST style. For example, to select the car with ID “Honda”, use the following URL: http://localhost/CarRentalDataService/CarRentalService.svc/Cars('Honda').

Using the browser is enough only for browsing; however, in order to make the Data Service usable in our sample, we will have to do the CRUD operations using .NET code. This will be shown next.

Part 3: Custom Activities

Following the architecture diagram, we should now be seeing the WF 4.0 Service. Prior to that, let's discuss the custom activities. Activities are the building blocks of WF. Every shape you drag from the toolbox into the WF designer is an Activity. Custom Activities allow the developer to extend the existing activities with new ones written especially for the problem in hand; it is a kind of a Domain Specific Language (DSL).

WF 4.0, in particular, encourages the use of custom activities. Prior to 4.0, WF had the Code Activity shape which allowed the developer to write code directly into the WF process. In WF 4.0, the Code Activity shape is gone, and now developers will have to create custom activities to build their components.

In our example, there are a set of custom activities that we will need to use in both the WF 4.0 Service and the WF 4.0 Client. In the attached files, you will find a project named “CustomActivities”; this is a Class Library were all activities are compiled. Add this project to your solution “CarRentalDemo”. Let’s examine its contents:

GetInput.cs: This activity collects input from a user via console, and assigns it to an output argument. Arguments are the way in WF 4.0 to get data in and out of a process. There are input arguments and output arguments. Below is the code of the activity:


See full detail: http://www.codeproject.com/KB/WF/WF4Services.aspx

Flexible Panels for WPF

I really like WPF. It's the best layout technology I've seen yet out of Microsoft. But most of the time I want my controls to take up all of the available space, and that leaves me two choices of built-in panels. First there's DockPanel, which doesn't work if I want to distribute the space between more than one control (and its requirement that the stretched control be the last child can lead to some strange XAML). Then there's the Grid, which can do it all, but its requirement that you define all of your rows and columns up front seems too verbose to me, especially if I only want a single row or column.

Having decided to implement my own Panel, I returned to my first love: wxWidgets. wxWidgets uses Sizers for layout, and in particular there are two that are relatively simple yet allow you to do most things you'd want to do: wxBoxSizer and wxFlexGridSizer.

BoxSizer

The concept of the BoxSizer class (based on wxBoxSizer) is pretty simple. It's very similar to a StackPanel in that it lines up its children in the Orientation direction and lets them be as big as they want in the other direction. However, it also provides a Proportion attached property for its children. All of the leftover space in the Orientation direction is divided up among the children that have a non-zero proportion. For simplicity in this article, we'll develop a sizer with fixed Orientation (Horizontal), but the download uses an Orientation property just like the StackPanel class.

Sizers1.png

The Proportion Attached Property

An attached property allows us to essentially add properties to other classes. We'll need one of these so our children can tell us what proportion they want to have. The first step is to register the attached property. This involves telling the framework what the type of the property is, what our type is, and what the default value is. We can also tell the framework that it needs to re-evaluate the layout when the property changes.


See full detail: http://www.codeproject.com/KB/WPF/Sizers.aspx

WPF Data Bound Menus

DataBoundMenus

Introduction

There is not just one way to make a WPF menu work. There are several techniques that you have to combine. Much of an application's menu is static. Some of it is context sensitive, and only appears in certain conditions. And in a few places, the menu items are dynamic, like recently opened files or currently open windows. This article demonstrates techniques for each case.

The sample code uses and includes an open source library called Update Controls that helps with data binding. Although the sample code depends upon it, these techniques themselves will work without Update Controls, except where otherwise stated.

Declarative Menu Structure

For the static menus, you want to declare the structure entirely in XAML. This gives you the greatest design/code separation, and the best tool support. Bind each of the menu items to an ICommand property in your view model.


See full detail: http://www.codeproject.com/KB/WPF/wpf_data_bound_menus.aspx

How to Perform WPF Data Binding Using LINQ to XML – Part 2

Introduction

This part of the article is a sequel to the previous article on how to develop a WPF application that can bind to XML data stored inline using LINQ to XML classes. In this part, I have discussed how to bind to an XML data stored in a file system.

It requires trivial changes in the XAML and the code-behind to bring in the same functionality here as we noted in the previous sample.

Change 1

Remember that we kept the XML chunk of data of our previous sample in the CDATA section, inline with the XAML code. Using the MethodName="Parse" specification in the Object DataProvider, this XML data is parsed and stored as an XElement instance.

Now, let us take a look at the resources section of the new XAML markup.


See full detail: http://www.codeproject.com/KB/WPF/WPFBindingToLINQXMLpart2.aspx

How to Perform WPF Data Binding Using LINQ to XML

System.Xml.Linq

Before binding XML data with WPF controls, let me give you an overview of the System.Xml.Linq namespace. It contains the classes for LINQ to XML. LINQ to XML is an in-memory XML programming interface that enables you to modify XML documents efficiently and easily.

Using LINQ to XML, you can:

  1. Load XML from files or streams.
  2. Serialize XML to files or streams.
  3. Create XML trees from scratch using functional construction.
  4. Query XML trees using LINQ queries.
  5. Manipulate in-memory XML trees.
  6. Validate XML trees using XSD.
  7. Use a combination of these features to transform XML trees from one shape to another.

For data binding efforts, we need to focus on two classes in this namespace, namely: XAttribute and XElement. The dynamic properties of these classes help us to exactly bind the control to the respective elements in the XML data.

The XAttribute class is derived from the XObject class and it represents an XML attribute. Attributes are not derived from XNode; they are not nodes in the XML tree. Instead, they are simply name/value pairs associated with an element.

The XElement class is derived from the XContainer class which derives from the XNode class, and it represents an XML element, the fundamental XML construct. An element has an XName, optionally one or more attributes, and can optionally contain contents like XElement, XComment, XText, and XProcessingInstruction.

Each XElement contains a list of attributes for that element. Attributes must have a qualified name that is unique to the element.

As an example, the following C# code shows the common task of creating an element that contains an attribute:


XElement phone = new XElement("Phone",    new XAttribute("Type", "Home"), "555-555-5555"); Console.WriteLine(phone);

Dynamic Data Binding in WPF and Dynamic Properties

Having learnt that we have a couple of XLinq classes available with us, the next step is to understand how data binding can be performed with these classes.

By default, data binding occurs only when the target UI element is initialized. This is called one-time binding. For most purposes, this is insufficient; with two-way binding, changes to the source are automatically propagated to the target, and changes to the target are automatically propagated to the source.

For one-way or two-way binding to occur, the source must implement a change notification mechanism, for example, by implementing the INotifyPropertyChanged interface or by using a PropertyNameChanged pattern for each property supported.

Most LINQ to XML classes do not qualify as proper WPF dynamic data sources. To support WPF data binding, LINQ to XML exposes a set of dynamic properties. These dynamic properties are special run-time properties in the XAttribute and XElement classes to act as dynamic data sources for WPF and implement change notifications.

The dynamic properties in the XAttribute and XElement classes cannot be accessed like standard properties. In C#, dynamic properties can only be accessed at run time through facilities provided by the System.ComponentModel namespace. However, in an XML source, dynamic properties can be accessed through a straightforward notation in the following form: object.dynamic-property.

The dynamic properties for these two classes either resolve to a value that can be used directly, or to an indexer such as Elements and Descendants property of XElement, that must be supplied with an index to obtain the resulting value or collection of values.

To implement WPF dynamic binding, dynamic properties will be used with facilities provided by the System.Windows.Data namespace, most notably the Binding class.

XML as Resource Data in XAML

Now, let us look at the various elements of XAML that can be used to define and use XML data. Also, this section explains the elements required for defining the resources, templates, and subsequent binding of these to the WPF controls.

Inside the Windows.Resources tag, we can declare the data source to XML data using the <ObjectDataProvider> and also a <DataTemplate> that follows a certain pattern of data elements.

The <ObjectDataProvider> tag declares an instance of ObjectDataProvider class, named LoadedBooks that uses an XElement as the source. This XElement is initialized by parsing an embedded XML document (a CDATA element). Also, white space is preserved when declaring the embedded XML document and when it is parsed. The reason is that the TextBlock control, which is used to display the raw XML, has no special XML formatting capabilities.

A DataTemplate named “BookTemplate” is defined to display the entries in the respective controls in the Book List UI section. It uses data binding and LINQ to XML dynamic properties to retrieve the book ID and book name through the following assignments:


See full detail: http://www.codeproject.com/KB/WPF/WPFBindingToLINQXML.aspx

AttachedPropertyEvent Pattern

Introduction

In our project we use the Composite WPF model, and we needed a way to publish events from our views (XAML code) without creating any code-behind, and without having any dependencies. To publish and subscribe to events, we already used IEventAggregator, but still we had to write some code-behind in order to publish the events.

So we came up with what we call "AttachedPropertyEvent".

About the Example

In this example, I'm going to implement SelectedItemsChanged on a datagrid. The datagrid resides in a view, and I wish to subscribe to this event in some viewmodel.

Implementation

First we create an AttachedProperty with get and set methods, and a callback to perform some logic. This class resides in our Infrastructure project, and namespace Events.


See full detail: http://www.codeproject.com/KB/WPF/AttachedPropertyEvent.aspx