Friday, February 03, 2012

What will you be if computers weren't in existence?

Yeah it's a tough question especially since most of us across the globe, both young and old heavily rely on computers and the internet . Today, life would be virtually impossible without it. When I was in elementary school I always dreamed of becoming an artist. I loved to paint and draw because I can express my thoughts and emotions through art. But things changed after I graduated  in high school because my family couldn't afford to send me to university. I earned my BS degree because I got a scholarship from STI to study computer science. So now I work as a web developer. But to answer the question, if computers didn't exist then I would be a carpenter and a farmer then I would create a machine from wood that will compile codes made out of paper that will produce kernels of corn ~ just kidding on that part =D. Seriously I would definitely be an architect or an artist because being an artist is having the freedom to express your personality through art. The picture below is one of my drawings which I’ve drawn a long long time ago. Not pretty cool but it rocks! :D

mydrawing

How about you? What do you think will you be doing now if computers weren't in existence?

 

Technorati Tags: ,

Wednesday, February 01, 2012

Finally! ProudMonkey Controls is out on CodePlex!

I've been receiving requests for the source code of my MessageBox controls for ASP.NET and so I've decided to upload my project in CodePlex so everyone can use it. You can check and download the controls here: http://proudmonkeycontrols.codeplex.com/

Feel free to visit my project page and provide your valuable feedback!

Thanks!

Using ProudMonkey ConfirmBox Control in GridView

There are times that we need to prompt the users when doing certain actions on the page. One practical example is to confirm the user when deleting a certain record just like what I have demonstrated awhile back about Displaying a Confirmation Message on GridView Deleting. If you noticed on that demo I simply use plain JavaScript to display the confirmation message. In this post I’m going to demonstrate how to use the ConfirmBox control in delete scenario.

Note that just for the simplicity of this demo I’m just going to create a dummy data as the DataSource for the GridView. If you are working with live data from database then you may want to check these previous articles about:

To get started let’s go ahead and set up the UI (HTML mark-up). For simplicity I set up the mark-up like this:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master"
                  AutoEventWireup="true" 
                  CodeBehind="GridView.aspx.cs"
                  Inherits="WebAppDemo.GridView" %>
<%@ Register Assembly="AjaxControlToolkit" 
             Namespace="AjaxControlToolkit" 
             TagPrefix="asp" %>
<%@ Register assembly="ProudMonkey.Common.Controls"
             namespace="ProudMonkey.Common.Controls" 
             tagprefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" >
    </asp:ToolkitScriptManager>
    <cc1:ConfirmBox ID="ConfirmBox1" runat="server" />
    <asp:Label ID="lblMessageDisplay" runat="server" ForeColor="Green" />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
        <Columns>
                <asp:BoundField DataField="ID" />
                <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
                <asp:TemplateField>
                <ItemTemplate>
                    <asp:TextBox ID="txtPrice" runat="server" Text='<%# Eval("Price") %>' />
                </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                <ItemTemplate>
                    <asp:TextBox ID="txtAmount" runat="server" Text='<%# Eval("Amount") %>' />
                </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button ID="btnDelete" runat="server" 
                                Text="Delete" 
                                OnClientClick="ShowConfirmBox(this,'Are you sure?');return false;" 
                                onclick="BtnDelete_Click" /> 
                </ItemTemplate>
                </asp:TemplateField>
        </Columns>
    </asp:GridView>
</asp:Content>

 

Obviously the page above make use of MasterPage and basically contains the ToolScriptManager, ConfirmBox, Label and GridView. The ToolScriptManager is necessary since the ConfirmBox control uses the ASP.NET Ajax Modal popup control. The Label is just for displaying the message and the GridView is for displaying the data.

Here’s the whole code behind part of the demo:

using System;
using System.Web.UI.WebControls;
using System.Data;

namespace WebAppDemo {
    public partial class GridView : System.Web.UI.Page {

