Advantages of ASP.NET Framework

                                                              MOST IMPORTANT ADVANTAGES & REASON TO CHOOSE ASP.NET FRAMEWORK

  • .NET allows the aptitude for any user to access data or database and return results.
  • Entire flexibility for viewing in multiple browsers including internet explorer and Mozilla Firefox.
  • .NET framework decreases the size of the entire written code which is generally used to create large applications.
  • It is easily integrated with other Microsoft applications.
  • .NET is purely server side technology.
  • Framework ASP.NET code boasts of high-security features in its internal setup and makes safe & secure applications.
  • It is easy to use for creating dynamic web pages and has the ability to dynamically edit any of the content on the web page.
  • Microsoft .NET stage offers rich Better interface controls.
  • It provides MVC Architecture (model view controller) to make versatile applications.
  • Microsoft .NET applications can be effortlessly referred on any Microsoft server. The structure stimulates one-time setup creation to convey application quicker.
  • Web server continually monitors the pages, applications, and components running on it. If its attention any infinite loops, memory leaks and other illegal activities, it quickly destroys those activities and restarts itself.
  • It provides more stability and scalability.

Multilevel Grid in MVC using Jquery

Steps To build Multilevel Grid in MVC

Step1:- Create Empty MVC application in visual studio

Step-2: – Create a MDF file inside App_Data folder.

Step-3:- Now create a table for retrieving the data here i took employees as table name.

CREATE TABLE [dbo].[Employees] (

   [EmployeeID]     INT           NOT NULL,

   [LastName]        NVARCHAR (50) NULL,

   [FirstName]       NVARCHAR (50) NULL,

   [Title]           NVARCHAR (50) NULL,

   [TitleOfCourtesy] NVARCHAR (50) NULL,

   [BirthDate]       DATETIME      NULL,

   [HomePhone]       NVARCHAR (50) NULL,

   [ReportsTo]       INT           NULL,

   CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED ([EmployeeID] ASC)

);

 After creating the table insert some data in that table like this

If you observe the above table, we have “ReportsTo” column this column contains EmployeeID values and based on this column we can assign employees to CEO, Project manager and Team Leader.

Step-4:- Create one ADO.Net Entity Model to Employees table. In solution you can see my entity model in below snippet.

 

Step-6:- Right click on controllers folder, create Controller.

public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<Employee> list = new List<Employee>();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
list = dc.Employees.OrderBy(a => a.EmployeeID).ToList();
}
return View(list);

}
}

MyDatabaseEntities is class which inherited by DbContext. using “dc” we retrieve all employees details and assign to the list.

Employee.cs:-

public string HomePhone { get; set; }

public Nullable<int> ReportsTo { get; set; }

}

Step7:- Now Right click on Index method of HomeController and add view.

 

Index.cshtml:-

 

@model List<MultilevelGrid.Employee>

 

<h2>Display Multilevel Grid</h2>

 

@* Jquery for Collapse/Expend *@

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function () {

$('.icon').on('click', function () {

var $pRow = $(this).parents('tr');

var $nextRow = $pRow.next('tr');

$nextRow.toggle();

$(this).toggleClass('icon-s icon-e');

});

})

</script>

 

@* CSS for dispalay the grid *@

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

<style>

.container {

min-width: 500px;

overflow: hidden;

}

.innerTable table {

margin: 0px auto;

border-left-width: 4px;

}

td.innerTable {

padding-left: 20px !important;

}

.icon {

background-repeat: no-repeat;

width: 16px;

height: 16px;

display: inline-block;

float: left;

color: navy;

}

.icon-e {

background-position: -32px -16px;

}

.icon-s {

background-position: -64px -16px;

}

</style>

 

@*Call NetedData.cshtml Page for displaying the grid*@

<div class="container">

@NestedData.GetHtml(Model, 0)

</div>

 

 

       

In above view we add Employee.cs file as model at top of Index.cshtml. End of the coding we call the NestedData.cshtml page.

 

Step8:- Create NestedData.cshtml page for displaying the multilevel grid.

 

@helper GetHtml(List<MultilevelGrid.Employee> employeeList, int parentID)

