Banner Ad

Friday, December 25, 2015

CRUD Operation - ASP.Net MVC with ADO.Net

By Francis   Posted at   6:58 AM   CRUD No comments
                                   
                                In this post, I’m going to discuss about the CRUD(Create, Read, Update and Delete) Operation in an ASP.Net MVC application by using raw ADO.Net. Most of the new learners, who started to learn MVC asked this frequently. That’s the main reason behind this tutorial.

Configuration:
For this particular application, I have used the below configuration:
1. Visual Studio 2015
2. SQL Server 2008
In order to keep my hand clean, I have used a simple table to do the CRUD operation.

Step 1:
Execute the below script on your DB

SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO

SET ANSI_PADDING ON 
GO

CREATE TABLE [dbo].[tblStudent]( 
    [student_id] [int] IDENTITY(1,1) NOT NULL, 
    [student_name] [varchar](50) NOT NULL, 
    [stduent_age] [int] NOT NULL, 
    [student_gender] [varchar](6) NOT NULL, 
CONSTRAINT [PK_tblStudent] PRIMARY KEY CLUSTERED 
( 
    [student_id] ASC 
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] 
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF 
GO


Step 2:
Create an “Empty” ASP.Net.MVC 4 application in Visual Studio 2015. Empty-MVC-Project

Step 3:
Add an “Empty” Controller by right clicking on the “Controller” folder select “Add” then select “Controller..”. In the popup select “MVC 5 Controller” then click “Add”. In the next popup you should give the name of the as “CRUDController”.
Add-Empty-Controller
After add the controller, you may noticed as per the “convention” in ASP.Net MVC under the “Views” folder, a new folder named “CRUD” also created.
Convention-Over-Configuration

Step 4:
Our DB access code are going to be placed inside the “Models” folder. Model is just a “Class” file.  So we are going to create a Model class for our purpose as below:
1. Right click on the “Model” folder. In the context menu select “Add” then choose “New item..”.
2. In the popup, select “Code” then choose “Class” and name the class file as “CRUDModel” then click “Add”. That’s all!
Add-Empty-Model
Step 5:
Till now we created classes for “Controller” and “Model”. We didn’t create any views till now. In this step we are going to create a view, which is going to act as a “home” page for our application. In order to create the view:
1. Right click on the “CRUD” folder under the “Views” folder in the context menu select “Add” then choose “View..”.
2. In the popup, give “View Name” and uncheck the “Use a layout page” checkbox. Finally click “Add” button.
Add-View
Step 6:
We don’t have a controller named “Default”, which is specified in the “RouteConfig.cs” file. We need to change the controller’s name as “CRUD”, in the default route values.

Route.config:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Routing;

namespace MVCWithADO 
{ 
    public class RouteConfig 
    { 
        public static void RegisterRoutes(RouteCollection routes) 
        { 
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute( 
                name: "Default", 
                url: "{controller}/{action}/{id}", 
                defaults: new { controller = "CRUD", action = "Index", id = UrlParameter.Optional } 
            ); 
        } 
    } 
} 


After the above change, just press F5 in visual studio, to verify that our application works fine without any error.
Step 7:
In order to achieve the complete CRUD operation, I’m going to add number of views as described in the Step 5. Here is the complete list of views and it’s purpose.
View Purpose
Home.cshtml This is the default view. Loaded when the application
launched. Will display all the records in the table
Create.cshtml Displays control’s to insert the record. Will be rendered
when the “Add New Record” button clicked on
the “Home.cshtml” view.
Edit.cshtml Displays control’s to edit the record. Will be rendered
when the “Edit” button clicked on the “Home.cshtml” view.

Step 8:
The model class, contains the all the “Data Access” logic. In other words, it will interact with Database and give it back to “View” thru “Controller”.


using System.Data; 
using System.Data.SqlClient;

namespace MVCWithADO.Models 
{ 
    public class CRUDModel 
    { 
        ///  
        /// Get all records from the DB 
        ///  
        /// Datatable 
        public DataTable GetAllStudents() 
        { 
            DataTable dt = new DataTable(); 
            string strConString =@"Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True"; 
            using (SqlConnection con = new SqlConnection(strConString)) 
            { 
                con.Open(); 
                SqlCommand cmd = new SqlCommand("Select * from tblStudent", con); 
                SqlDataAdapter da = new SqlDataAdapter(cmd); 
                da.Fill(dt); 
            } 
            return dt; 
        }

        ///  
        /// Get student detail by Student id 
        ///  
        ///  
        ///  
        public DataTable GetStudentByID(int intStudentID) 
        { 
            DataTable dt = new DataTable();

            string strConString = @"Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";

            using (SqlConnection con = new SqlConnection(strConString)) 
            { 
                con.Open(); 
                SqlCommand cmd = new SqlCommand("Select * from tblStudent where student_id=" + intStudentID, con); 
                SqlDataAdapter da = new SqlDataAdapter(cmd); 
                da.Fill(dt); 
            } 
            return dt; 
        }

        ///  
        /// Update the student details 
        ///  
        ///  
        ///  
        ///  
        ///  
        ///  
        public int UpdateStudent(int intStudentID, string strStudentName, string strGender, int intAge) 
        { 
            string strConString = @"Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";

            using (SqlConnection con = new SqlConnection(strConString)) 
            { 
                con.Open(); 
                string query = "Update tblStudent SET student_name=@studname, student_age=@studage , student_gender=@gender where student_id=@studid"; 
                SqlCommand cmd = new SqlCommand(query, con); 
                cmd.Parameters.AddWithValue("@studname", strStudentName); 
                cmd.Parameters.AddWithValue("@studage", intAge); 
                cmd.Parameters.AddWithValue("@gender", strGender); 
                cmd.Parameters.AddWithValue("@studid", intStudentID); 
                return cmd.ExecuteNonQuery(); 
            } 
        }

        ///  
        /// Insert Student record into DB 
        ///  
        ///  
        ///  
        ///  
        ///  
        public int InsertStudent(string strStudentName, string strGender, int intAge) 
        { 
            string strConString = @"Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";

            using (SqlConnection con = new SqlConnection(strConString)) 
            { 
                con.Open(); 
                string query = "Insert into tblStudent (student_name, student_age,student_gender) values(@studname, @studage , @gender)"; 
                SqlCommand cmd = new SqlCommand(query, con); 
                cmd.Parameters.AddWithValue("@studname", strStudentName); 
                cmd.Parameters.AddWithValue("@studage", intAge); 
                cmd.Parameters.AddWithValue("@gender", strGender); 
                return cmd.ExecuteNonQuery(); 
            } 
        }

        ///  
        /// Delete student based on ID 
        ///  
        ///  
        ///  
        public int DeleteStudent(int intStudentID) 
        { 
            string strConString = @"Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";

            using (SqlConnection con = new SqlConnection(strConString)) 
            { 
                con.Open(); 
                string query = "Delete from tblStudent where student_id=@studid"; 
                SqlCommand cmd = new SqlCommand(query, con); 
                cmd.Parameters.AddWithValue("@studid", intStudentID); 
                return cmd.ExecuteNonQuery(); 
            } 
        } 
    } 
}




Controller:
Controller

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Data; 
using System.Data.SqlClient; 
using MVCWithADO.Models; 
namespace MVCWithADO.Controllers 
{ 
    public class CRUDController : Controller 
    { 
        ///  
        /// First Action method called when page loads 
        /// Fetch all the rows from DB and display it 
        ///  
        /// Home View 
        public ActionResult Index() 
        { 
            CRUDModel model = new CRUDModel(); 
            DataTable dt = model.GetAllStudents(); 
            return View("Home",dt); 
        }

        ///  
        /// Action method, called when the "Add New Record" link clicked 
        ///  
        /// Create View 
        public ActionResult Insert() 
        { 
            return View("Create"); 
        }

        ///  
        /// Action method, called when the user hit "Submit" button 
        ///  
        /// Form Collection  Object 
        /// Used to differentiate between "submit" and "cancel" 
        ///  
        public ActionResult InsertRecord(FormCollection frm, string action) 
        { 
            if (action == "Submit") 
            { 
                CRUDModel model = new CRUDModel(); 
                string name = frm["txtName"]; 
                int age = Convert.ToInt32(frm["txtAge"]); 
                string gender = frm["gender"]; 
                int status = model.InsertStudent(name, gender, age); 
                return RedirectToAction("Index"); 
            } 
            else 
            { 
                return RedirectToAction("Index"); 
            } 
        }

        ///  
        /// Action method called when the user click "Edit" Link 
        ///  
        /// Student ID 
        /// Edit View 
        public ActionResult Edit(int StudentID) 
        { 
            CRUDModel model = new CRUDModel(); 
            DataTable dt = model.GetStudentByID(StudentID); 
            return View("Edit", dt); 
        }

        ///  
        /// Actin method, called when user update the record or cancel the update. 
        ///  
        /// Form Collection 
        /// Denotes the action 
        /// Home view 
        public ActionResult UpdateRecord(FormCollection frm,string action) 
        { 
            if (action == "Submit") 
            { 
                CRUDModel model = new CRUDModel(); 
                string name = frm["txtName"]; 
                int age = Convert.ToInt32(frm["txtAge"]); 
                string gender = frm["gender"]; 
                int id = Convert.ToInt32(frm["hdnID"]); 
                int status = model.UpdateStudent(id, name, gender, age); 
                return RedirectToAction("Index"); 
            } 
            else 
            { 
                return RedirectToAction("Index"); 
            } 
        }

        ///  
        /// Action method called when the "Delete" link clicked 
        ///  
        /// Stutend ID to edit 
        /// Home view 
        public ActionResult Delete(int StudentID) 
        { 
            CRUDModel model = new CRUDModel(); 
            model.DeleteStudent(StudentID); 
            return RedirectToAction("Index"); 
        } 
    } 
}



Views:
Create.cshtml


<!DOCTYPE html>

<html>    

<head>     

    <meta name="viewport" content="width=device-width" />     

    <title>Insert</title>     

</head>     

<body>     

    <form id="frmDetail" method="post" action="@Url.Action("InsertRecord")">     

        Enter Name:<input name="txtName" />     

        <br />     

        Enter Age:<input name="txtAge" />     

        <br />     

        Select Gender: <input type="radio" name="gender" value="male" checked>Male     

        <input type="radio" name="gender" value="female">Female     

        <br />     

        <input type="submit" value="Submit" name="action" />     

        <input type="submit" value="Cancel" name="action" />     

    </form>     

</body>     

</html>    

Home.cshtml:
@using System.Data    

@using System.Data.SqlClient     

@model System.Data.DataTable     

@{     

    Layout = null;     

}

<!DOCTYPE html>

<html>    

<head>     

    <meta name="viewport" content="width=device-width" />     

    <title>Home</title>     

</head>     

<body>     

    <form method="post" name="Display">     

        <h2>Home</h2>     

        @Html.ActionLink("Add New Record", "Insert")     

        <br />     

        @{     

            if (Model.Rows.Count > 0)     

            {     

                <table>     

                    <thead>     

                        <tr>     

                            <td>     

                                Student ID     

                            </td>     

                            <td>     

                                Name     

                            </td>     

                            <td>     

                                Age     

                            </td>     

                            <td>Gender</td>     

                        </tr>     

                    </thead>     

                    @foreach (DataRow dr in Model.Rows)     

                    {     

                        <tr>     

                            <td>@dr["student_id"].ToString()  </td>     

                            <td>@dr["student_name"].ToString()  </td>     

                            <td>@dr["student_age"].ToString()  </td>     

                            <td>@dr["student_gender"].ToString()  </td>     

                            <td>@Html.ActionLink("Edit ", "Edit", new { StudentID = dr["student_id"].ToString() })</td>     

                            <td>@Html.ActionLink("| Delete", "Delete", new { StudentID = dr["student_id"].ToString() })</td>     

                        </tr>     

                    }

                </table>    

                <br />     

            }     

            else     

            {     

                <span> No records found!!</span>     

            }     

            }

    </form>    

</body>     

</html>     

Edit.cshtml
@using System.Data    

@using System.Data.SqlClient     

@model System.Data.DataTable     

@{     

    ViewBag.Title = "EditView";     

}     

<html>     

<head>     

    <script type="text/javascript">     

    </script>     

</head>     

<body>     

    <form id="frmDetail" method="post" action="@Url.Action("UpdateRecord")">     

        Enter Name:<input name="txtName" value="@Model.Rows[0]["student_name"]" />     

        <br />     

        Enter Age:<input name="txtAge" value="@Model.Rows[0]["student_age"]" />     

        <br />     

        Select Gender:

        @if (Model.Rows[0]["student_gender"].ToString().ToLower() == "male")    

        {     

            <input type="radio" name="gender" value="male" checked /> @Html.Raw("Male")     

            <input type="radio" name="gender" value="female" />            @Html.Raw("Female")     

        }     

        else     

        {     

            <input type="radio" name="gender" value="male">  @Html.Raw("Male")     

            <input type="radio" name="gender" value="female" checked />            @Html.Raw("Female")     

        }     

        <input type="hidden" name="hdnID" value="@Model.Rows[0]["student_id"]" />     

        <br />     

        <input type="submit" value="Submit" name="action" />     

        <input type="submit" value="Cancel" name="action"/>     

    </form>     

</body>     

</html>   

Sunday, December 6, 2015

November Month Winner In C# Corner

By Francis   Posted at   10:00 AM   CSharpCorner No comments


                                             I'm very much excited to announce that I am again in the monthly winners list of C# Corner. This is second time in a row I'm really happy about that! This recognition really boost me up towards more community contribution as well as increase my responsibility in the ASP.Net Community. I want to thank my friends, colleagues who are all always encourage me!  Thanks to every one! :)

