Posts Tagged 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

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 read JSON with object name using Json.Net in C#

In this article I am going to explain how to read the values from Json using Json.Net library when it is having Object Name.


In this article we are using Json.Net library to parse and read values in Json. We will be using JSON serializer methods available in this dictionary.

If you don’t have Json Framework in your machine you can get it from Nugget for Json.

Sample JSon file which we use in this article

{"firstName":"Test1FN", "lastName":"Test1LN"},
{"firstName":"Test2FN", "lastName":"Test2LN"}


After adding library to your project ensure that you have added the namespace reference in your page

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Next add a class to hold the values, note that I have used JsonProperty to map the JSON property to a .NET member or constructor parameter. This is very important as the object name format is not following key: value combination so if you don’t set this then while reading you will get exception.

public class User
   [JsonProperty("firstName", Required = Required.Always)]
   public string FirstName { get; set; }

   [JsonProperty("lastName", Required = Required.Always)]
   public string LastName { get; set; }

Now you can use the below code to read the values

//Load your Json string here
String jsonString = "{\"user\":[{\"firstName\": \"Test1FN\", \"lastName\": \"Doe\"},{\"firstName\": \"Test2FN\", \"lastName\": \"Test2LN\"}]}";
JToken root = JObject.Parse(jsonString);
JToken user = root["user"];
//Deserialize the Json to list
var deserializedUser = JsonConvert.DeserializeObject<List<User>>(user.ToString());

//Loop through values 
foreach (User p in deserializedUser)
//Your code to process the values

, , , ,

Leave a comment

Null Conditional Operator in C# 6.0


In this article I am going to explain about one of the new feature introduced with C# 6.0 – Null Conditional Operator.


Null reference is one of the common exception which normally faced by most of the developers if you didn’t handled by adding proper checking for null values in code.

To resolve this null reference exception till now what we did was to add proper check condition for null values in code like given below

string firstname = null;
//Check if Firstname is null or not 
if(firstname != null)
     string res = firstname.Substring(0, 4);

Even though above code will works fine, we need to add additional code like if condition and all to safeguard the code from null reference exception. Wouldn’t it be nice if you have a single line of code which actually checks for null condition and the handles it.

With C# 6.0 they introduced a new operator called Null Conditional Operator (?). This will handles the above line of code in a single statement like given below

string firstname = null;
//Handle the null case using the operator(?) this wont throw null reference exception
string res = firstname?.Substring(0, 4);

Internally what the null conditional operator do is it will check for null before calling the following methods and if there is any null value the code execution will won’t proceed further and return the null value which subsequently stop the null reference exception from occurring.

Ex: In below code

string res = firstname?.Substring(0, 4);

Null conditional operator first check for null values in firstname and it will call the following method Substring method only if firstname is not null.

A word of caution while using null conditional operator is that you need to ensure that the variable you are assigning the result will be of nullable type


The below code will throw an exception

DataTable dttable = new DataTable();
dttable = null;
int rowcount = dttable?.Rows.Count;

You need to make it nullable using nullableint to resolve the issue

DataTable dttable = new DataTable();
dttable = null;
int? rowcount = dttable?.Rows.Count;

, , , ,

Leave a comment