{

 <table class=”table table-bordered”>

   @{

     int currentID = 0;

     int rowIndex = 0;

     foreach (var i in employeeList.Where(a => a.ReportsTo.Equals(parentID)))

      {

        if (i.EmployeeID == currentID)

         {

           continue;

         }

        else

         {

          if (rowIndex == 0)

            {

              <thead>

                <tr>

                   <th>Employee ID</th>

                   <th>Employee Name</th>

                   <th>Designation</th>

                   <th>Contact Number</th>

                </tr>

               </thead>

             }

        rowIndex++;

        currentID = i.EmployeeID;

         var Sub = employeeList.Where(a =>                                                                                                                                                                                                    a.ReportsTo.Equals(i.EmployeeID)).ToList();

        var newEmployeeList = employeeList.

 Where(a => !a.EmployeeID.Equals(i.EmployeeID)).ToList();

        <tbody>

          <tr>

            <td>

               @if (Sub.Count > 0)

                {

                 <a class=”icon icon-e” style=”float:left; cursor:pointer;”>>></a>

                }

               else

                {

                 <span style=”display:inline-block;width:14px”>&nbsp;</span>

                }

                 @i.EmployeeID

                 </td>

                 <td>@i.TitleOfCourtesy @i.FirstName @i.LastName</td>

                 <td>@i.Title</td>

                 <td>@i.HomePhone</td>

            </tr>

            <tr style=”display:none;”>

                 @if (Sub.Count > 0)

                  {

                    <td colspan=”4″ class=”innerTable”>

                      @NestedData.GetHtml(newEmployeeList, i.EmployeeID)

                    </td>

                   }

                  else

                   {

                     <td colspan=”4″></td>

                   }

              </tr>

         </tbody>

        }

      }

    }

</table>

}

 

In above code we retrieve the two categories of employees based “ReportsTo” column.i.e:

 

1)var Sub = employeeList.Where

(a => a.ReportsTo.Equals(i.EmployeeID)).ToList();

2) var newEmployeeList = employeeList.Where

(a =>!a.EmployeeID.Equals(i.EmployeeID)).ToList();

 

Step9:- Now run the application, by default the application load like this.

If you click on “>>” button, the next row will be expanded like this.

 

The above output indicates, the Project manager and Team Leader are working under CEO. Again if you click on second EmployeeID it will be expanded.

 

 

It’s indicates the Jr.Developer works under Project Manager.

 

This all explains how multilevel grid worked on employees table. Thanks!

Passing XML as a parameter in stored procedure and inserting using ADO.NET code with Example In MVC

XML_Stored_Proc

if we have number of parameters. We can append all parameters to xml parameter and passing as a single parameter in xml. This if helpful for more performance to a stored procedure.

Follow the Below steps 

Step-1: Create Table

Table

Step-2:  Create Procedure like below

CREATE PROCEDURE  [dbo].[USP_XMLInsert]
(
@xmlx xml
)
AS
BEGIN
SET NOCOUNT ON;
      INSERT INTO Tbl_Customer
      SELECT
      Customer.value(‘(Name/text())[1]’,’NVARCHAR(50)‘) as Name , –TAG
      Customer.value(‘(City/text())[1]’,’NVARCHAR(50)‘) as City, –TAG
      Customer.value(‘(IndustryType/text())[1]’,’NVARCHAR(50)‘) as IndustryType –TAG
      FROM
      @xmlx.nodes(‘/Customer‘)AS TEMPTABLE(Customer)

END

GO

Step 3: Create sample MVC application and create model class in models folder and create properties like below;

namespace Insert_XMLPROC.Models
{
    public class Customer
    {
        public string Name { get; set; }
        public string City { get; set; }
        public string IndustryType { get; set; }
    }
}

Step 4: Create controller in controller folder and write insert logic

    public class CustomerController : Controller
    {
        // GET: Customer
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Customer objcustomer)
        {
            StringBuilder objstring = new StringBuilder();
            objstring.Append(“<Customer>“);
            objstring.Append(“<Name>“);
            objstring.Append(objcustomer.Name);
            objstring.Append(“</Name>“);
            objstring.Append(“<City>“);
            objstring.Append(objcustomer.City);
            objstring.Append(“</City>“);
            objstring.Append(“<IndustryType>“);
            objstring.Append(objcustomer.IndustryType);
            objstring.Append(“</IndustryType>“);
            objstring.Append(“</Customer>“);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(objstring.ToString());

            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“MyConnection“].ToString());
            con.Open();
            SqlCommand cmd = new SqlCommand(“USP_XMLInsert“, con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue(“@xmlx“, xmlDoc.InnerXml);
            cmd.ExecuteNonQuery();
            return View();
        }
    }


Step 5: Create index view and write insert logic

@model Insert_XMLPROC.Models.Customer

@{
    ViewBag.Title = “Index“;
}

<h2>Index</h2>