Tuesday, November 10, 2015

October month winner in C#Corner

By Francis   Posted at   6:27 PM   CSharpCorner No comments
I’m very much delight to announce that, I have selected one of the monthly winner for the month October 2015.
I’m very much happy and thankful to all of my readers,friends and colleague who are all always improves me a lot! :)

Sunday, October 25, 2015

Visual Studio : How to install Nuget packages in your project?

By Francis   Posted at   2:00 AM   Visual Studio Tips and Tricks No comments
               In this article I’m going to explain about how to install/uninstall Nuget packages for your application in Visual Studio using “Nuget Package Manager” and “Package Manager Console”. I assume that you have Visual Studio 2013/2015 on your machine.
                    Before that, if you are not aware about “Nuget” means, the below sentence is for you:
                  “NuGet is the package manager for the Microsoft development platform including .NET. The NuGet client tools provide the ability to produce and consume packages. The NuGet Gallery is the central package repository used by all package authors and consumers.”
Install Nuget Package using ‘Nuget Package Manager’:
Step 1:
Rightclick on your project and select  “Manage Nuget Packages”.


Step 2:
Now the “Nuget Package Manager” window will appear with the list of nuget packages.

Step 3:
In the search box, type the package you look for and hit enter. In this example, I just searched for “routedebugger” package and installed it by clicking the “Install” button.

