Sunday, October 26, 2008

LINQ to Sql

I am going to demonstrate LINQ to Sql by writing code.

Support you have a table called Categories in Shalvin database you need to first create a Entity. An Entity is a class that represents a Table or a view in the database.

Create a class as follows:
Set a reference to Data.Linq.

using System.Data.Linq.Mapping;

[Table]
public class Categories
{
[Column(IsPrimaryKey=true, IsDbGenerated=true)]
public int CategoryId { get; set; }

[Column]
public string CategoryName { get; set; }

[Column]
public string Description { get; set; }
}

Each property should have Column Atribute. I am also setting values of IsPrimaryKey and IsDbGenerated for CategoryId column. Editing is possible only if IsPrimaryKey is set to true. IsDbGenerated Indicated that it is an Identity column.


In the asp .net page :

using System.Data.Linq;
protected void Page_Load(object sender, EventArgs e)
{
string ConString = "Integrated Security=sspi;Initial Catalog=Shalvin";
DataContext db = new DataContext(ConString);
var tMovies = db.GetTable<categories>();
GridView1.DataSource = tMovies;
DataBind();
}Now suppose you are interested only in viewing the Categories table with CategoryName 'Confections'.

GridView1.DataSource = tMovies.Where(m => m.CategoryName.Contains("Beverages"));
The DataContext is the source of all entities mapped over a database connection. It tracks changes that you made to all retrieved entities .

Linq to Sql with Visual Studio Tools

Having seen the internals lets turn our attention to the Visual Studio Support of Linq to Sql.
Here I have started an Empty Visual Studio Project and Added a Linq to Sql Classes from the Add New Item Dialog. I have renamed it AirLines.dbml



On to the design surface it is possible to drag the table from Database Explorer.



That's all I have to do and I am ready to do CRUD operation with the selected tables.

AirLinesDataContext context = new AirLinesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    GridView1.DataSource = context.Locations;

    DropDownList1.DataSource = context.Locations;
    DropDownList1.DataTextField = "LocationName";
    DropDownList1.DataValueField = "LocationId";

    DataBind();
  }
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
  Response.Write(DropDownList1.SelectedValue.ToString());
}

protected void btnInsertLocation_Click(object sender, EventArgs e)
{
  var loc = new Location { LocationName = "London", Latitude =67 };
  context.Locations.InsertOnSubmit(loc);
  context.SubmitChanges();
}


Related Blogs
Linq to Objects
Linq to Xml (Code Snippets)

Wednesday, October 15, 2008

Microsoft Innovation Days Kochi

Learn for free about building reliable, high performance applications with a super-rich user interactivity using Microsoft technologies, such as the Visual Studio 2008, SQL Server 2008, Windows Server 2008, Silverlight 2 RC0 and Internet Explorer 8.

Date: November 6, 2008 (Thursday)

Venue: Taj Residency
Marine Drive, Shanmugham Road
Ernakulam, Cochin 682304

9 am Tea and Registration

9:45 AM Keynote - The magic of Software

Sneak peak into the host of technology innovations that Microsoft is working on - Windows 7, Live platform, Cloud services and many more , accompanied with uber-cool demos.

10:45 AM Next generation web experience with IE 8 and Silverlight
Learn how you can leverage some of the developer features in IE 8 to "light up" your web site and provide a compelling experience to your website users by rendering your data on Silverlight controls.

12:00 PM SQL Server – Optimize your Queries

Lunch Break (1.30 - 2.30)

2:30 PM Partnering with Microsoft
Learn about the various partnering opportunities with Microsoft that will support and enhance your development and marketing efforts.

3:00 PM AJAX - Get it right for your
ASP.NET Applications
Find out how to AJAX Enabling your ASP.NET Applications in the right way and also explore some of the best practices to build a high performance web application. Finally, learn how the new version of ASP.NET improves AJAX enabled web development.

4:30 PM The developer's toolkit for building .Net applications.

Find out the host of tools you can use to analyze and identify performance bottlenecks in your .Net applications. Explores some of the in-built tools that ships with the .NET SDK such as ildasm, gacutil, ngen, fxcop etc and and features in Visual Studio. which will help you develop better, faster, more secure, error free NET applications.

Click here to register

Friday, October 10, 2008

Silverlight 3/Wpf : Adding Controls Dynamicallys

Lets see how to dynamically add controls and attaching event handler to the added control.

Here I am creating an object of button class and adding it into the Grid using the Add method of Grid's Children property.

private void btnAddControl_Click(object sender, RoutedEventArgs e)
{
Button btn = new Button();
btn.Click += new RoutedEventHandler(btn_Click);
btn.Content = "Shalvin";
btn.Width = 75;
btn.Height = 25;
Grid1.Children.Add(btn);
}

private void btn_Click(object sender, RoutedEventArgs e)
{
//MessageBox works only with WPF , Silverlight 3 and not with Silverlight 2
MessageBox.Show("ShalvinPD.blogspot.com");
}

Result

WPF Routed Event

A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.

For example if you want a single event handler for the buttons inside a Grid you can define a Routed event as Button.Click = "Grid_Click" inside the Grid as shown in the diagram.









private void Grid_Click(object sender, RoutedEventArgs e)
{
//MessageBox works only with WPF and not Silverlight 2
MessageBox.Show("ShalvinPD.blogspot.com");
}

Wednesday, October 8, 2008

WPF Templates

WPF introduces the concept of lookless controls.

Using Templates it is possible to change the appearance of a control. For examples it is possible for a ListBox to contain the Photos of employees instead of the usual List Items.

I am going to demonstrate creating a simple Template whereby a button will appear as a blue rectangle.














Silverlight Tags

<UserControl x:Class="ButtonTemplate.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <Button Height="50" Width="75">
            <Button.Template>
                <ControlTemplate>
                    <Rectangle Fill="LightBlue"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
    </Grid>
</UserControl>




Result



















As shown in the output the button can respond to click event as expected.

Now lets create an ellipse button.










Result

Monday, October 6, 2008

WPF Styles

Styles are equivalent to CSS in html. Lets see how to create Styles in WPF.Inside the Window Xaml tag add a Window.Resource section.In the Style tag's TagetType you can specify to what type of control you want the style to apply. Using Setters you can specity the Property and and its corresponding value.























Here is the result





















In this example I am setting the Background, Width and Opacity properties for Button. All the buttons in the form will inherit these properties thereby rendering a consistant look and feel.

Wednesday, September 3, 2008

Asp .Net Validation Controls

Client Side validation is an important task in Web Application development. All server side technologies except Asp .Net expects the programmer to be conversant with JavaScript, the default client side scripting language. Asp .Net comes packed with a number of validation control which emits javascript thus making the life of programmer easier.

RequiredFieldValidator
RequiredFieldValidator can be used to check whether a value is entered into a control.
Place a RequiredFieldValidator next to the control you want to check for the extistence of value.
Set the ControlToValidate Property to the Control you want to validate. Set an appropriate errror message using the ErrorMessage property. If you submit the form without entering the a value to the TextBox the use will receive an error message.



Result



















RequiredFieldValidator InitialValue

Suppose you want to display an additional message inside the textbox and that text shouldn't be treated as an input text. Then you can set the InitialValue of RequiredFieldValidator to the text that is displayed in the textbox.

























CompareValidator
CompareValidator can used for :
i. checking the type of contents in a control, for example whether the value entered is numeric.
ii. Check for equality of the contents in two controls, for example checking the text of Password and Reenter Password textboxes.
iii. Checking whether the values of two controls are greater than, lesss than, etc. for example wheter the value entered in Bid textbox is greater than the value in Price textbox.



OperatorCheck Property

i. Lets take up the first scenario. We want to check whether the value entered into a control is numeric.





As usual add a CompareValidator next to the control you want to validate. Set the ControlToValidate and ErrorMessage as in the case with RequiredFieldValidator. Set the Operator property to DataTypeCheck and Type to integer.




Now if the end user happens to enter a non numeric value he will receive an error message specified in the ErrorMessage property.








































































ControlToCompare Property

ii. Let's take up the scenario of checking the equality of values entered in two controls as in the case with Password and Reenter password textboxes.




Here set the ControlToValidate property to Re enter password textbox's id and ControlToCompare to the password textbox's id.







iii. In the case of third scenario where the Bid Amount should be greater than Price amount, set the ControlToValidate to Bid textbox's id and ControlToCompare to Price textbox's id. Next set the Operator to GreaterThan and Type to integer.





RangeValidator
RangeValidator
can be used to check wheter the value entered into a control falls under a specific range. For example we can check wheter the age is between 35 and 60. In this case apart form ControlToValidate and ErrorMessge set the MinimumValue and MaximumValue property to 35 and 60 respectively.





ValidationSummary



Instead of displaying error message side by side the textbox, it can be displayed as summary. For this you can use ValidatiorSummary control. Place a ValidationSummar Control on the form having validation controls. Set the Text Property of Validation Controls to say *. All the controls that fail the validation text will display * as shown in the figure.

Asp .Net Ajax VII : AlwaysVisibleControlExtender


With Ajax .Net we can easily make a part of the page always always visible. An example of Always visible content is the gmail's Sending message as you sent a message. Even if you scroll down the page the Sending message will be visible.




Lets see how to implement it in Asp .Net.

Open an Ajax Web Page.

Add a Panel set a BackColor and a Text.

Add an AlwaysVisibleControl Extender. Set the TargetControlId to the Panel control and HorizontalSide to Right.