<script src=“~/Scripts/jquery-1.10.2.js”></script>
<script src=”~/Scripts/jquery-1.10.2.min.js“></script>
<div>
    <table>
        <tr>
            <td>Name</td>
            <td>
                <input type=”text” id=”txtName” />
            </td>
        </tr>
        <tr>
            <td>City</td>
            <td>
                <input type=”text” id=”txtCity” />
            </td>
        </tr>
        <tr>
            <td>IndustryType</td>
            <td>
                <input type=”text” id=”txtIndustryType” />
            </td>
        </tr>
        <tr>
            <td>
                <input type=”button” id=”btnsubmit” value=”Save” />
            </td>
        </tr>
    </table>

    <script type=“text/javascript”>
        $(document).ready(function () {
            $(‘#btnsubmit‘).click(function () {
                $.ajax(
                {
                    type: “POST“,
                    url: ‘/Customer/Index‘,
                    data: {
                        Name: $(‘#txtName‘).val(),
                        City: $(‘#txtCity‘).val(),
                        IndustryType: $(‘#txtIndustryType‘).val(),
                    }

                });

            });
        });
    </script>
</div>


Usage of BundleConfig.cs file with sample an example in MVC

Follow below steps:

Step-1:

To add Bundle config file, first you need to add the Microsoft.AspNet.Web.Optimization nuget package to your web project:

Install-Package Microsoft.AspNet.Web.Optimization

Step-2:

Then under the App_Start folder create a new cs file called BundleConfig.cs.

Add below code in Bundleconfig file;

namespace BundleConfigEx
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle(“~/bundles/sciptsJS”).Include(“~/Scripts/jquery-{version}.js”));
BundleTable.EnableOptimizations = true;
}
}

}

bundles.Add(new ScriptBundle(“~/bundles/sciptsJS”).Include(“~/Scripts/jquery-{version}.js”));

we will add number of bundles(Based on Our requirement) like above line of code. 

Step-3:

For this we will register our bundles in Global.asax.cs file like below;

BundleConfig.RegisterBundles(BundleTable.Bundles);

Step-4:

Now we can call this bundle in our _layout file (or) View(Index.cshtml) like below

@Scripts.Render(“~/bundles/sciptsJS”)

Email sending code with an attachment using ASP.NET MVC

Please follow the below steps;

Step-1: Create a new model class in models folder

The following is the code for new model;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVC_SentMailApp.Models
{
    public class MailModel
    {
        public string To { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
    }
}
Step-2: Create a new controller in Controllers Folder
Following is the code for Controller;
SentMailController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
namespace MVC_SentMailApp.Controllers
{
    public class SentMailController : Controller
    {
        //
        // GET: /Sent Mail/
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// Send Mail with Gmail
        /// </summary>
        /// <param name=”objModelMail”>MailModel Object, keeps all properties</param>
        /// <param name=”fileUploader”>Selected file data, example-filename,content,content type(file type- .txt,.png etc.),length etc.</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(SendMailwithAttachment.Models.MailModel objModelMail, HttpPostedFileBasefileUploader)
        {
            if (ModelState.IsValid)
            {
                string from = “Your Gmail Id”; //example:- lakshmi9@gmail.com
                using (MailMessage mail = new MailMessage(from, objModelMail.To))
                {
                    mail.Subject = objModelMail.Subject;
                    mail.Body = objModelMail.Body;
                    if (fileUploader != null)
                    {
                        string fileName = Path.GetFileName(fileUploader.FileName);
                        mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName));
                    }
                    mail.IsBodyHtml = false;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = “smtp.gmail.com”;
                    smtp.EnableSsl = true;
                    NetworkCredential networkCredential = new NetworkCredential(from, “Your Gmail Password”);
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = networkCredential;
                    smtp.Port = 587;
                    smtp.Send(mail);
                    ViewBag.Message = “Sent”;
                    return View(“Index”, objModelMail);
                }
            }
            else
            {
                return View();
            }
        }
    }
}
Index.cshtml
 
@model MVC_SentMailApp.Models.MailModel
@{
    ViewBag.Title = “Index”;
}
<script src=”~/Scripts/jquery-1.7.1.min.js”></script>
<script>
    $(document).ready(function () {
        if (‘@ViewBag.Message’ == ‘Sent’) {
            alert(‘Mail has been sent successfully’);
        }
    });
</script>
<h2>Index</h2>
<fieldset>
    <legend>Send Email
    </legend>
    @using (@Html.BeginForm(“Index”, “SendMailer”, FormMethod.Post, new { @id = “form1″, @enctype =”multipart/form-data” }))
    {
        @Html.ValidationSummary()
        <input type=”submit” value=”Send” />
        <table>
            <tr>
                <td>To:
                </td>
                <td>
                    @Html.TextBoxFor(m => m.To)
                </td>
            </tr>
            <tr>
                <td>Subject:
                </td>
                <td>
                    @Html.TextBoxFor(m => m.Subject)
                </td>
            </tr>
            <tr>
                <td>Attachment
                </td>
                <td>
                    <input type=”file” name=”fileUploader” />
                </td>
            </tr>
            <tr>
                <td>Body:
                </td>
                <td>
                    @Html.TextAreaFor(m => m.Body)
                </td>
            </tr>
        </table>
    }
</fieldset>
 
