Archive for category C#

Getting started with MongoDB in Asp.Net Core


In this article we will discuss on the procedures to build a simple application in Asp.Net Core which communicates with MongoDB database.


This application will do the CRUD operation on a Mongo database and then displays the details in a table.

ThirdPartyTool Used

Robo 3T – is a third party tool which provides a lightweight MongoDB management tool


Setting up MongoDB:

If you have not installed the mongodb exe then download and install the same from MongoDB Download Center

After installation of the database, in order to access the mongodb we have to start the MongoDB Process.

To start MongoDB, run mongod.exe in command prompt. Make sure you are running the command prompt from installation folder of Mongodb.  By default installation path is set as C:\Program Files\MongoDB\Server\3.6\bin\

Additionally we need a data directory to store all data in MongoDB. User can set the path for data files using the –dbpath option to mongod.exe


You can begin using the Robo 3T after starting mongodb process.

For this demo I have created a Collections namely Customer with 3 columns


Since the database is ready now we will start building the application. Follow along the article to create sample application

Below is a sample demonstration of the application we are going to make


Create a new Project in Visual Studio


And Select the Template for Asp.Net Core MVC Web Application


To interact with MongoDB from c# code, we need to install .NET MongoDB Driver which provides asynchronous interaction with MongoDB.  I utilized the below nugget commands to add driver into my project

Model Class

Lets make an entity class called “Customer” which fits the schema of the Customer table in the database

The class contains Id property of the type ObjectId. This property is used to match an item in MongoDB collections. We as well have another attribute, namely BsonElement which is applied to represent an “element” in the MongoDB collection.

Controller Methods

In Controller we will add code for reading, editing, creating and deleting records from MongoDB.  I have moved the code to retrieve the mongodb database details to a common method.

Views Code

Since this was a more of a MongoDB demo I have used the scaffolding option available with MVC to generate View. You can modify this as per your needs.

Index View

Create View

Delete View

Details View

Edit View


In this article we have looked into procedures to create a simple application in MVC Core using MongoDB as database.

You can download the source code for Asp.NetCoreMVCMongoDBDemo from GitHub.



, , , , , ,

Leave a comment

Implementing Multiselect feature on AutoCompleteExtender

AjaxControlToolkit’s AutoComplete extender is designed to be a single selection control. i.e. When user selects a value the dropdown list will be closed and selected text will be assigned to targeted textbox control.

Recently I got a question on the Forums where the user wants to make the AutoCompleteExtender a multi select one. Besides the chosen values should be appended to textbox as comma separated values. This question caught my attention as it was a little tricky.

Here are the details of requirements

  • Keep the dropdown list of options on AutoComplete Extender opened
  • Allow multiple selection on AutoComplete Extender
  • Add the string to target textbox control as comma separated strings

We need to come up with a custom implementation to accomplish this requirement.  When I looked at some threads I found the code to keep the list opened. However, I need to customize it to generate comma separated values.

You can find complete implementation details here

Add a behaviorID to AutocompleteExtender control. We will use this id to close the dropdown list after user selecting values

Now we need to add a button to close the dropdown list after selecting values

Add the following javascript function to your page to close the window

Now we need to customize the inbuilt function “_setText” and “_hideCompletionList” function in order to accomplish our requirement

Complete Code



Code to populate the list when user type in characters on textbox



, , , , ,

Leave a comment

How to display larger numbers on Excel export in C#


In this article I am going to explain a solution to the problem with displaying large numbers (more than 15 numbers) in excel while exporting data in C#.

Issue Description:

By default, excel normally display larger numbers like 123456E+17 when the number overcomes Excel’s precision limit for numbers which is 8 digits. When we export the data from Gridivew to excel the same problem exists.


Drawback of existing Solution:

One solution to resolve this is to make the column type of excel to text instead of numbers. To this we need to add a single quote (‘) to the numbers which we are exporting. This will resolve the issue of displaying the complete number, however this solution has a drawback as it will display single quote along with the number like ‘123456789011.

Solution to the Problem

To show the number without using single quote we can use a Third Party Excel library called EPPlus. EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx). This library offers several features and methods to help the user to generate Excel sheet. You can read the complete details from the link I shared above.

Here in this fix we will use the method LoadFromDataTable to load the data from DataTable to Excel. The same case applies when you Export data from gridview and other controls.


private void ExcelExport(DataTable tbl)
            using (ExcelPackage pck = new ExcelPackage())
                //Create the worksheet
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
                //Load the datatable into the sheet, starting from cell A1.
                ws.Cells["A1"].LoadFromDataTable(tbl, true);
                //Write it back to the client
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=file.xlsx");

Before using above code add the below references in your page

using OfficeOpenXml;
using OfficeOpenXml.Style;

Sample usage to above method

DataTable dt = new DataTable();
            DataRow Sample = dt.NewRow();
            Sample["PhoneNo"] = "12345678911121314";
            Sample["Name"] = "SampleName";