        private DataTable GetSampleData() {

            //NOTE: THIS IS JUST FOR DEMO
            //If you are working with database
            //You can query your actual data and fill it to the DataTable
            DataTable dt = new DataTable();
            DataRow dr = null;

            //Create DataTable columns
            dt.Columns.Add(new DataColumn("ID", typeof(string)));
            dt.Columns.Add(new DataColumn("ProductName", typeof(string)));
            dt.Columns.Add(new DataColumn("Price", typeof(string)));
            dt.Columns.Add(new DataColumn("Amount", typeof(string)));

            //Create Row for each columns
            dr = dt.NewRow();
            dr["ID"] = 1;
            dr["ProductName"] = "Proudct 1";
            dr["Price"] = "100";
            dr["Amount"] = "10";

            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["ID"] = 2;
            dr["ProductName"] = "Product 2";
            dr["Price"] = "200";
            dr["Amount"] = "2";

            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["ID"] = 3;
            dr["ProductName"] = "Product 3";
            dr["Price"] = "50";
            dr["Amount"] = "10";

            dt.Rows.Add(dr);
            return dt;
        }
        

        private void BindGrid(DataTable source) {
            GridView1.DataSource = source;
            GridView1.DataBind();
        }

        private DataTable UpdateTable(DataTable source, int rowIndex) {
            for (int i = 0; i < GridView1.Rows.Count; i++) {
                TextBox tb1 = (TextBox)GridView1.Rows[i].Cells[2].FindControl("txtPrice");
                TextBox tb2 = (TextBox)GridView1.Rows[i].Cells[3].FindControl("txtAmount");
                source.Rows[i]["Price"] = tb1.Text;
                source.Rows[i]["Amount"] = tb2.Text;
            }
            source.Rows.RemoveAt(rowIndex);
            return source;
        }

        protected void Page_Load(object sender, EventArgs e) {
            if (!IsPostBack) {
                ViewState["COPY"] = GetSampleData();
                BindGrid(GetSampleData());
            }
        }

        protected void BtnDelete_Click(object sender, EventArgs e) {
            if (ViewState["COPY"] != null) {
                DataTable dt = (DataTable)ViewState["COPY"];
                Button btnDelete = (Button)sender;
                GridViewRow gvRow = (GridViewRow)btnDelete.NamingContainer;
                BindGrid(UpdateTable(dt, gvRow.RowIndex));

                lblMessageDisplay.Text = "Record deleted!";
            }
        }
    }
}

 

Since I didn’t use database for storing the data you may notice that I use ViewState to store the data across postbacks as you see in Page_Load event. The UpdateTable() method is responsible for handling the deletion. You may also notice that before the row is being removed it updates first the data, this is to ensure that the data on the TextBox are retained on postbacks.

Here’s the page output when you run the code.

Initial load

pm1

After clicking the Delete button

pm2

After clicking the YES button

pm3 

 

Enjoy!!!

Technorati Tags: ,

Wednesday, January 25, 2012

Closing my Blog at CodeASP.Net