Step 4:
While installing if the downloaded package tries to change the files in the solution/project it will popup the dialog to warn us. Just click “OK” for it and you can see the “installation progress” in the Output window.


Step 5:
Now you can just expand the “Solution Explore” window, see in the “Reference” to check that particular reference is added or not.

Uninstall NuGet Package using ‘Nuget Package Manager’:
Step 1:
If you want to uninstall, again go to the “Nuget Package Manager” and search for the particular package.Visual Studio automatically finds that particular package is installed on not and now you can see the “Uninstall”  button.


Step 2:
Since it made some changes in the project while installing, so it will automatically revert the changes in the file. So again it will popup the dialog. just click “OK”. Also in output window you can see the uninstall status.





Install NuGet Package using ‘Package Manager Console’:
Alternatively, you can use the “Package Manager Console” in Visual studio to install the necessary packages by running the respective command.
Step 1:

Go to www.nuget.org and type the package name in the search box and go to the particular package’s page, there you can find the “Package Manager Console” command.



Step 2:
To open the Package Manager Console, Tools –>NuGet Package Manager –> Package Manager Console.

Just copy the command from above website and paste it on the package manager console and hit enter.


Note :  Before hit enter key, just check the project name in the “Default project” dropdown. Incase, if you have lot of projects, you must pay attention on this by selecting correct project.
Uninstall NuGet Package using ‘Package Manager Console’:
Step 1:
In order to uninstall, just type the below command in the “Package Manager Console” and hit enter, it will uninstall the package: Uninstall-Package routedebugger.