With above code the exported excel file will look like below


You can use Nugget to add the EPPlus in your solution.


, , , , , , ,

1 Comment

How to check if an array of elements are in Sequential Order in C#

You can use the SequenceEqual method to check if numbers are in Sequence order.  SequenceEqual method determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.


//Your Input
int[] numSequence = { 1, 2, 3, 4, 5 };
//Check if they are in sequence or not
bool isInSequence = numSequence.SequenceEqual(Enumerable.Range(1, numSequence.Count()));

Above code will give the result as true if numbers are in proper sequence.

You also need to ensure that you have added the below namespace for Linq in your page

using System.Linq;

, ,

Leave a comment

Search and Populate GridView from database using Jquery Ajax


In this article I am going to explain how to search and Populate GridView from database using Jquery Ajax.


You need to add the necessary JQuery files to your page prior to use this plugin. In this example I have used the online JQuery CDN files available. If you don’t want to use the online available cdn file then you can manually add the jquery files to your solution. I have explained the steps here in detail.

I have used Address table from AdventureWorks Database. You can download it from here.


Here we are make use of Jquery Ajax post method in Jquery to check if record exists in database and get the details on the blur event of textbox.


 <html xmlns="">
 <head runat="server">
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
     <title runat="server"></title>
     <script src=""></script>
     <script type='text/javascript'>
         $(document).ready(function () {
             //Attach on change event to textbox here
             $("#TextBox1").change(function () {
                 //Remove all previously added rows in gridview
                 $("[id*=sampleGV] tr").not($("[id*=sampleGV] tr:first-child")).remove();
                     type: "POST",
                     //Call the method to get data from database 
                     url: "WebForm4.aspx/GetOrderDetails",
                     //Pass the value from textbox to method
                     data: '{"addressID":' + $("#TextBox1").val() + '}',
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: function (result) {
                         //Add the resul to gridview
                         $("#sampleGV").append("<tr><td>" + result.d[0][0] + "</td><td>" + result.d[0][1] + "</td><td>" + result.d[0][2] + "</td></tr>");
                     failure: function (response) {
                     error: function (response) {
 <body class="myCss">
         <form id="form1" runat="server" class="hidden">
             <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
             <asp:GridView ID="sampleGV" runat="server" Width="1000px" ShowHeaderWhenEmpty="true"
                 CellPadding="0" CellSpacing="0">


First we need to populate an empty row in GridView. Reason behind this is if we didn’t assign any datasource then the GridView won’t populate at runtime and we won’t be able to access it at client side

 protected void Page_Load(object sender, System.EventArgs e)
         //Load and empty row to gridview
         if (!IsPostBack) {
                DataTable dt = new DataTable();
                sampleGV.DataSource = dt;

Next is the GetOrderDetails method which will read the parameter from client side and the search the database and then pass the result set back. Note the [Services.WebMethod()] attribute I added to the GetOrderDetails method,this is important  otherwise the serverside method will not be called from client side jQuery AJAX call.

public static Array GetOrderDetails(string addressID)
	//Create sql connection object here
	SqlConnection conn = null;
	//Create sql DataTable object here
	DataTable dt = new DataTable();
	//Create sql SqlDataAdapter object here
	SqlDataAdapter da = default(SqlDataAdapter);
	//Create sql ArrayList object here
	ArrayList rows = new ArrayList();
	//Get the connectionstring from webconfig file
	string connection = ConfigurationManager.ConnectionStrings("Adventure WorksConnectionStringPersonal").ConnectionString;
	//Create sql SqlConnection object here and assign the conenctionstring
	conn = new SqlConnection(connection);
	//Create sql query here
	string sql = "SELECT AddressID,AddressLine1,City FROM Person.Address a WHERE a.AddressID = @AddressID";
	//Create sql SqlCommand and assign connection and command here
	SqlCommand cmd = new SqlCommand(sql, conn);
	//Pass your parameter here
	cmd.Parameters.AddWithValue("@AddressID", addressID);
	//Open the SQLConnection here
	//Create SqlDataAdapter object here
	da = new SqlDataAdapter(cmd);
	using (DataSet ds = new DataSet()) {
		//Load the DataTable
		foreach (DataRow dataRow in dt.Rows) {
			rows.Add(dataRow.ItemArray.Select(item => item.ToString()));
		//Create an array and then return the values
		return rows.ToArray();


, , , ,

Leave a comment

How to highlight the selected rows in Repeater using Jquery


In this article I am going to explain how to highlight the selected row in Repeater control using Jquery.  At runtime Repeater control will render as table we will be manipulating this table structure to access each row and then use the css to highlight the row.


You need to add the necessary JQuery files to your page prior to use this plugin. In this example I have used the online JQuery CDN files available. If you don’t want to use the online available cdn file then you can manually add the jquery files to your solution. I have explained the steps here in detail.


We will use the below css to hightlight the rows in gridview.

<style type="text/css">
            background-color: #9999FF;

Jquery Code:             

Below Jquery function will remove the css from all other rows except the selected row

 <script src=""></script>
    $(function () {
         $(".trclass").click(function () {


   <asp:Repeater runat="server" ID="Repeater1">
                <table width="500px" border="1px">
                    <tr style="background-color: #fb7700">
                <tr class="trclass">
                        <asp:Label ID="lblValue1" runat="server" Text='<%# Eval("val1") %>'></asp:Label>
                        <asp:Label ID="lblValue2" runat="server" Text='<%# Eval("val2") %>'></asp:Label>

Below code is to populate dummy data, you dont need this code if you are populating the repeater from database in code behind.


  protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
                DataTable table1 = new DataTable();
                table1.Rows.Add("Value1", "Message1");
                table1.Rows.Add("Value2", "Message2");
                table1.Rows.Add("Value3", "Message3");
                table1.Rows.Add("Value4", "Message4");
                table1.Rows.Add("Value5", "Message5");
                table1.Rows.Add("Value6", "Message6");
                table1.Rows.Add("Value7", "Message7");
                Repeater1.DataSource = table1;


, , , , ,

Leave a comment

How to Crop the Image using CropImage.Net tool in Asp.Net


In this article I am going to explain how to crop an Image using CropImage.Net


You can download the dll files needed to use CropImage.Net from this link. Once you have a downloaded the files you need to add the dll files to your solution. You can follow the below steps to add the dlls.

  • Open your Project within the Solution Explorer
  • Right-click the References folder and Choose Add Reference options
  • Find and select the dlls which needs to be added to your solution
    • ImageResizer.dll
    • Imazen.Crop.dll
    • System.Web.Extensions.dll (You may need to use the browse button if you are not finding the dll in available list)
  • Click the Ok button to add it to your Project.

Now you have all the files added to your project

Details of CropImage.Net Control:

CropImage.Net exposes method called Crop, which actually Crops the original image and saves it to the specified path. This method have two overrides one with destinationpath as parameter and another one with destinationpath and appendCorrectExtension.

public void Crop(string destPath);
public void Crop(string destPath, bool appendCorrectExtension)


Here I am going to explain the steps on how to use CropImage.Net tool to crop the images using Asp.Net.

In this demo I will upload a file and then the uploaded file will be shown in an image control. Then with the help of CropImage control the image will be cropped and shown in another image control called result.

First Step is to register the ImageCrop control in your page like given below

<%@ Register Assembly="Imazen.Crop" Namespace="Imazen.Crop" TagPrefix="ic" %>

Then you need add the below CropImage control to your page and then set it Image property to the Image control from which Image is used to crop.

<ic:CropImage ID="CropImage1" runat="server" Image="Image1" CanvasWidth="300" />

Then we use the Crop method to crop and save the image to the destination path provided.

//Save the copy in local folder
CropImage1.Crop(MapPath("~/images"), true);

You also need to add the below configurations to your webconfig file

<?xml version="1.0"?>
    <compilation debug="true" />
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>

    <validation validateIntegratedModeConfiguration="false"/>
      <add name="ImageResizingModule" type="ImageResizer.InterceptModule"/>

Complete Code:


<%@ Register Assembly="Imazen.Crop" Namespace="Imazen.Crop" TagPrefix="ic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
            <h3>Croping Image using ImageResizer in .Net</h3>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
            <asp:Image ID="Image1" runat="server" ImageUrl="" />

            <ic:CropImage ID="CropImage1" runat="server" Image="Image1" CanvasWidth="300" />

            <asp:Button ID="Button1" runat="server" Text="Crop" OnClick="btnCrop_Click" />
            <h3>The result</h3>
            <asp:Image ID="Result" runat="server" Visible="false" />


protected void btnCrop_Click(object sender, EventArgs e)

        //Show the Result Image control 
        Result.Visible = true;
        //Assign the image url from CropImage control
        Result.ImageUrl = CropImage1.CroppedUrl;

        //Save the copy in local folder
        CropImage1.Crop(MapPath("~/images"), true);

        //You can also get the coordinates from CropImage if you want to show to the user
        this.Title = CropImage1.X + "," + CropImage1.Y + "," + CropImage1.X2 + "," + CropImage1.Y2;


    protected void btnUpload_Click(object sender, EventArgs e)
        //Check if file upload is having any value
        if (FileUpload1.HasFile)
                //Get the uploaded filename from FileUpload Control
                string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
                //Save the file to folder
                FileUpload1.SaveAs(Server.MapPath("~/images/") + filename);
                //Show the uploaded image in Image Control which is tagged to the Image Cropping Control
                Image1.ImageUrl = "~/images/" + filename;
            catch (Exception ex)
                throw new Exception(ex.InnerException.ToString());

Note that I have used the folder which is inside in my solution.You can see that in the image given above. If you have a different you need to change the path accordingly.


, , , , ,