I will be closing my blog (http://codeasp.net/blogs/Vinz) to avoid cross posting of contents and traffic. This means that I will not be posting there anymore. But please note that by stop blogging there doesn't mean I will stop contributing to the codeasp.net community, of course I will still be moderating posts and participating in the forums and try my best to answer to questions to the best that I can and whenever time permits. See you guys there!!! =}

I've recently updated the look and feel of this blog and updated each content to make it more readable and clean. I hope you like it.

Tuesday, January 24, 2012

ProudMonkey Controls will be in CodePlex soon

I will be hosting this project in http://www.codeplex.com/ as open source project. I’m working on it so stay tuned! =}

Thursday, January 12, 2012

Using MessageBox Control Outside UpdatePanel Control

Few days ago I wrote a simple demo about “Using ProudMonkey Controls with ASP.NET AJAX Update Panel”. One small problem is that if for some reasons you will place the MessageBox control outside UpdatePanel then you’ll notice that the MessageBox will not display properly in the page.

So if you were setting your html mark-up like this:

<%@ Register Assembly="AjaxControlToolkit" 
             Namespace="AjaxControlToolkit" 
             TagPrefix="asp" %>
<%@ Register Assembly="ProudMonkey.Common.Controls"
             Namespace="ProudMonkey.Common.Controls"
             Tagprefix="cc1" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <cc1:MessageBox ID="MessageBox1" runat="server"  />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Button ID="Button1" runat="server"
                            onclick="Button1_Click"
                             Text="Show Message" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

 

And calling the MessageBox at Button click event:

protected void Button1_Click(object sender, EventArgs e){
      MessageBox1.ShowError("Test ERROR Message!");
} 

 

You will end up getting something like this in the page:

 

m1

 

The reason why it happened because when you do a PostBack some of the attributes defined within MessageBox will not be loaded properly (e.g the src and style). To resolved the issue we can set up Triggers in the UpdatePanel to do postback. Here’s the sample demo below for your reference:

ASPX:

<%@ Register Assembly="AjaxControlToolkit"
             Namespace="AjaxControlToolkit" 
             TagPrefix="asp" %>
<%@ Register Assembly="ProudMonkey.Common.Controls"
             Namespace="ProudMonkey.Common.Controls"
             Tagprefix="cc1" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" >
        </asp:ToolkitScriptManager>
        <cc1:MessageBox ID="MessageBox1" runat="server"  />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Button ID="Button1" runat="server"
                            onclick="Button1_Click"
                            Text="Show Message" />
            </ContentTemplate>
           <Triggers>
                <asp:PostBackTrigger ControlID="Button1" />
            </Triggers>
        </asp:UpdatePanel> 
    </form>
</body>
</html>

Code Behind:

protected void Button1_Click(object sender, EventArgs e){
     MessageBox1.ShowError("Test ERROR Message!");
}  

 

Running the page will display the MessageBox properly. Here’s a sample screen shot below:

m2

That’s it! I hope someone find this post useful.

Wednesday, January 11, 2012

Show Large Image on Mouseover with jQuery

I’ve been seeing many members in the forums asking how to display a large copy of the image on mouseover. Some of them are displaying the image in a Repeater, GridView or DataList control. I didn’t find any direct solution that shows the scenario they wanted so I thought of writing this post to demonstrate how to go about it. I know there are lot of ways of doing/implementing a solution for this scenario and this is just one them. In this example I’m going to use the DataList control for displaying the data along with the images.

To get started let’s go a head and set-up the HTML mark-up. Just for the simplicity of this demo, I’ve just set up the mark-up this way:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <asp:DataList ID="DataList1" runat="server" RepeatColumns="2" RepeatDirection="Vertical">
        <ItemTemplate>
                <table>
                    <tr>
                        <td><asp:Image ID="imgProduct" runat="server" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "ProductImage") %>' style="width:100px; height:100px;" /></td>
                        <td> 
                            <asp:Label ID="lblProduct" Text='<%# DataBinder.Eval(Container.DataItem, "ProductName") %>' runat="server" />
                            <br />
                            <asp:Label ID="lblPrice" Text='<%# DataBinder.Eval(Container.DataItem, "Price") %>' runat="server" />
                            <br />
                            <asp:TextBox ID="txtQty" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                </table>
        </ItemTemplate>
</asp:DataList>
</asp:Content>

 

As you can see there’s really no fancy about the mark-up above. It just contain a DataList control with Image, TextBox and Label controls defined within it. You also notice that each control are binded with the fields that we want to display. Now let’s go ahead and populate the DataList with a sample data. Here’s the code behind part below:

using System;
using System.Data;

namespace WebAppDemo {
    public partial class Repeater : System.Web.UI.Page {

        private DataTable GetSampleData() {

            //NOTE: THIS IS JUST FOR DEMO
            //If you are working with database
            //You can query your actual data and fill it to the DataTable

            DataTable dt = new DataTable();
            DataRow dr = null;

            //Create DataTable columns
            dt.Columns.Add(new DataColumn("ID", typeof(string)));
            dt.Columns.Add(new DataColumn("ProductImage", typeof(string)));
            dt.Columns.Add(new DataColumn("ProductName", typeof(string)));
            dt.Columns.Add(new DataColumn("Price", typeof(string)));

            //Create Row for each columns
            dr = dt.NewRow();
            dr["ID"] = 1;
            dr["ProductName"] = "Product 1";
            dr["ProductImage"] = "~/Images/Image1.jpg";
            dr["Price"] = "100";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["ID"] = 2;
            dr["ProductName"] = "Product 2";
            dr["ProductImage"] = "~/Images/Image2.jpg";
            dr["Price"] = "200";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["ID"] = 3;
            dr["ProductName"] = "Product 3";
            dr["ProductImage"] = "~/Images/Image3.jpg";
            dr["Price"] = "50";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["ID"] = 3;
            dr["ProductName"] = "Product 4";
            dr["ProductImage"] = "~/Images/Image4.jpg";
            dr["Price"] = "500";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["ID"] = 3;
            dr["ProductName"] = "Product 5";
            dr["ProductImage"] = "~/Images/Image5.jpg";
            dr["Price"] = "70";
            dt.Rows.Add(dr);

            return dt;
        }

