Saturday, February 19, 2011

Razor View Engine and Visual Studio

The inspiration for this blog on Razor was the Web Camp conducted by Microsoft Evangelists Nahas Mohammed  and Ramaprasanna Chellamuthu on February 18 at Kochi. We received great insight into Razor View Engine and Web Matrix.
A few of the audience were invited to the stage and it was more of an interactive Code camp.


I am using Visual Web Developer 2010, a free tool from Microsoft for developing Asp .Net Applications. All the examples will work in Visual Studio.  I have already installed Asp .Net MVC 3 in my machine.

Visual Studio 2010 / Visual Web Developer 2010 comes will Intellisense and debugging support for Razor. Unlike Asp .Net Web Forms in Razor the Visual Interface is defined using HTML.

I am starting an Empty Web Site and Adding an Empty Razor Page.







@{
    var strName = "";
    if(IsPost)
    {
        strName = "Hello welcome to Razor"
    }
    
}
<form method=post>
<p>
@strName
</p>
<input id="Submit1" type="submit" value="submit" />
</form>






Inside a block each statement should end with a semicolon. Inside html you can call the memory variable using @ symbol. There semicolon should not be present.

We are checking a form post using IsPost. On Clicking the Submit buttom a Form POST will occur after that the memory variable will be assigned the Hello message and that message will be dispayed.



Using can use Html Tab in the Toolbox to add Html tags to the form.


You can see that the auto completion feature is available.

@{
    var strName = "";
    if(IsPost)
    {
        strName = "Hello " + Request["txtName"];
    }
 }
<form method=post>
<p>
@strName
</p>
Name 
<input Name="txtName" type="text" />
<br />
<input id="Submit1" type="submit" value="submit" />
</form>



In the above example we extracting the value of textbox using Request.








@{
    var sum = 0;
    if(IsPost)
    {
        sum = Request["txtValue1"].AsInt() + Request["txtValue2"].AsInt();
           
    }
    
}

<form method =post>
<p>
@sum
</p>
Value 1<input Name = "txtValue1" type="text" />
</br>
Value 2<input Name = "txtValue2" type="text" />
</br>
<input id="Submit1" type="submit" value="submit" />
</form>

AsInt() is used to convert the value to Integer.



Session
//Session.cshtml
@{
    Session["Name"] =  "Shalvin"; 
}

<form method =post>
<a href = "@Href("Welcome")">Welcome</a>
</form>





//Welcome.cshtml
@{
var strName = "Hello " + Session["Name"];
}




@strName





Href method is used to create paths to resources like Web pages.
In the first page we are defining the session variable and in the second page we extracting the value of Session variable.


Entity Framework
I am creating an Entity Data Model is shown in the figure



@{
    var context = new ContactManagementModel.ContactManagementEntities();

    var Grps = context.ContactGroups;

    var gd = new WebGrid(Grps);
}

<html>
<body>
 @gd.GetHtml();
</body>
</html>






WebGrid helper can be used to display day is a tabular manner.





@{
    var context = new ContactManagementModel.ContactManagementEntities();
  var strMessage = "";
    if(IsPost)
    {
    var Grp = new ContactManagementModel.ContactGroup{GroupName = Request["txtGroupName"]};

    context.AddToContactGroups(Grp);
    context.SaveChanges();
    strMessage = "Record Saved";
    }
        
}

<form method = "post">
<p>
@strMessage
</p>
Group Name 
<input Name = "txtGroupName" type="text" />
</br>
    <input id="Submit1" type="submit" value="submit" />
</form>

Thursday, February 3, 2011

Microsoft Web Camps on February 18, Kochi

Venue : ABAD PLAZA
M.G Road, Cochin-682 035


09:00am - 10:00amREGISTRATION
10:00am - 10:30amOpening Keynote  -  Nahas Mohammed & Ramaprasanna Chellamuthu
10:30am - 11:30amIntroduction to WebMatrix - Nahas Mohammed
11:30am - 12:30pmForms and Data Access - Nahas Mohammed
12:30pm - 01:30pmLUNCH BREAK
01:30pm - 02:30pmHelpers and Publishing - Ramaprasanna Chellamuthu
02:30pm - 03:30pmDotNetNuke on WebMatrix - Ramaprasanna Chellamuthu
03:30pm - 04:00pmAudience Q&A and Closing Note - Nahas Mohammed & Ramaprasanna Chellamuthu

RSVP : 080-4089 7010,
+91-96636 82120

mswebcamps@end2end.in

Saturday, January 15, 2011

Asp .Net Mvc with Entity Framework










































































public ActionResult Index()
{
var Grp = context.ContactGroups;
return View(Grp);
}







//
// GET: /Home/Create

public ActionResult Create()
{
return View();
}

//
// POST: /Home/Create

[HttpPost]
public ActionResult Create(ContactGroup Grp)
{
if (ModelState.IsValid)
{
try
{
context.AddToContactGroups(Grp);
context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View(Grp);
}
}
else
{
return View(Grp);
}
}





//
// GET: /Home/Edit/5

public ActionResult Edit(int id)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);
return View(Grp);
}

//
// POST: /Home/Edit/5

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);

try
{
UpdateModel(Grp, collection.ToValueProvider());
context.SaveChanges();

return RedirectToAction("Index");
}
catch
{
return View();
}
}






//
// GET: /Home/Delete/5

public ActionResult Delete(int id)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);
return View(Grp);
}

//
// POST: /Home/Delete/5

[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
var Grp = context.ContactGroups.SingleOrDefault(x => x.GroupId == id);

try
{
context.DeleteObject(Grp);
context.SaveChanges();

return RedirectToAction("Index");
}
catch
{
return View();
}
}

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

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