Showing posts with label C# Dynamic Binding. Show all posts
Showing posts with label C# Dynamic Binding. Show all posts

Monday, 5 March 2012

Dynamic Data in Asp.net 4.0. Part3 : Customizing Dynamic Data application

This is the 3rd and last part of the article on Asp.net Dynamic Data and in this part we are going to learn how to customize a Dynamic Data application.

Dynamic Data in Asp.net 4.0. Part2 :Understanding the Application project and its internal building blocks

Dynamic Data in Asp.net 4.0. Part1 : Introduction

 explains the details of a Dynamic Data application and introduces it's building blocks. Once you go through that post, you will understand how a Dynamic Data application works and this is important to learn how to customize it.


Dynamic Data lets you quickly build a data driven Asp.net application that lets you perform the CRUD functionality along with the listing and details pages without writing almost a single line of code! But, in a real worl'ds application, the CRUD (Plus listing and details pages) functionality is not enough, and, most of the cases you would need to build custom-designed pages with many other customized functionality.

One of the cool features of Dynamic Data is, it lets you easily customize the functionality at each granular level, and, there is no alien codes to customize (Unlike most other code generation framework). Customizing a Dynamic Data application is too easy once you understand how it works.

Lets start customizing it!

Scaffolding only particular tables instead of all

Find the following piece of codes in the Global.asax


1
2
DefaultModel.RegisterContext(typeof(DynamicDataEntities),
                new ContextConfiguration() { ScaffoldAllTables = true });

Specifying ScaffoldAlltables = true  in the above code instructs the Dynamic Data engine to generate codes for all tables in the data source (Be it an Entity framework data source or a Linq data source). Most of the cases this is not desired and we need some mechanism to scaffold only the tables we woul like.

To do this, perform the following steps:

Specify ScaffoldAllTables = false (Which is the default).

Let's assume the following three tables are included in the Entity (Or Linq) data context and we would like only to scaffold Employee and Address tables.


Figure : Entity Model
Add a cs file (Say, Entity.cs) in the Dynamic Data project, write two partial classes for the Employee and Address table and specify the ScaffoldTable(true) attribute for each of the classes as follows:


1
2
3
4
5
6
7
8
9
[ScaffoldTable(true)]
public partial class Address
{
}
 
[ScaffoldTable(true)]
public partial class Employee
{
}

Build and run the project. You would see that, only Employee and Address table has been included now in the Dynamic Data application and the other (Department) table is ignored:


Figure : Output after scaffolding only selected tables
Customizing display for individual fields

As you may already know, the "FieldTemplates" folder contains templates (In the form of User Controls) for most common data types. So, customizing these templates would result in a global change for the corresponding data types.

For example, the Text.ascx contains the following markup for displaying a text field:


1
<asp:Literal runat="server" ID="Literal1" Text="<%# FieldValueString %>"/>

If you want to display all the text fields in Green color, you can replace the above markup with the following (Assuming that you added a css class "GreenText" in the Site.css and set color : Green):


1
<asp:Label runat="server" ID="Literal1" Text="<%# FieldValueString %>" CssClass="GreenText"/>

After doing the change, browse the application and go to the listing page of any table. You would see the text fields all turned into green:


Figure : Customizing text field display
If you go to any other page, you would see the text color turned into green. That's some power! So now you have the field templates, and you know how to customize those to make any global change in your application. Its all yours!

Customizing display for a table data

The "EntityTemplates" folder contains the following three templates (In the form of User Controls) which determine how to display each column value of data for a particular table in Display, Edit and Insert mode.


Figure : EntityTemplates
So, changing the templates inside this folder results in changing the display of the column values for a particular table.

As an experiment, lets do a little change in the \EntityTemplates\Default.ascx like the following (Add the class="LightGrayBackground", along with adding the class LightGrayBackground in the Site.css with setting a light gray background-color):