        protected void Page_Load(object sender, EventArgs e) {
            if (!IsPostBack) {
                DataList1.DataSource = GetSampleData();
                DataList1.DataBind();
            }
        }       
    }
}

 

Running the code will display something like this in the page:

datalist0

Now that we already have our data in placed let’s proceed implementing the mouseover functionality with jQuery. To start using jQuery then register the following script at the very top of the <head> section of the page or if you are using master page then add it the very top of  the content head section.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>

As you can see I'm using Google AJAX API CDN to host the jQuery file for some reasons. You can also download the jQuery here and host it in your server if you'd like. Now add the following mark-up at the top your DataList.

    <span id="coord"></span>
    <div id="divImageDisplay" style="position:absolute;">   
    </div>

The divImageDisplay is where we display the large copy of the Image when we hover on each image from the DataList. We will then display the coordinate values in the label to see the top and left value. Okay here's the full script below for the mouseover functionality:

<script type="text/javascript">
        function getTop(e) {
            var offset = e.offsetTop;
            if (e.offsetParent != null) offset += getTop(e.offsetParent);
            return offset;
        }
        function getLeft(e) {
            var offset = e.offsetLeft;
            if (e.offsetParent != null) offset += getLeft(e.offsetParent);
            return offset;
        }
        function hideDivImageDisplay() {
            $('#divImageDisplay').html();
        }

        function showDivImageDisplay(img) {
            var grid = $('#<%=DataList1.ClientID %>');
            var leftPos = getLeft(img) + 80;
            var topPos = getTop(img) + 20;
            $('#divImageDisplay').offset({ top: topPos, left: leftPos })
            $('#divImageDisplay').html("<img src='" + img.src + "' width='300px' height='300px'/>");

            //print the coordinates
            $('#coord').text('Image ID: ' + img.id + ' left: ' + leftPos + ' top: ' + topPos);
        }
  
</script>

 

The getTop() function gets the top position coordinate value of the hovered image. The  getLeft() function gets the left position coordinate value. The hideDivImageDisplay() function will hide the div by clearing out the elements within it using the .html() jQuery function. The showDivImageDisplay() function is where we set the position of the divImageDisplay to display below each image from the DataList.

Now let’s put it all together. Here’s the full ASPX mark-up below:

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">

<script type="text/javascript">
        function getTop(e) {
            var offset = e.offsetTop;
            if (e.offsetParent != null) offset += getTop(e.offsetParent);
            return offset;
        }
        function getLeft(e) {
            var offset = e.offsetLeft;
            if (e.offsetParent != null) offset += getLeft(e.offsetParent);
            return offset;
        }
        function hideDivImageDisplay() {
            $('#divImageDisplay').html();
        }

        function showDivImageDisplay(img) {
            var grid = $('#<%=DataList1.ClientID %>');
            var leftPos = getLeft(img) + 80;
            var topPos = getTop(img) + 20;
            $('#divImageDisplay').offset({ top: topPos, left: leftPos })
            $('#divImageDisplay').html("<img src='" + img.src + "' width='300px' height='300px'/>");

            //print the coordinates
            $('#coord').text('Image ID: ' + img.id + ' left: ' + leftPos + ' top: ' + topPos);
        }
  
</script>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <span id="coord"></span>
    <div id="divImageDisplay" style="position:absolute;">   
    </div>

    <asp:DataList ID="DataList1" runat="server" RepeatColumns="2" RepeatDirection="Vertical">
        <ItemTemplate>
                <table>
                    <tr>
                        <td><asp:Image ID="imgProduct" runat="server" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "ProductImage") %>' style="width:100px; height:100px;" onmouseover="showDivImageDisplay(this);" onmouseout="hideDivImageDisplay();" /></td>
                        <td> 
                            <asp:Label ID="lblProduct" Text='<%# DataBinder.Eval(Container.DataItem, "ProductName") %>' runat="server" />
                            <br />
                            <asp:Label ID="lblPrice" Text='<%# DataBinder.Eval(Container.DataItem, "Price") %>' runat="server" />
                            <br />
                            <asp:TextBox ID="txtQty" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                </table>
        </ItemTemplate>
</asp:DataList>
</asp:Content>

Here’s the output below when running the page:

datalist

 

That’s it! I hope someone find this post useful!