That’s all! Hope this will helpful for someone!! Let me know your thoughts as comments!

Sunday, September 20, 2015

Various ways to Inject JS into ASP.Net Controls

By Francis   Posted at   6:07 PM   ASP.Net Server Controls No comments
There are various ways to inject Javascript to the ASP.Net Controls. In this post we are going to discuss those techniques.

For simple illustrative purpose, normally in an ASP.Net Webform, in the controls like Text box, whenever you press enter key it will submit the page. In other words, it will posted the page back to the server. In this post, we are going to see how to avoid this by using Javascript.

Technique 1: Inject Javascript directly to the markup.
                 In this way, you need to include the “onkeydown” event on each text box control.
Markup:
 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DemoWebForm.WebForm1" %>  
  
<!DOCTYPE html>  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title></title>  
</head>  
<body>  
    <form id="form1" runat="server">  
        Enter First Name:   
         <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="false" onkeydown="return (event.keyCode!=13);"></asp:TextBox>  
        <br />  
        Enter Last Name:   
         <asp:TextBox ID="TextBox2" runat="server" AutoPostBack="false" onkeydown="return (event.keyCode!=13);"></asp:TextBox>  
        <br />  
  
        <asp:Button runat="server" ID="btnSubmit" Text="Submit" />  
    </form>  