Figure : Customizing Entity template
After doing so, run the aplication and go to the View Details page for a particular data of a table. You would see that, the background color of each cell is changed:


Figure : Output of a change in EntityTemplates
Similarly, you can customize the Default_Edit.aspx and Default_Insert.aspx to customize the layout and functionality of Edit and Insert view for the column values. Like the FieldTemplates, customizeing the EntityTemplates lets you make global changes from a single point.

Customizing pages

The "PageTemplates" folder contains the page templates, which are as follows:


Figure : Page Templates
As you know already, doing any change in any of these page templates (And their corresponding code behind classes) would result in change of display and functions in the corresponding pages.

For demonstration, just do a minor change in the Details.aspx as follows (Append the text in Red border):


Figure : Customize Details.aspx PageTemplate
Run the application and as you expected, when the details page is viewd for a particular data in a Table, the output would be now changed as follows :


Figure : Change in output after customizing Details.aspx
Like the FieldTemplates and EntityTemplates, doing any change in the PageTemplates also results in a global change for all tables in the application.

Using a customized page for a particular table

The aspx files in the PageTemplates folder are globally used by all tables. For example, the PageTemplates\Details.aspx is used to show the details page for a particular data for all of the tables. So, any customization done in these aspx files result in the corresponding change getting effected for all tables. This might not be desirable in case we need to have a specialized page for a particular table.

Fortunately, it is very easy to create a specific customized page for any particular table in Dynamic Data application. All you need is to create a folder within the "CustomPages" folder and name the folder same as the target Table name.

For example, if we want to create a customized details page for Address data, we would need to create the Details.aspx within the "Addresses" folder inside "CustomPages" folder as follows:


Figure : Customized details page for Addresses table
For simplicy, lets copy the contents of aspx markup and codes from code behind class from PageTemplates\Details.aspx and paste onto CustomPages\Addresses\details.aspx and customize the markup of CustomPages\Addresses\details.aspx as follows:


Figure : Customize Details.aspx for Addresses table
Build and run the application and go to the details page of a data in Addresses table. You would see an output like the following:


Figure : Custmized details page output for a specific table
Similarly, you can customize the other pages also for a particular table (Say, Insert.aspx, List.aspx, Edit.aspx etc) using the same approach.


Using a customized EntityTemplate (Details view) for a specific table

Like the custom pages, it is possible to define customized EntityTemplates for a particular table to display column values for a particular table. For this, you need to create templates (In the form of user controls) within the EntityTemplates folder as follows:


Figure : Customized EntityTemplate files for Addresses table
That is, you need to copy the existing EntityTemplate files and replace the word "Default" with the corresponding table name (In this cases, Addresses). Once done, customize the files as you like and see the outputs in Details/Edit and Insert views.

Using a customized field output for a particular table

Most of the cases, you would want to have the same look & feel and functionality for particular data types in your application. But, in some particular case, you might want to have customized look & feel or functionality for a particular data type for a particular table. For example, you may want to display textual field values with a border when the data in Addresses table is viewed. You need to perform the following steps to do this:

1. Copy the Text.ascx and create a new user control (Say, Address.ascx) and customize the User Control's markup as follows:

?
1
2
3
4
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="Address.ascx.cs" Inherits="WebApplication2.DynamicData.FieldTemplates.Address" %>
<asp:Label runat="server" ID="Literal1" Text="<%# FieldValueString %>"
style="border:1px solid black" />

2. Create a partial class for Addresses table (If it is not there already) with a MetaData class and specify the UIHint attribute as follows:

?
1
2
3
4
5
6
7
8
9
10
11
[ScaffoldTable(true)]
[MetadataType(typeof(AddressMetadata))]
public partial class Address
{
}
 
public partial class AddressMetadata
{
    [UIHint("Address")] //UIHint(User Control's name)
    public string AddressName;
}

After doing the above, build the application and you will see a border around the Address data as follows:


Figure : Customize field output for table
Notice that, the borders are displayed only when the "Addresses" pages are being viewed. for any other tables, no border is going to be displayed.