Monday, January 09, 2012

ASP.NET MVC 3 - Editing and Updating the Form

This demo is a continuation of my previous article about "Creating a Simple Log-in Form". Basically in this post I'm going to demonstrate the basic on how to edit and update the form with ASP.NET MVC 3.

Before you go any further, I'd suggest you to check out my previous article first about "ASP.NET MVC 3: Creating a Simple Sign-Up Form" and "Creating a Simple Log-in Form".

STEP 1: Creating the Model class

Just for the simplicity of this demo, I'm just going to display the FirstName, LastName and ContactNumber in the form and have the user edit those information as they like. So first we'll add a new class under ViewModel's folder. To do this just right click on the "ViewModels" folder and then select Add -> then select class. In this example I'm going to name the class as "UserProfile" with the following properties below:

using System.ComponentModel.DataAnnotations; 

namespace MVCDemo.Models.ViewModels
{
    public class UserProfile
    {
        [Display(Name = "User Login ID")]
        public string UserLoginID { get; set; } 

        [Display(Name = "First Name")]
        public string FirstName { get; set; } 

        [Display(Name = "Last Name")]
        public string LastName { get; set; } 

        [Display(Name = "Contact Number")]
        public string ContactNumber { get; set; }
    }
}

 

As you can see there's nothing really fancy in the code above. It just contains four properties with the Display attribute decorated on each property.

STEP 2: Creating the View

The next step is to create a view under "Account" folder. To do this just right click on the folder -> select Add -> and then select View. A popup window should appear wherein you can type in the view name.

In this demo I'm just going to name the view as "MyProfile". Now select Razor (CSHTML) as the View engine then check the Create a strongly-type view checkbox. Under the model class drop down, select UserProfile class. Then under scaffold template select Edit. Click Add to generate the view and the pre-defined codes for you. Here's the code below with few modifications:

@model MVCDemo.Models.ViewModels.UserProfile

@{
    ViewBag.Title = "My Profile";
}

<h2>ViewPage1</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User Profile</legend>
        <br />
        <div style="color:Green">@ViewData["Status"]</div>
        <br />
        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ContactNumber)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ContactNumber)
            @Html.ValidationMessageFor(model => model.ContactNumber)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
@Html.ActionLink("Logout", "LogOff", "Account")
</div>

STEP 3: Adding the GetUserDetail() and the UpdateUserProfile() method in the UserManager class

Here's the code below:

public SysUser GetUserDetail(string loginID) { 
    var userDetails = from p in dre.SysUsers 
                      where p.SysUserLoginID == loginID 
                      select p; 

    return userDetails.ToList().FirstOrDefault(); 
} 

The code above gets the details of the user information from the database by passing in the loginID as the parameter to the query using LINQ syntax.

public void UpdateUserProfile(UserProfile userProfile) { 
     var user = (from p in dre.SysUsers 
                 where p.SysUserLoginID == userProfile.UserLoginID 
                 select p).FirstOrDefault(); 

        user.FirstName = userProfile.FirstName; 
        user.LastName = userProfile.LastName; 
        user.ContactNumber = userProfile.ContactNumber; 

        dre.SaveChanges(); 
} 

The method above takes UserProfile object as the parameter. It then query the database to get the specific user details based on the UserLoginID. It will then update the fields by assigning the new values from the UserProfile object and then save the changes. The UserProfile object is the object used in our strongly typed view "MyProfile".

STEP 4: Adding the MyProfile action methods in the AccountController()

Here's the block of code below:

[Authorize] 
public ActionResult MyProfile(string userLoginID) { 
       UserManager um = new UserManager(); 
       var userDetail = um.GetUserDetail(userLoginID); 

       UserProfile user = new UserProfile(); 
       user.UserLoginID = userDetail.SysUserLoginID; 
       user.FirstName = userDetail.FirstName; 
       user.LastName = userDetail.LastName; 
       user.ContactNumber = userDetail.ContactNumber; 

       return View(user); 
} 

What it does is it creates an instance of the UserManager class and then get the user details data by calling the GetUserDetail() method with the parameter from the UserManager object. We then populate the properties we defined in the UserProfile class that we have created in STEP 1 so that the View that we have created in STEP 2 will be populated with the result.