</body>  
</html> 


Technique 2: Inject Javascript thru server side code.
                        If you want to achieve the above one in server side, that is you loop thru the controls and inject the same javascript snippet. For this, you can use the following markup and code behind:
Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DemoWebForm.WebForm1" %>  
  
<!DOCTYPE html>  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title></title>  
</head>  
<body>  
    <form id="form1" runat="server">  
        Enter First Name:   
         <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="false" ></asp:TextBox>  
        <br />  
        Enter Last Name:   
         <asp:TextBox ID="TextBox2" runat="server" AutoPostBack="false" ></asp:TextBox>  
        <br />  
  
        <asp:Button runat="server" ID="btnSubmit" Text="Submit" />  
    </form>  
</body>  
</html>


Codebehind:
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
  
namespace DemoWebForm  
{  
    public partial class WebForm1 : System.Web.UI.Page  
    {  
        protected void Page_Load(object sender, EventArgs e)  
        {  
            DisableEnterKey(Page.Controls);  
  
        }  
  
        public void DisableEnterKey(ControlCollection ctrls)  
        {  
            foreach (Control c in ctrls)  
            {  
                foreach (Control ctrl in c.Controls)  
                {  
                    if (ctrl is TextBox)  
                        ((TextBox)ctrl).Attributes.Add("onkeydown", "return (event.keyCode!=13);");  
                    else if (ctrl is DropDownList)  
                        ((DropDownList)ctrl).Attributes.Add("onkeydown", "return (event.keyCode!=13);");  
                }              
            }  
        }  
    }  
}  



Technique 3: Using JQuery
                      In the above 2 techniques, either we need to include the same line in each controls or we need to loop thru the controls and inject the JS. In some cases you may want to achieve the same using the JQuery

Markup:

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){ 
            $('input[type=text]').on("keydown", "", function () { return (event.keyCode != 13); });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        Enter First Name: 
         <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="false"></asp:TextBox>
        <br />
        Enter Last Name: 
         <asp:TextBox ID="TextBox2" runat="server" AutoPostBack="false"></asp:TextBox>
        <br />
        <asp:Button runat="server" ID="btnSubmit" Text="Submit" />
    </form>
</body>
</html>


The above one is so simple, that is no repetition of code.

Hope this helps!

Monday, September 14, 2015

How to improve the performance of an ASP.Net Web page?

By Francis   Posted at   9:22 PM   Webpage No comments
Performance         
                     This is the most common question from asp.net forum to any interview. In this post I’m going to point out some of the important points that may help to improve the performance.
                      Here I used the word “improve performance” in the sense to decrease the loading time of the page. There are various reason behind. Some of them we look into from the “backend side” (Database side) and rest of them we need to take care in “front-end” ((UI) side.
For illustrative purpose, you have a ASP.Net Web site, one of the aspx page take much time to load. Also as a backend I assume that you are using SQL Server. Through out this article, we are going to see how to decrease the loading time.
Back End (DB):
Below are the points that you need to consider to fine tune the DB:
1) Try to check the Query performance, that is how much time the query will take to execute and pull the records from DB. The Use SQL Server Profiler and Execution plan for that query. So that you can come to the conclusion in which part it took much time.
2) Check in every table (who are all part of the query) Index is created properly.
3) If your query involves an complex Stored procedure, which in turn use lot of joins, then you should focus on every table. In some cases, sub-query perform better than the joins.
4) If your web page, involves paging concepts, try to move the paging concepts to SQL Server. I meant that based on the page count the SP will return the records, instead of bring the records as a whole.
Front End (UI):
1) If your page displays a lot of records, try to introduce “paging”. Say for example your page displays 1000 record in a page. Instead of pulling 1000 records as a whole, by introducing paging such that page size as 10, you need to pull 10 records only!
2) Try to choose “tabless” design, that is try to avoid “table” to design the webpage. In order to achieve this use should use “div” tag.
3) If you want to design responsive pages, try to use existing (proved) frameworks such as Bootstrap, instead of trying your own code.
4) Also if your webpage deals with lot of images or videos to display, then consider to use appropriate CDN (Content Delivery Network).
5) Use bundling and minification techniques, which reduce the server calls to load the javascript and CSS files, which in turn reduce the loading time.