Well, these are the basic customizations you might want to know about a Dynamic Data application. While building a real world application, you might learn and discover newer customzation needs and once you are used to the basic stuffs, it won't be hard for you to do those customizations. Feel free to explore the customizations and enjoy Dynamic Data.

Dynamic Data in Asp.net 4.0. Part2 :Understanding the Application project and its internal building blocks

Dynamic Data in Asp.net 4.0. Part2 :Understanding the Application project and its internal building blocks

 

Dynamic Data in Asp.net 4.0. Part1 : Introduction

we learned how to create an Asp.net Dynamic Data web application project using Visual Studio 2010 and utilize it's power to generate a CRUD application for all tables in a database. In this post we would try to understand the Dynamic Data application project structure and its internal building blocks, which would help us to customize the application later, to suit the requirement of a real world application.


When a Dynamic Data application porject is being opened in the Visual Studio 2010, it will be shown as follows in the solution explorer:

Figure : Dynamic Data application project in Solution Explorer
Except the Model1.edmx (Which has been added later as Entity data model), all other files and folders are initially created by the Visual Studio. Let's try to understand the project structure and the files/folders in this solution.

Global.asax

The Global.asax file contains the initialization codes for the Dynamic Data application and the codes are executed when the Application starts. Basically, it initializes the Data model for the application (The Entity data model in this case) using the following piece of code:

?
1
2
DefaultModel.RegisterContext(typeof(YourDataContextType),
new ContextConfiguration() { ScaffoldAllTables <b>= </b>false });

The Entity context class name is to be provided in place of YourDataContextType (In our example, which would be DynamicDataEntities) and the ScaffoldAllTables = true has to be set in order to make sure that the Dynamic Data engine generates CRUD functionality for all tables in the Entity context. It is however possible to specify not to sfaffold all tables by keeping ScaffoldAlltables = false and doing customization so that sfaffolding applies on individual table levels only. But, for now, let's keept it simple as the customization options will be discussed in the next part of the posts.

Along with Scaffolding, the routing rule is configured in Global.asax as follows:

?
1
2
3
4
5
routes.Add(new DynamicDataRoute("{table}/{action}.aspx")
{
   Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert"}),
   Model = DefaultModel
});

The above code specifies that, the URL patterns for the Dynamic Data application would be of the form "{table}/{action}.aspx" (Say, Department/Edit.aspx, or, Department/Details.aspx), and, the corresponding actions would be either "List"or "Details" or "Edit" or "Insert" for the URLs. It also sets the current Data model (Model = DefaultModel) to which the routing would be applied.


Default.aspx

It is the default page which lists the tables using a GridView and renders each Table using a Hyperlink.
Figure : Table listing in Default page
Open the Default.aspx and you would see the following code:

Figure : DynamicHyperLink
As you probably figured out, in the Default.aspx, the Tables are bound to the GridView's DataSource, and, that results in displaying table names using hyperlinks, which are generated by the <asp:DynamicHyperLink/> control inside the <ItemTemplate>.

The <asp:DynamicHyperLink/> is a Server control which is used in Dynamic Data application to display links for different actions such as edit, delete, and insert. The <asp:DynamicHyperLink/> has a "Action" property which could be set either of the values "Details" or "Edit" or "Insert" or "List" and if this property value is not set, by default, "List" is assumed. So, the following URLs are rendered by the DynamicHyperLink control for the above codes in Default.aspx (Using the format {table}/{action}.aspx):

/Addresses/List.aspx
/Departments/List.aspx
/Employees/List.aspx

Just to understand a bit more, had we set Action = "Details", then the Table names would have been rendered using the following hyperlinks (Which is of course, not applicable here):


/Addresses/Details.aspx
/Departments/Details.aspx
/Employees/Details.aspx

DynamicData\PageTemplates

The "PageTemplates" folder contains the templates for the pages for the following actions:

Details (Details.aspx) : For showing details for a particular row in a table
Edit (Edit.aspx) : For showing a particular row in a table in edit mode
Insert (Insert.aspx) : For inserting a row for a table
List (List.aspx) : For listing a table data
ListDetails (ListDetails.aspx) : For listing a table data along with displaying detailed data for a particular row

Figure : PageTemplates in Dynamic Data application
Open Details.aspx and you will see that the aspx markup mainly contains following code:

Figure : Codes in Details.aspx
Notice the DynamicEntity server control. This control is a place holder control used to load a particular control from the DynamicData\EntityTemplates folder.

Note that, the DynamicData\EntityTemplates folder contains the following three user controls:

Default.ascx  : Displays the columns values for a particular row in current table
Default_Edit.ascx : Displays the columns values for a particular row in current table in Edit mode.
Default_Insert.ascx : Displays input fields for a particular row in current table.

When <asp:DynamicEntity runat="server" /> is used in the Details.aspx, it is replaced by the user control \EntityTemplates\Default.ascx at run time. Similarly, when <asp:DynamicEntity runat="server" Mode="Edit" /> is used in Edit.aspx, it is replaced by the \EntityTemplates\Default_Edit.ascx and when <asp:DynamicEntity runat="server" Mode="Edit" /> is used in Edit.aspx, it is replaced by the \EntityTemplates\Default_Insert.ascx.

So, when a particular Page template is executed, in place of the <asp:DynamicEntity/> controls, a particular EntityTemplate controls gets executed for each of the row in the current Table.

DynamicData\EntityTemplates

As said already, this folder contains three user controls to display column values for a row in a Table in three different modes : Display, Edit and Insert.

Figure : EntityTemplates in Dynamic Data application
At runtime, either of these three user control replaces the <asp:DynamicEntity/> control in the Page template depending upon the Mode property value.

Open the Default.ascx and you will see the following markup

Figure : EntityTemplate Markup
The CodeBehind of this user control populates the column values for a particular row in the current table using the following code:

?
1
2
3
4
5
6
7
8
9
10
protected override void OnLoad(EventArgs e)
{
    foreach (MetaColumn column in Table.GetScaffoldColumns(Mode, ContainerType))
    {
        currentColumn = column;
        Control item = new _NamingContainer();
        EntityTemplate1.ItemTemplate.InstantiateIn(item);
        EntityTemplate1.Controls.Add(item);
    }
}

Now, while populating the column values for a particular row, it needs to render an appropriate control based upon the type of the column value (Say, if the column value is of a Boolean type, it should be rendered using a CheckBox, or, if the column value is of a Text type, it should be rendered using a TextBox). The EntityTemplate uses a specialized control <asp:DynamicControl/> (Mark in red above) to dynamically render an appropriate control based upon the column type of the table.