[HttpPost] 
[Authorize] 
public ActionResult MyProfile(UserProfile userProfile) { 

       UserManager um = new UserManager();9:34 PM 1/9/2012 
       um.UpdateUserProfile(userProfile); 

       ViewData["Status"] = "Update Sucessful!"; 

       return View(userProfile); 
} 

The method above is reponsible for saving the information to the database. This method will be called upon clicking the "Save" button. As you can see the method is decorated with [HttpPost] which means that the method can only be invoked during post request. The first line creates an instance of the UserManager object and the call the UpdateUserProfile method by passing the UserProfile object to it. The UserProfile object contains the updated data from the view and ready to be used to perform the update. We then use ViewData to store some status message to let the user know that the record is updated successfully in the database.

You also noticed that both methods are decorated with the [Authorize] attribute to essure that the method can only be invoked by authenticated users.

STEP 5: Adding a link to Edit Profile

In the Welcome page add the following line below.

@Html.ActionLink("Edit Profile", "MyProfile", "Account", new { userLoginID = Context.User.Identity.Name }, null) 

 

The first parameter sets the text of the link. The second parameter is the Action method (in this case we have the "MyProfile" action method). The third parameter is the controller name in which the action method belongs to (in this case we set the Account for AccountController. The fourth parameter is Route arguments, in this parameter we can pass values to our action method ( in this case we passed in the identity of the user who logged in). The last parameter is the html arguments. We set it to null/nothing so that the correct method will be called.

Here are some screen shots of the output.

After log-in

mvcpart3a

The MyProfile page

mvcpart3b

Editing the form

mvcpart3c

After updating the form

mvcpart3d

 

That’s it! I hope someone find this post useful!

Thursday, January 05, 2012

Using ProudMonkey Controls with ASP.NET AJAX Update Panel

Using the MessageBox, ConfirmBox and FrameBox controls within Update Panel control is very easy. Just like other asp standard controls, you can just put the controls that you want to use within Update Panel and your good to go. Here's a simple demo I wrote just for your reference.

 

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ProudMonkeyControlTEST.aspx.cs" Inherits="WebAppDemo.ProudMonkeyControlTEST" %>

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%@ Register assembly="ProudMonkey.Common.Controls" namespace="ProudMonkey.Common.Controls" tagprefix="cc1" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <cc1:MessageBox ID="MessageBox1" runat="server" />
            <cc1:ConfirmBox ID="ConfirmBox1" runat="server" />
            <cc1:FrameBox ID="FrameBox1" runat="server" />

            <asp:Button ID="Button1" runat="server" Text="ConfirmBox" OnClientClick="ShowConfirmBox(this,'Are you sure?');return false;" onclick="Button1_Click" /> 
            <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Show Message" />
            <asp:Button ID="Button3" runat="server" Text="Show my Blog" OnClientClick="ShowFrameBox('Vinz Blog','http://geekswithblogs.net/dotNETvinz/Default.aspx');return false;" />
        </ContentTemplate>
    </asp:UpdatePanel>
       
        
    </form>
</body>
</html>

 

CODE BEHIND:

using System;

namespace WebAppDemo
{
    public partial class ProudMonkeyControlTEST : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e){

        }

        protected void Button1_Click(object sender, EventArgs e) {
            MessageBox1.ShowInfo("You've just clicked Yes!");
        }

        protected void Button2_Click(object sender, EventArgs e){
            MessageBox1.ShowError("ERROR");
        }   
    }
}


That's it! I hope someone find this post useful!

Technorati Tags: ,

Friday, December 30, 2011

ASP.NET MVC 3 - Creating a Simple Log-In Form

This demo is a continuation of my previous article about "ASP.NET MVC 3: Creating a Simple Sign-Up Form" which I wrote few months ago. Basically in this post I'm going to demonstrate how to create a simple LogOn form in which users can supply their username and password. And how to authenticate and validate users in ASP.NET MVC 3.

I will not elaborate more in details about the model, view and controllers function so before you go any further, I'd suggest you to check my previous article first about "ASP.NET MVC 3: Creating a Simple Sign-Up Form" especially if you are new to MVC web development approach.

As a recap, here's the previous project structure below:

mvcpart2a

STEP 1: Creating a Model class

To get started let's go ahead and create a simple model class for our Log-in. To do this just right click on the "ViewModels" folder and then select Add -> then select class. In this example I'm going to name the class as "UserLogon" with the following properties below:

using System.ComponentModel.DataAnnotations;

namespace MVCDemo.Models.ViewModels
{
    public class UserLogon
    {
        [Required]
        [Display(Name = "User Login")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    }
} 

The fields defined above will be used in our Login form. You may also noticed that the fields are decorated with Required, Display and DataType attributes. These attributes are called Data Annotations.

STEP 2: Creating the View

Now right click on the "Account" folder and then select Add -> and then select View. A popup window should appear in which you can configure the view for the page. In this demo I'm going to name the view as "LogOn". Now select Razor (CSHTML) as the view engine then check the “Create a strongly-type view” checkbox. Under the model class drop down, select “UserLogOn” class. Then under scaffold template select Create. Take a look at screen shot below for a reference.

mvcpart2b

Click Add to generate the view and the pre-defined codes for you. Here's the generated markup below with some text modifications:

@model MVCDemo.Models.ViewModels.UserLogon 

@{ 
    ViewBag.Title = "Log On"; 
} 

<h2>LogOn</h2> 

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
    <fieldset> 
        <legend>User Logon</legend> 

        <div class="editor-label"> 
            @Html.LabelFor(model => model.UserLogIn) 
        </div> 
        <div class="editor-field"> 
            @Html.EditorFor(model => model.UserLogIn) 
            @Html.ValidationMessageFor(model => model.UserLogIn) 
        </div> 

        <div class="editor-label"> 
            @Html.LabelFor(model => model.Password) 
        </div> 
        <div class="editor-field"> 
            @Html.EditorFor(model => model.Password) 
            @Html.ValidationMessageFor(model => model.Password) 
        </div> 

        <p> 
            <input type="submit" value="Log On" /> 
        </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink("Return to Home page","Index", "Home") 
</div> 

 

Again as a recap, the mark-up above is a strongly-type view. This enables better compile-time checking of your code and richer IntelliSense in the Visual Studio editor. By including a @model statement at the top of the view template file, you can specify the type of object that the view expects. In this case it uses the MVCDemo.Models.ViewModels.UserLogon .

STEP 3: Adding the GetuserPassword() method

Under ObjectManager folder, add this method in UserManager class.

public string GetUserPassword(string userLogIn) { 
            var user = from o in dre.SysUsers where o.SysUserLoginID == userLogIn select o; 
            if (user.ToList().Count > 0) 
                return user.First().SysPassword; 
            else 
                return string.Empty; 
} 

 

The method above gets the user password from the database based on the user login provided by the user using LINQ query.

STEP 4: Adding the LogOn ActionResults in the AccountController

Add the following code below in the AccountController under "Controllers" folder.

        // GET: /Account/LogOn

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

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(UserLogon model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                UserManager userManager = new UserManager();
                string password = userManager.GetUserPassword(model.UserLogIn);

                if (string.IsNullOrEmpty(password))
                {

                    ModelState.AddModelError("", "The user login or password provided is incorrect.");
                }

                if (model.Password == password)
                {
                    FormsAuthentication.SetAuthCookie(model.UserLogIn, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Welcome", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

 

As you can see there are two methods above with the same name. The first "LogOn" method will return the LogOn.cshtml that we have just created in STEP 2. The second LogOn method is decorated with the "[HttpPost]" attribute which indicates that the overload of the "LogOn" method can only be invoked for POST requests.

The second method will be triggered once the Button "Log On" is fired. What it does is first it will check if the required fields are supplied so it checks for ModelState.IsValid condition.It will then create an instance of the UserManager class and call the GetUserPassword() method by passing the userLogIn value supplied by the user to get the password. If the password returns an empty string then it will display an error to the view. If the password supplied is equal to the password retrieved from the database then it will redirect the user the the Welcome page, otherwise display an error stating that the password supplied is invalid.

STEP 5: Implementing Log-Out functionality

The log-out code is pretty easy. Just add the following method below in the AccountController class.

// GET: /Account/LogOff 

public ActionResult LogOff() 
{ 
      FormsAuthentication.SignOut(); 

      return RedirectToAction("Index", "Home"); 
}

 

You can then add the following Logout ActionLink in the “Welcome” view.

@Html.ActionLink("Logout", "LogOff", "Account")

The Output

The Log-in page

mvcpart2c

Screen shot that shows the validation

mvcpart2d

After successful Log-on

mvcpart2e

That's it! I hope someone find this post useful!

Technorati Tags: ,