In the code above we have the following 4 fields:
  • To
  • Subject
  • Message
  • Attachment

When the user clicks the “Send” button, the mail will be sent to the specified mail address that you provide in the “To” TextBox.

That’s it. Press F5 to run your code.

U can also try it in your local environment — good luck:)

Insert data using Jquery Ajax Call in ASP.NET MVC

Follow below steps to Insert data into database using ajax call in MVC;

Step-1:

Create One table To Save data

Step-2: 

Create procedure to insert data like below

CREATE PROCEDURE [dbo].[InsertData]
(
@Address nvarchar(50),
@Name nvarchar(50)
)

AS
BEGIN
INSERT INTO Tbl_Test
(
Address
,Name
)
Values
(
@Address
,@Name
)
END

Step-3:

Create an MVC sample application to insert data

Step-4:

Create Model class in Models folder

Write following code in model class

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

namespace BundleConfigEx.Models
{
public class SaveData
{
public string Address { get; set; }
public string Name { get; set; }
}
}

Step-5:

Add controller class

paste below code in controller class

using BundleConfigEx.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BundleConfigEx.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(SaveData objdata)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“MyConnection”].ToString());
con.Open();
SqlCommand cmd = new SqlCommand(“USP_InsertData”, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(“@Address”, objdata.Address);
cmd.Parameters.AddWithValue(“@Name”, objdata.Name);
cmd.ExecuteNonQuery();
con.Close();

}
catch (Exception)
{

throw;
}
return View(“Index”);
}
}
}

Step-6:

Create a view and paste below code;

@model BundleConfigEx.Models.SaveData
@using System.Web.Optimization;

@{
ViewBag.Title = “Index”;
}

<h2>Index</h2>
<script src=”~/Scripts/jquery-1.10.2.js”></script>
<script src=”~/Scripts/jquery-1.10.2.min.js”></script>
<div>
<table>
<tr>
<td>Address</td>
<td>
<input type=”text” id=”txtaddress” />
</td>
</tr>
<tr>
<td>Name</td>
<td>
<input type=”text” id=”txtname” />
</td>
</tr>
<tr>
<td>
<input type=”button” id=”btnsubmit” value=”Save” />
</td>
</tr>
</table>

<script type=”text/javascript”>
$(document).ready(function () {
$(‘#btnsubmit’).click(function () {
$.ajax(
{
type: “POST”,
url: ‘Home/Index’,
data: {
Address: $(‘#txtaddress’).val(),
Name: $(‘#txtname’).val(),
}

});

});
});
</script>
</div>

All the best good luck 🙂

New Features in .Net framework 4.5 and 5.0

Explaining the following features:

  • Parallel foreach
  • BigInteger
  • Expando Objects
  • Named and Optional Parameters
  • Tuple

1. Parallel.ForEach

Parallel.ForEach is a feature introduced by the Task Parallel Library (TPL). This feature helps you run your loop in parallel. You need to have a multi-processor to use of this feature.

Simple foreach loop

foreach (string i in listStrings)

{

……….

}

Parallel foreach

Parallel.Foreach(listStrings, text=>
{
……………………..
});

2. BigInteger

BigInteger is added as a new feature in the System.Numerics DLL. It is an immutable type that represents a very large integer whose value has no upper or lower bounds.

BigInteger obj = new BigInteger(“123456789123456789123456789”);

3. ExpandoObject

The ExpandoObject is part of the Dynamic Language Runtime (DLR). One can add and remove members from this object at run time.

Create a dynamic instance.

dynamic Person = new ExpandoObject();

Person.ID = 1001;

Person.Name = “Princy”;

Person.LastName = “Gupta”;

4. Named and Optional Parameters

Optional Parameters

A developer can now have some optional parameters by providing default values for them. PFB how to create optional parameters.

Void PrintName(string a, string b, string c = “princy”)

{

Console.Writeline(a, b, c)

}

We can now call the function PrinctName() by passing either two or three parameters as in the following:

PrintName(“Princy”,”Gupta”,”Jain”);
PrinctName(“Princy”,”Gupta”);

Output

PrincyGuptaJain
PrincyGuptaprincy

Note: An optional parameter can only be at the end of the parameter list.

Named Parameters

With this new feature the developer can pass values to parameters by referring to parameters by names.

Void PrintName(string A, string B

{

}

Function call

PrintName (B: “Gupta”, A: “Princy”);

With this feature we don’t need to pass parameters in the same order to a function.

5. Tuple

A Tuple provides us the ability to store various types in a single object.

The following shows how to create a tuple.

Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1,”princy”, true);

Var tupleobj = Tuple.Create(1, “Princy”, true);

In order to access the data inside the tuple, use the following:

string name = tupleobj.Item2;

int age = tupleobj.Item1;

bool obj = tupleobj.Item3;