Readers!! Do you thing that I have missed out anything? Let me know your thoughts in comments! Smile

Wednesday, September 9, 2015

How to publish ASP.Net Web application using Visual Studio 2015

By Francis   Posted at   6:52 PM   Visual Studio No comments

                             In this post, we are going to see a step by step procedure using the custom profile option. In other words, this post is going to explain how to publish the website in local file system.

                       The main purpose of publish dialog is provide an simplified way to take the file list which need to be publish on your website. In this article I’m going to explain how to publish a MVC web application using the “publish” dialog provided in VS 2015.

 Step 1 : Open Publish Dialog

                    You can open the publish dialog by “Right Click” on the project then select “Publish” on the floating menu.

PublishCommand

 

Step 2: Create Profile

                       As a first step, you should create a profile before publishing. This is just one kind of grouping, say for example you can create multiple profile one for Azure and one for local. So when next time you open this dialog you can see the profiles and select from them.

PublishDialog

I have selected “Custom” as a “Publish Target” and gave profile name as “LocalPublish”.

PublishProfileDialog

Step 3: Select the Connection

In this step, we need to tell where our published files are going to be. You can publish the files directly on your server also by selecting “Web Deploy” publish method or you can use FTP too.

PublishOptions

Since I’m going to publish files in local file system so I selected “File System”.

PublishInLocal

Step 4: Select Configuration and other settings

In this step, you can choose “Configuration” mode and other settings like delete files before publishing in the specific folder, precompile etc.

PublishMode

 

Step 5: Preview & Publish

You are about to complete your publishing. Click publish to start the publishing.

PublishPreview

In the output window you can see the result of the publish.

OutputWindowAck

 

Hope this post is useful who are all using the “Publish” option in Visual Studio 2015.

Happy Coding!!

Monday, September 7, 2015

How to Hosting Asp.net MVC Web Application in Local Machine?

By Francis   Posted at   2:32 PM   IIS No comments

                     In this post I’m going to discuss about how to host an ASP.Net MVC Application in your  local machine. Most of the steps to deploy a web form application and MVC applications are equivalent.

Prerequisite:

           In order to explain the steps, I assume you have a complete ASP.Net MVC Application that is ready to build with out any error.

Step 1:

Publish you MVC application in a local file path, using publish option in Visual Studio.

publishOptionInVS

For this example, I have published my application in the below path like : C:\MVCDemo

ASPNETPublishedFiles

Step 2:

Create a Virtual directory in IIS and mapped the above published file path to it.

MVCAppVirtualDirectory

If you have any doubts in creating virtual directory refer my below blog posts:

Create virtual directory on IIS using Visual Studio.

Create Virtual directory on IIS

Step 3:

You are almost done! The only thing pending is you need to browse the website, that just published. This is where most of the ASP.Net developer (especially who is a newbie to ASP.Net MVC), what they were doing : Expand the Virtual directory –> Views –> Switch to content view –> select the cshtml file –> right click on it and click “Browse”, which throws 404 Error in browser.

BrowseMVCFile

404Error

 

The above issue is common to all ASP.Net developers, who are all comes with ASP.Net  WebForm background. In order to browse the  mvc application, you need to mention the path in the form like “http://localhost/YourControllerName/YourActionMethod", which is the url routing pattern specified by default.

 

ASPNetApplication

 

Hope this helps!

Thursday, September 3, 2015

Daily Interview Questions #15 : What is the difference between the C# keywords ‘ref’ and ‘out’?

By Francis   Posted at   5:26 AM   C# Interview Questions No comments

ref

out

Parameters passed with the prefix “ref”. By using “ref” C# implements the concept called “Call by reference”. Parameters passed with the prefix “out”.
An argument passed by ref must be assigned with a value before the call. ‘out’ parameter must assigned with some value prior to the termination of the function.

Tuesday, August 18, 2015

How to Send SMS From ASP.Net Web Application?

By Francis   Posted at   7:14 PM   SMS Gateways 20 comments
Disclaimer:
            In this article I have used a Third party SMS Gateway service provider, which is I have personally used and experienced.
Introduction:
                    In my previous article I explained SMS Gateways and the various schemes available for them. This article explains how to integrate those SMS gateways into an ASP.Net web application.
What a "SMS Gateway" is?
                   A SMS Gateway allows a computer to send or receive SMS to or from a telecommunications network. This Wikipedia URL provides more detail.
Some “facts” about SMS Gateways
                  When I did some experimentation and Googling of SMS gateways some of the tutorials suggested use of “free” SMS gateways. But nothing worked for me. Latter I understood that “Nothing comes free”. Also most people asked the same question: “Is there any free SMS service is available to send SMS from my website?”. In my experience the answer is no. So my point here is, don’t waste your time searching for the free API. Instead, find a well-suited SMS Gateway provider and sign up with them.

Sunday, July 26, 2015

Visual Studio Tips and Tricks-12 : Create ASP.NET 5 Website in Visual Studio 2015(Community Edition)

By Francis   Posted at   11:19 AM   Visual Studio Tips and Tricks No comments

1) Open Visual Studio 2015.

2) Select File –> New –> Project

3) In the “New Project” window, select Templates –> Visual C# –> ASP.NET Web Application. Give valid name and select location then click “OK”.

NewProject-Window

4) During this post, ASP.Net 5 is in Preview. So in the next screen you can see the “ASP.Net 5 Preview Template” and select “Website”.

TemplateWindow

5) That’s it! You have created ASP.Net 5 website. It looks like below:

ASPNet5_Website

 

Happy Coding!!!

Monday, June 29, 2015

Visual Studio Tips and Tricks–11 : Various ways to open Visual Studio IDE in Windows

By Francis   Posted at   10:51 AM   Visual Studio Tips and Tricks No comments

In my previous articles I have explained various of tips and tricks for Visual studio. In this post i ‘m going to explain various ways that are available to open the Visual Studio IDE.

 

Way #1:

Click the Start button and type “v” in the “search” box. It will listed the programs (including Visual Studio) and select the Visual Studio.

image

 

Way #2:

Click “Start” button and type “devenv” in “Search” box. “Devenv” is the short form for “Development Environment”, which denotes Visual Studio in Windows OS.

 

image

 

Way #3:

Windows 7 offers the concept called “pin and unpin the programs” in task bar. Just pin the Visual Studio in task bar as shown below. This is another shortcut to open VS in a quicker manner.

image

Sunday, February 22, 2015

Gridview : Highlight Row/Cell using JQuery

By Francis   Posted at   3:16 PM   Gridview No comments
                         As an ASP.Net developer every one experience with the most prominent Gridview. In this article I'm going to couple all types of "highlighting" rows/column using JQuery.

Problem:
You may need to achieve any one of these following:
1. Highlight the row when mouse over on it in a grid view.


2. Highlight the cell when mouse over on it

3. Highlight a row of the gridview when click on the row.


4. Highlight a cell on a gridview when click on the cell.


prerequisite:
               This tutorial rely on JQuery purely. So you need to include the jquery library on your solution. You can download JQuery from here.

Code:

           As a first step, we need some data to be filled in Gridview. For this purpose, I have created a simple table "tblEmployee" with some columns. 


CREATE TABLE [dbo].[tblEmployee](
	[EmpID] [int] NOT NULL,
	[EmpName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	[EmpAge] [int] NOT NULL,
 CONSTRAINT [PK_tblEmp] PRIMARY KEY CLUSTERED 
(
	[EmpID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

Use the below script to insert values in to that table:


insert into tblEmployee values (1,'Francis',30);
insert into tblEmployee values (2,'Ram',25);
insert into tblEmployee values (3,'Arul',25);
insert into tblEmployee values (4,'Prabhu',30);


As a next step, create a webform and include a grid view into it as below:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridviewDemo.aspx.cs" Inherits="DemoWebApp.GridviewDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="gvEmployee" runat="server" EmptyDataText="No Records Found" AutoGenerateColumns="false" >
                <Columns>
                    <asp:BoundField HeaderText="SNo" DataField="EmpID" />
                    <asp:BoundField HeaderText="Employee Name" DataField="EmpName" />
                    <asp:BoundField HeaderText="Age" DataField="EmpAge"  />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

The below code in the code-behind file used to check the post-back and call the method to bind the data table to  grid view.

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // Bind the grid
                gvEmployee.DataSource = GetDataFromDB();
                gvEmployee.DataBind();
            }
        }

The below function is used to get data from Database and return a data table.
 
    private DataTable GetDataFromDB()
        {
            DataTable dt = new DataTable();
            // Read Connection String from WebConfig
            string strConString = ConfigurationManager.ConnectionStrings["MyConString"].ToString();
            // Create connection object
            using (SqlConnection con = new SqlConnection(strConString))
            {
                string strQuery = "Select * from tblEmployee";
                // open connection
                con.Open();
                // create command object
                SqlCommand cmd = new SqlCommand(strQuery, con);
                // create adapter 
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                // execute query and fill the data into datatable
                da.Fill(dt);
            }
            return dt;
        }
We are going to define the following "style" classes in the aspx file itself. These classes are going to be used in JQuery to highlight the row/cell.
 
<style type="text/css">
        .selectedCell {
            background-color: lightblue;
        }

        .unselectedCell {
            background-color: white;
        }
    </style>

In the next step I'm going to add the JQuery in the aspx file (between the <script>  and </script> tag). The below JQuery snippet is used to highlight the row when mouse over on it.


        // Highlight the row when mouse over on it
        $(document).ready(function () {
            $('#gvEmployee tr').hover(function () {
                $(this).addClass('selectedCell');
            }, function () { $(this).removeClass('selectedCell'); });
        });

Include the below JQuery code if you want to highlight the cell instead of row:
        // Highlight the cell when mouse over on it
        $(document).ready(function () {
            $('#gvEmployee td').hover(function () {
                $(this).addClass('selectedCell');
            }, function () { $(this).removeClass('selectedCell'); });
        }); 

The below JQuery is used to highlight the row when the particular row is clicked.
 
        //Highlight the cell when the row clicked
        $(function () {
            $(document).on('click', '#gvEmployee tr', function () {
                $("#gvEmployee tr").removeClass('selectCell');
                $(this).addClass('selectCell');
            });
        });
Include the below Jquery code if you want to highlight the cell when the particular cell clicked.
 
       //Highlight the cell when the row clicked
        $(function () {
            $(document).on('click', '#gvEmployee tr', function () {
                $("#gvEmployee tr").removeClass('selectCell');
                $(this).addClass('selectCell');
            });
        });

Highlight row/cell based on some condition:

                             In some cases you may want to highlight the row or cells based on some condition too. In that case, you can use "RowDataBound" event of Gridview. For an example, i'm going to highlight the row based on the "age" column value.

        protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int age = Convert.ToInt32(e.Row.Cells[2].Text.ToString());
                if (age >= 25 && age < 30)
                {
                    e.Row.BackColor = Color.GreenYellow;
                }
                if (age == 30)
                {
                    e.Row.BackColor = Color.LightBlue;
                }
            }
        }
The output is look alike below:
Highlight Rows on Databound
 In another way, you may want to highlight the column alone while binding the data, the below code accomplish this.
        protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int age = Convert.ToInt32(e.Row.Cells[2].Text.ToString());
                if (age >= 25 && age < 30)
                {
                    e.Row.Cells[2].BackColor = Color.GreenYellow;
                }
                if (age == 30)
                {
                    e.Row.Cells[2].BackColor = Color.LightBlue;
                }
            }
        }
The above code output like below:
Highlight Column on Databound
If you have any clarifications let me know your thoughts as comment!



Connect with Us