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;