The <asp:DynamicControl/> control has a property "Mode" which could have either of the three values "Edit" "Insert" and "ReadOnly". In the Default.ascx, the "Mode" property value is not specified. On the other hand, in the Default_Edit.ascx, the "Mode" property value is set to "Edit" and in the Default_Insert.ascx, the "Mode" property value is set to "Insert" to insertuct the Dynamic Data runtime that the corresponding controls should be rendered in appropriate mode depending upon the Page (In Details.aspx, a text data should be displayed using a Label, and, in Edit.aspx, a text data should be displayed using a TextBox.

The good news is, you can decide what exact control to render for each particular column type in "Insert" "Edit" and "ReadOnly" mode. The user controls inside the FieldTemplates folder let you do this.

DynamicData\FieldTemplates

This folder contains some tiny user controls as templates to configure what specific control to render for each specific data type in "Insert" "Edit" and "ReadOnly" mode.

Figure : FieldTemplates in Dynamic Data application
At runtime, the <asp:DynamicControl/> controls are replaced by one of the user controls within the FieldTemplates folder and the specific user control is chosen based upon the data type of the column and the Mode property value of the <asp:DynamicControl/> control. For example:

Text.ascx : This user control template is used to replace the DynamicControl for columns of type varchar/text for readonly mode. It has the following markup:


1
<asp:Literal runat="server" ID="Literal1" Text="<%# FieldValueString %>" />

Text_Edit.ascx : This user control template is used to replace the DynamicControl for columns of type varchar/text for edit mode. It has the following markup:


1
2
3
4
5
6
<asp:RequiredFieldValidator runat="server"  ID="RequiredFieldValidator1" CssClass="DDControl DDValidator" 
ControlToValidate="TextBox1" Display="Static" Enabled="false" />
<asp:RegularExpressionValidator runat="server"  ID="RegularExpressionValidator1" CssClass="DDControl DDValidator" 
ControlToValidate="TextBox1" Display="Static" Enabled="false" />
<asp:DynamicValidator runat="server" ID="DynamicValidator1"  CssClass="DDControl DDValidator"
ControlToValidate="TextBox1"  Display="Static" />

DynamicData\Filters

There is a Filters folder which contains three user controls (Templates) for displaying filter options for each individual rows in the listing page.

Figure : Filters
If you open the List.aspx page template you would see an <asp:DynamicFilter> controls is being used there as follows:

Figure : DynamicFilter control

The <asp:DynamicFilter/> control is used in the page markup to generate the UI for filtering table rows. Dynamic Data creates the UI by using the default filter templates that are in the \DynamicData\Filters folder. These templates support foreign-key, Boolean, and enumeration column types.

When the List.aspx page is viewed for a particular table, the Filter user controls are executed to render to filter the listing data as follows:


Figure : Filtering data in List.aspx
Others

The DynamicData\Content folder contains the resources and contents that are to be used by the tamplates. Initially this folder contains a Pager template (GridViewPager.ascx) to be used as the pagination template for the GridViews in the List.aspx, and, an "image" folder containing some images.

The CustomPages folder is initially empty. This folder would contain any custom page template that we might need to create for a particular table if we want.

Hope, this post was helpful to understand the building blocks of a Dynamic Data application project, and also to learn how the application works. The next post is going to cover the customizations options that you might need to do when you would want to use Dynamic Data for your next Asp.net application project.

next artical to learn how to customize a Dynamic Data application.

 

 

Dynamic Data in Asp.net 4.0. Part1 : Introduction

Dynamic Data in Asp.net 4.0. Part1 : Introduction
Introduction

Dynamic Data in Asp.net was first introduced in .NET 3.5 SP1, and later was improved in Asp.net 4.0. For those who were longing for a RAD (Rapid Application Development) platform in Asp.net, Dynamic Data was a real good news for them. It provides a framework to quickly develop a Data Driven Asp.net application by generating CRUD functionality for the database tables. But, if you want to consider Dynamic Data as just another Code Generator tool, you are completely wrong. Generation of codes is just a part of the Dynamic Data framework. What makes it different? Well, unlike most other code generation frameworks, the framework allowes you to utilize the powerful Dynamic Data features without using the code generation based on database tables (scaffolding) at all! Most importantly, the Dynamic Data framework is so elegantly designed that its really easy for you to customize the framework generated codes at each granular level and this makes it really valuable and effective to be considered as a RAD framework to build your next Asp.net application.

In this Part1 of the article on Dynamic Data in Asp.net, I'll cover the basics and then will eventually cover the customizations which you might need to know when developing real applications.

Here we go.

Creating a Dynamic Data Application project

Assuming you are using Visual Studio 2010, go to File->New project->Asp.net Dynamic Data Entities Web Application (If you want to develop a Dynamic Data application based on Entity framework) or File->New project->Asp.net Dynamic Data Linq to SQL Web Application (If you want to develop a Dynamic Data application based on Linq to SQL) and click "OK" to let Visual Studio create the project.


Figure : Add new dynamic data project
Once the project is created, it will be shown in the solution explorer as below:


Figure : Dynamic Data project in Solution Explorer
Running a Dynamic Data Project

As Dynamic Data is a Data driven Asp.net application, it cannot be run unless we configure the data source for the application project.

Follow these steps to execute a "Hello world" run of the Dynamic Data application.
Right click on the project and Add an "ADO.NET Entity Data Model" to launch the wizerd to configure the Entity data model and specify inputs in each step until Finish.


Figure : Add ADO.NET Entity Data Model

Figure : Choose Data Model

Figure : Choose Database


Figure : Choose Database objects (Tables)
Once done, the Entity Model will be added in the solution and it will be displayed in the designer view and in the solution explorer.


Figure : An Entity data model
Figure : Entity Model in Solution Explorer
Double click on the Designer.cs file of the Entity Model (edmx) to open the corresponding Code file and expand the region "Context" to find the Entity context class name.


Figure : EntityContext class
Copy the class name (The class which inherits the ObjectContext class) for the Entity context and open the Global.asax in the Visual Studio editor to register and configure the Dynamic Data with the Entity context class. 

To configure, uncomment the following line in the Global.asax (Which is commented out by default , and paste the Entity context class name (DynamicDataEntities in this example) within the typeof() operation (The first red box)



Figure : Configure the Entity Context with Dynamic Data

Also, specify ScaffoldAllTables = true (Which is by default false) to specify that the Dynamic Data engine should generate codes to perform CRUD operations for all tables in the database (Ideally, this may not be desired, but, for understanding and running the very first Dynamic Data application, lets keep this simple).
Build the Application and once build is successful, Run or Debug the application. It will launch the application which should be something like as follows:

Figure : Dynamic Data web site
 Click on a particular Table name in the listing and it will show a listing page including all filtering options (For all the foreign keys) with Insert/Update/Delete links for each data


Figure : Listing page for a particular table

Using the Filter options you can filter the listing page by selecting particular filter data. The filter data are retrieved from the database using the foreign key values. Also, clicking on the "Insert new item" link below allows you to enter a new item in the system and the Edit and Delete links let you Edit a particular item and Delete one respectively.

Creating a Dynamic Data web application project and running it by configuring an Entity or Linq to SQL Data source requires 5 minutes of works at best and the end result is a powerful bug free CRUD application for the entire database generated right way.

In the next part of this article we would try to understand the building blocks of the Dynamic Data Application project, which would eventually help us customize the application when we would implement a real application using this framework.


Tuesday, 7 February 2012

Dynamic SQL Server stored procedure execution form in SSMS

 

Problem
The purpose for most stored procedures is for execution within applications, but there are some stored procedures that may be used for administrative purposes and only get executed ad hoc.   In addition, during testing you run stored procedures interactively to make sure things are working correctly.  You have the ability to run any stored procedure directly from a query window and include the necessary parameters, but is there any easier way to know what parameters a stored procedure requires and to pass the parameters directly to a stored procedure?

Solution
In SQL Server Management Studio you have the ability to execute a stored procedure directly from the object browser tree.  Just browse to the desired stored procedure and right click and select "Execute Stored Procedure..." as shown below.


When you select "Execute Stored Procedure..." a window such as the following will pop up that will give you the list of parameters to use for the stored procedure.

Enter the value you want to use for the parameter and select "OK" to run the stored procedure.

The stored procedure will execute based on the parameters you pass as well as create sample code such as the following that is used for the execution of the stored procedure.

That's all there is to it.  This is a pretty simple tip, but could save you a lot of time if you need to run a stored procedure and don't want to mess with having to type the commands or if you don't remember the exact parameters that the stored procedure needs.
The only downside to this is that it only works for user defined stored procedures.  System stored procedures do not give you the option to use the "Execute Stored Procedure...".
 Next Steps
  • Next time you need to run a stored procedure use this technique as a faster way to execute the code

Reff ..to Posted by ==By: