Monday, December 6, 2010

Query Tool with Asp .Net



using System.Data;

using System.Data.SqlClient;

using System.Configuration;


public partial class _Default : System.Web.UI.Page

{

SqlConnection cnn, cnn2;

SqlCommand cmd;

SqlDataReader dr;


protected void Page_Load(object sender, EventArgs e)

{

cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=master");

cnn.Open();

cmd = new SqlCommand("sp_helpDb", cnn);

dr = cmd.ExecuteReader();

TreeNode tn;

if (!IsPostBack)

{

while (dr.Read())

{

ddlDb.Items.Add(dr["name"].ToString());

tn = new TreeNode(dr["name"].ToString());

TreeView1.Nodes[0].ChildNodes.Add(tn);

}

dr.Close();

}

}


protected void btnExecute_Click(object sender, EventArgs e)

{

cnn2 = new SqlConnection(@"integrated Security=sspi;Initial Catalog=" + Session["Db"]);

cnn2.Open();


cmd = new SqlCommand(txtQuery.Text, cnn2);

dr = cmd.ExecuteReader();

GridView1.DataSource = dr;

DataBind();

dr.Close();

}


protected void ddlDb_SelectedIndexChanged(object sender, EventArgs e)

{

Session["Db"] = ddlDb.Text;

}

}




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>

<table class="style1">
<tr>
<td colspan="2">
<br />
Select Database
<asp:DropDownList ID="ddlDb" runat="server" AutoPostBack="True" Height="21px"
onselectedindexchanged="ddlDb_SelectedIndexChanged" Width="122px">
</asp:DropDownList>
&nbsp;&nbsp;&nbsp;
<asp:Button ID="btnExecute" runat="server" onclick="btnExecute_Click"
Text="Execute" />
<br />
</td>
</tr>
<tr>
<td>
<asp:TreeView ID="TreeView1" runat="server">
<Nodes>
<asp:TreeNode Text="Database" Value="Database"></asp:TreeNode>
</Nodes>
</asp:TreeView>
</td>
<td>
<table class="style1">
<tr>
<td>
<asp:TextBox ID="txtQuery" runat="server" Height="87px" TextMode="MultiLine"
Width="370px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtResult" runat="server" Height="16px" TextMode="MultiLine"
Visible="False" Width="370px"></asp:TextBox>
<br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
ASP.NET 4 Unleashed</td>
</tr>
</table>
</td>
</tr>
</table>

</div>
</form>
</body>
</html>

Sunday, December 5, 2010

Entity Framework and Stored Procedures

Entity Framework also allows you to work with Stored Procedures.
I have created a stored procedure for extracting the Contact information based on GroupId.

create procedure spGetContactsByGroup (@pGroupId int)
Entity Framework 4.0 Recipes: A Problem-Solution Approach (Expert's Voice in .NET)as
select * from Contacts where GroupId = @pGroupId
go

spGetContactsByGroup 2

While running the Entity Data Model Wizard I am selecting the Stored Procedure spGetContactsByName.






















But when you look at ContactManagementModel in the Model Browser you won't see any indication of stored procedure.  For that you have to explicitly create a complex type.



















Navigate to the ContactManagementModel.Store and then to Stored Procedures section there you will find spGetContactByGroup stored procedure. Right click the stored procedure and select Add Function Import.

























In the Add Function Import dialog select Select Complex type from Return a Collection of section. Click on Get Column Information Button and then Create Complex Type Button.



Now you can see that the stored procedure is appearing as a Complex Type within the ContactManagementModel.


Now you can use the stored procedure in code.

using ContactManagementModel;public partial class _Default : System.Web.UI.Page
{ ContactManagementEntities context = new ContactManagementEntities();
protected void Page_Load(object sender, EventArgs e)

{
if (!IsPostBack)
{

ddlGroups.DataSource = context.ContactGroups.ToList();
ddlGroups.DataTextField = "GroupName";

    ddlGroups.DataValueField = "GroupId";
DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

{ int intGroupId = Int32.Parse(ddlGroups.SelectedValue.ToString());

var Contact = from p in context.spGetContactsByGroup(intGroupId)
select new { p.ContactName, p.Email };

GridView1.DataSource = Contact.ToList();
DataBind();

}



Top

Saturday, December 4, 2010

Entity Framework Model First

With Entity Framework it is possible to develop a model first and then derive at a database.

In the Entity Data Mode Wizard select Empty Model.





This action will instantiate the Entity Model Designer with its associated toolbox which contains options for creating Entity, Association and Inheritance.

For creating an Entity double click on Entity from the toolbox.

We are in the process of creating a many to many relationship. I am going to take Marriage Hobbyist as the sample. Here I am going to track the marriages of Marriage Hobbyists like Elizabeth Taylor, Richard Burton, Tom Cruise, Sasi Taroor, etc. I am creating two Entities Gentleman and Lady. The association here is Many to Many.  Here a Entity called Elizabeth Taylor have multiple marriages with Richard Burton, Conrad Hilton, etc. And Richard Burton in turn have multiple marriages with Elizabeth Taylor, etc.






















..




















..




















By default the association is One to Many Instead I am selecting *(Many) from the Multiplicity attribute of Gentleman Entity.




















In effect a  Many to Many Association between Gentleman and Lady as shown in the diagram.
























You are expected to create a database as shown below. Once you have done that you can select Generate Database from Model by right clicking on the Model Designer surface.




















..




















You can see the database Script generated for you.




















Here is the output of running the script and opening the table in Database Diagram. Here you can see Gentleman, Lady as well as the junction table GentlemanLady.






















Now you can use the Asp .Net Dynamic Data Project for easily creating a Project for MarriageHobbyists.

Asp .Net Dynamic Data




Asp .Net Dynamic Data is a technology used for dynamically generating CRUD forms. It is based on either Entity Framework or Linq to Sql.

Here I am demonstrating Ado .Net Dynamic Data with Entity Framework.

Start a New Web Site in Asp .Net and select Asp .Net Dynamic Entities Web Site.




Add and Ado .Net Entity Data Model as described in the beginning of the blog.



Open Global.asax and navigate to RegisterRoutes event. Uncomment the DefaultModel.RegisterContext and inside the typeof type the name of the Ado .Net Entities you have created and set ScaffoldAllTables attribute to true as shown below.







DefaultModel.RegisterContext(typeof(ContactManagementModel.ContactManagementEntities),
new ContextConfiguration() { ScaffoldAllTables = true });



Wednesday, December 1, 2010

User Group Meeting - 11th Dec 2010 - Kochi

Venue: Mastermind Computer Institute, 2nd Floor,
New Kochappilly Building,
Professional WCF 4: Windows Communication Foundation with .NET 4 (Wrox Programmer to Programmer)Near Federal Bank,
Civil Line Road,
Chembumukku,Cochin-682030

Agenda                                                                           

09:30 - 09:40 Community updates
09:40 - 10:30 Introduction to WCF
10:30 - 11:15 Lambda - It's uses and abuses
11:15 - 11:30 Tea Break (15 min)
11:30 - 12:15 Introducing Razor – A new view engine for ASP.NET
12.15 - 01:00 Memory and Resource Leaks in .NET application

Click Here to Register

Further enquiries : 9745800512

Wednesday, November 10, 2010

Kerala Microsoft Users Group Session in Kochi on 13th Nov

* Windows Phone 7
* Windows Communication Foundation 4.0
* Microsoft Surface
* Test Driven Development

Venue
Mastermind Computer Institute,
2nd Floor, New Kochappilly Building,
Near Federal Bank, Civil Line Road,
Chembumukku, Cochin-682030

For online registration, please visit K-MUG web site (http://k-mug.org)
K-MUG sessions are FREE, but the entry pass is mandatory. All questions can be posted to K-MUG discussion forum or contact the administrator at admin@k-mug.org
Event details can located here http://k-mug.org/content/Sessions.aspx

Sunday, October 10, 2010

Sharepoint Productivity Tour 2010

How to Do Everything Microsoft SharePoint 20106th - 20 October
Mumbia, Chennai, Hydrabad, Bangalore, Trivandrum

Learn about the new features in SharePoint 2010.

Saturday, October 9, 2010

Community Tech Day - 23rd Oct 2010 - Kochi

IMA House, J. N. International Stadium Road,Palarivattom P.O., Cochin 682025, Kerala

09:15 - 09:30 Welcome and Community Update by Sreejumon & Vinod09:30 - 10:00 Plunge into Mono by Praseed
Pro Telerik ASP.NET and Silverlight Controls (Pro Series)10:00 - 11:00 Telerik Productivity Tools by Raj
11:00 - 11:15 Tea Break (15 min)11.15 - 12:15 T-SQL Tips and Tricks with SQL Server by Vinod
12.15 - 01:00 Entity Framework 4 by Shalvin
01:00 - 01:45 Lunch Break (45 min)01.45 - 02:45 Security Auditing and Accountability under Windows 2008 by Manu
02:45 - 03:30 NoSQL databases in .NET Apps by Shiju
03:30 - 03:45 Tea Break (15 min)
03:45 - 04:30 Generics - A Revisit by Yanesh
04:30 - 05:15 .NET Serialization And XML by Praseed
05.15 - 05:30 Closing Ceremony

Details

Register

Community Tech Days

Wednesday, August 25, 2010

Entity Framework 4

Entity Framewok 4 is a Object Relation Mapping Tool chain from Microsoft.
In fact it is much more than an ORM tool. It is going to be the future of Microsoft Data Access Technology. With Entity Framework in place programmers need not worry about database, tables, relations, Stored Procedure Name parameters and the like. Instead you work with a conceptual model that reflects your business objects just like working with objects in memory.Pro Entity Framework 4.0

Windows Forms Data Binding

Asp .Net and SaveChanges Method


WPF

Stored Procedure in Entity Framework

Asp .Net Dynamic Data


Contact Management System Table Structure
To make things simple I am using just two tables Contact Groups and Contacts.


create table ContactGroups(GroupId int identity(1,1) primary key,
GroupName varchar(40))

create table Contacts (ContactId int primary key identity(1,1) ,
GroupId int references ContactGroups(GroupId), ContactName varchar(40),
Phone varchar(15), Email varchar(40))



Entity Data Model(EDM)
Entity Data Model is the bridge between the database and the conceptual model.
The EDM is represented by a single XML document at design time which will be split into three sections at run time representing Conceptual (CSDL - Conceptual Schema Definition Language), Storage (SSDL - Storage Schema Definition Language) and Mapping Layers (MDL- Mapping Definition Language).

First lets see how to create an Entity Data Model.
Entity Framework 4 requires .Net 4. I am starting an Empty Asp .Net Project.




















In the Add New Item Dialog I am selecting ADO .NET Entity Data Model.





















The screen asks us whether to start by Generating from Database or start with an empty model.
Lets start with Generating from Database.

Entity Framework also support Domain Driven development that well will take up on another blog.



In the Choose your Data Connection Screen you can select the database to work with. I am select ContactManagement database a simple database with just two table.
At the bottom of the wizard is the Entity Container Class which follows a naming pattern like Entities. So in our case it is ContactMangementEntities.




















The next screen list all the database object. I am selecting just one table to make things simple.

Bottom of the screen are two new features. Select both the options.



















Now you are receiving the designer. Individual items in an EDM are called Entities. In our example there is only one entity.

Add a GridView on the the form. From the Smart Tag of GridView select New Data Source from Choose Data Source option.
From the Choose Data Source Type select Entity. Click Next. From the Named Connection select ContactManagementEntities. Click Next. Select ContactGroup from EntitySetName. Since we have added only one Entity you will see just ContactGroup in the combo box. Click finish and you can see the GridView filled with data.


Windows Forms Data Binding
In the previous example we saw working with wizards. In this section we are going to make our hands dirty by writing some code. As in the previous example here too I am creating a Entity Data Model.






































Now go to Data Menu and select Show Data Sources which will show the Data Sources window. Click on the first icon in the Data Sources window, ie. the Add New Data Source icon. This will invoke Data Source Configuration Wizard. Select Object and proceed with the wizard.
This wizard will create an Object Data Source.
Drag the ContactGroup on to the form. Visual Studio will create the form for you with button for CRUD operations.

Add the following following code to the load event of the form.


private void Form1_Load(object sender, EventArgs e)
{
ContactManagementEntities con = new ContactManagementEntities();Programming Entity Framework: Building Data Centric Apps with the ADO.NET Entity Framework
var Grps = from p in con.ContactGroups
select p;
contactGroupBindingSource.DataSource = Grps;
}



















Windows Forms ComboBox Grid Lookup


ContactManagementEntities cont = new ContactManagementEntities();
List<ContactGroup> Grps;
List<Contact> Contacts;

bool flag = false;
private void ComboOneToMany_Load(object sender, EventArgs e)
{
Grps = cont.ContactGroups.ToList();

Contacts = cont.Contacts.ToList();


FillCombos();
flag = true;
}

private void FillCombos()
{

cboGroups.DisplayMember = "GroupName";
cboGroups.DataSource = Grps;
cboGroups.ValueMember = "GroupId";
}

private void cboGroups_SelectedIndexChanged(object sender, EventArgs e)
{
if (flag == true)
{
MessageBox.Show(cboGroups.SelectedValue.ToString());
int intGroupId = Int32.Parse(cboGroups.SelectedValue.ToString());
var Conts = from p in cont.Contacts
where p.GroupId == intGroupId
select new { p.ContactName };
dataGridView1.DataSource = Conts;
}



















Joins
int intGroupId = Int32.Parse(cboGroups.SelectedValue.ToString());
var Contacts = from p in con.ContactGroups
join c in con.Contacts on p.GroupId equals c.GroupId
where p.GroupId == intGroupId
orderby p.GroupName;
dataGridView1.DataSource = Conts;



Asp .net


ContactManagementModel.ContactManagementEntities con;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnAdd_Click(object sender, EventArgs e)
{
con = new ContactManagementModel.ContactManagementEntities();
var Grp = new ContactManagementModel.ContactGroup { GroupName = txtGroup.Text };
con.AddToContactGroups(Grp);
con.SaveChanges();
txtGroup.Text = "";
txtGroup.Focus();
Response.Write("Record Saved");
}



Top












Delete Record using DeleteObject Method

ContactManagementModel.ContactManagementEntities context = new ContactManagementModel.ContactManagementEntities();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlGroups.DataSource = context.ContactGroups;
ddlGroups.DataTextField = "GroupName";
ddlGroups.DataValueField = "GroupId";
DataBind();
ddlGroups.Items.Add("");
ddlGroups.SelectedValue = "";
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{


}
protected void btnDelete_Click(object sender, EventArgs e)
{
int intGroupId = Int32.Parse(ddlGroups.SelectedValue.ToString());
var Grp = context.ContactGroups.Where(p => p.GroupId == intGroupId).First();
context.DeleteObject(Grp);
context.SaveChanges();
Response.Write("Record Deleted");
}

Updating Records
private void btnUpdate_Click(object sender, EventArgs e)
{
int intGroupId = Int32.Parse(cboGroup.SelectedValue.ToString());

var Grp =
context.ContactGroups.Where(p => p.GroupId == intGroupId).First();

Grp.GroupName = txtGroupName.Text;
context.SaveChanges();
MessageBox.Show("Record Updated");
}

WPF
 <Grid>
<TabControl Height="279" HorizontalAlignment="Left" Margin="20,20,0,0" Name="tabControl1" VerticalAlignment="Top" Width="471">
<TabItem Header="Groups" Name="tabItem1">
<Grid>
<TabControl Height="172" HorizontalAlignment="Left" Margin="25,19,0,0" Name="tabControl2" VerticalAlignment="Top" Width="350">
<TabItem Header="Insert" Name="tabItem2">
<Grid />
</TabItem>
<TabItem Header="Show">
<Grid>
<DataGrid AutoGenerateColumns="True" Height="100" HorizontalAlignment="Left" Margin="18,20,0,0" Name="dgdGroups" VerticalAlignment="Top" Width="246" />
</Grid>
</TabItem>
</TabControl>
</Grid>
</TabItem>
<TabItem Header="Contacts">
<Grid>
<TabControl Height="205" HorizontalAlignment="Left" Margin="28,22,0,0" Name="tabControl3" VerticalAlignment="Top" Width="341">
<TabItem Header="Insert" Name="tabItem3">
<Grid />
</TabItem>
<TabItem Header="Lookup">
<Grid>
<ComboBox Height="23" HorizontalAlignment="Left" Margin="114,21,0,0" Name="cboGroup" VerticalAlignment="Top" Width="120" />
<DataGrid AutoGenerateColumns="True" Height="113" HorizontalAlignment="Left" Margin="41,50,0,0" Name="dgdContacts" VerticalAlignment="Top" Width="237" />
</Grid>
</TabItem>
</TabControl>
</Grid>
</TabItem>
</TabControl>
</Grid>


  ContactManagementEntities context = new ContactManagementEntities();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var Grp = from p in context.ContactGroups
select new { p.GroupId, p.GroupName };
dgdGroups.ItemsSource = Grp;
cboGroup.ItemsSource = Grp;
cboGroup.DisplayMemberPath = "GroupName";
cboGroup.SelectedValuePath = "GroupId";
}

private void cboGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

int intGrp = Int32.Parse(cboGroup.SelectedValue.ToString());

var Contacts = from p in context.Contacts
where p.GroupId == intGrp
select new { p.ContactName, p.Email };

dgdContacts.ItemsSource = Contacts;
}

Max

ContactManagementEntities context = new ContactManagementEntities();
private void btnInsert_Click(object sender, RoutedEventArgs e)
{
  try
  {
      var intGroupId = (from p in context.ContactGroups
                                  select p.GroupId).Max();

      intGroupId++;

      var Grp = new ContactGroup { GroupId = intGroupId, GroupName = txtGroupName.Text };
     context.AddToContactGroups(Grp);

    context.SaveChanges();
    MessageBox.Show("Record Saved");
  }
  catch (Exception ex)
  {
       MessageBox.Show(ex.ToString());
  }
     
 }

Related Blog

Entity Framework Model First

Entity Framework and Stored Procedures

 

Thursday, August 19, 2010

DevCon 2010 at Trivandrum

Real World Functional Programming: With Examples in F# and C#Venue : ParkCenter, Technopark, Trivandrum, Kerala, India

Day 2 (4th Sept- Saturday)
08:30AM – 09:30AM – Registration Confirmation
09:30AM – 10:30AM – Functional programing with F#
10:30AM – 11:30AM – Power Shell – Your Wish is my Command
11:30AM – 11:45AM – Tea Break
11:45AM – 12:30PM – Visual Studio 2010 tips
12:30PM – 01:15PM – ASP.NET MVC2
01:15PM – 02:00PM – Lunch
02:00PM – 02:45PM – Great Developer Contest – Final
02:45PM – 03:45PM – Office Addins with Visual Studio 2010
03:45PM – 04:30PM – Entity Framework 4
04:30PM – 05:00PM – Closing Ceremony
Details

I am taking a session on Entity Framework 4.

Saturday, July 10, 2010

Implicitly Typed Array C#

C# 4.0 in a Nutshell: The Definitive Reference
Implicitly typed array is a feature introduced with C# 3.0

that allows compiler to deduce the type of array.


private void Window_Loaded(object sender, RoutedEventArgs e)
{
//1. An implicitly typed array of string
var friends = new[] { "Praseed", "Biju" };
MessageBox.Show(friends.GetType().ToString());

//2.  An implicitly typed array
var points = new[] { 90, 95, 966 };
MessageBox.Show (points.GetType().ToString());


//3. An array of doubles
var price = new[] { 10.40, 10, 60 };
MessageBox.Show (price.GetType().ToString());
}


In this example instead of I giving a type to the arrays

I am expecting the compiler to deduce the type. Compiler no doubt is a smarter guy than me.

The first two examples are self explanatory in nature.

The first example will produce an output of System.String[].

Second example will produce and output of System.Int32[].

In the third case where I am providing multiple types, the compiler will deduce the type that all other given types can be conveted to. In this case it will be producing an array of double.

Tuesday, June 29, 2010

DevCon 2010, Trivandrum

Programming Windows Azure: Programming the Microsoft CloudThe event for software professionals who want to get ahead and stay ahead.

When
03 (Saturday) and 04 (Sunday) – July – 2010
Where
ParkCenter, Technopark, Trivandrum, Kerala, India
Register
Register for DevCon 2010 in Trivandrum, India  on Eventbrite

http://k-mug.org/events/devcon2010/

Sessions

DevCon 2010 – 3rd and 4th July at ParkCenter, Technopark, Trivandrum
Day 1 (3rd July – Saturday)
08:30AM – 09:15AM – Registration Confirmation
09:15AM – 09:30AM – Welcome Speech
09:30AM – 10:15AM – Key Note Session – “Cloud – The Meta Platform”
10:15AM – 11:00AM – New features in .NET 4.0 & Visual Studio 2010
11:00AM – 11:15AM – Tea break
11:15AM – 12:15PM – Robotics Programming
12:15PM – 01:15PM – Web Security and Security Auditing
01:15PM – 02:15PM – Lunch
02:15PM – 03:15PM – Windows Azure
03:15PM – 04:00PM – Great Developer Contest – Final
04:00PM – 05:00PM – Managing Application Compatibility in Windows 7
Day 2 (4th July – Sunday)
08:30AM – 09:30AM – Registration Confirmation
09:30AM – 10:30AM – Data on the Cloud
10:30AM – 11:30AM – Mixed Mode Windows development using C# and C++
11:30AM – 11:45AM – Tea Break
11:45AM – 12:00PM – Visual Studio 2010 tips
12:30PM – 01:30PM – Tuning Tools in SQL Server 2008
01:30PM – 02:30PM – Lunch
02:30PM – 03:15PM – ASP.NET MVC2
03:15PM – 04:00PM – Windows 7 Phone
04:00PM – 05:00PM – Closing Ceremony

Wednesday, May 26, 2010

Asp .Net Web Site Project in Asp .Net 4

Pro ASP.NET 4 in C# 2010, Fourth EditionAsp .Net Web Web Site Project in Asp .Net 4 is an excellent starting point for a new project. It comes packed with Membership, Master Page, Style Sheet etc.














Lets explore the contents of a project. The Accounts folder contains the Membership related forms. Most important being Login.aspx and Register.aspx. Forms Authentication is enabled by default.


In the Styles Folder there is Site.css.


Site.master is the Master Page.


First Let me take Site.master. I am editing the heading 'My ASP.NET Application' to 'Shalvin Content Mangement System' which is an H1.


Now I am selecting Default.aspx. I am editing the existing contents of the page to suit my project.
















Clicking on the Login link at the right side of the page will take you to the Login page.















There is an option for Registering as a new user.