Dapper ORM for .Net

Dapper is opensource micro ORM framework that will help you access data from database in .Net projects. The project is maintained by stackoverflow community and hosted on GitHub

Usually database query return table which contains rows of information. In the object based programming world require data as class/objects. ORM help us to convert row into an object. It can also perform all CURD operations too.

The ORM can be utilized in Model-View-Model View pattern and it will help minimize the complexity of the code.

Dapper is not a database specific package. It can be used with any database (SQL Server,MySQL, MS Access etc). It uses a IDbConnection for performing operations.

It does not replacing anything at all, a simple example will explain the concept.

Dapper Object List example

using Dapper;

class Group
       public int ID { get; set; }
       public string g_name { get; set; }
       public double g_dr_loc { get; set; }
       public static List<Group> GetAll()
           using (IDbConnection db = new System.Data.OleDb.OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings["cstring"].ConnectionString))
               return db.Query<Group>("select id,g_name from groups").ToList();


var groups=Group.GetAll()

Here in the example, the Group model’s GetAll() static method will query all the rows into List of Group(model) using the Dapper. Without dapper you have to use Linq or a loop to store the row as a list of objects.

You can see how Linq can be used to achieve this in the following posts

Linq – suming rows,create list of custom fields,create model class object list from data table - Linq - suming rows,create list of custom fieds,create model class list from data table

Use word template with Xceed.Docx

Xceed.Words.Net is a library for generating word file without using the office library. You need not to install the office for create word file from your C# application.

I have plenty of beautiful Microsoft template, which I used create reports. So what I need is to use those template with Xceed. The idea sound good, isn’t it.

Lets place all your templates inside folder, in your debug folder and use it in your Xceed code as follows

using (var document = Xceed.Words.NET.DocX.Create(fname))
 document.ApplyTemplate(@"doctemplates /CashLedger.dotx");
document.ReplaceText("[MyCompany]", ViewModels_Variables.ModelViews.CompanyProfile[0].company);
                    document.ReplaceText("[Clandmark]", " | " + ViewModels_Variables.ModelViews.CompanyProfile[0].lmark);
                    document.ReplaceText("[CCity]", " | " + ViewModels_Variables.ModelViews.CompanyProfile[0].place); 

My template folder simply named templates and use @”doctemplates /CashLedger.dotx” to locate the application path folder.

Here is a sample document template

How to find sum from obervablecollection list in C#

This example shows how you can simply find aggregate functions like sum, average etc from a Obervablecollection list.

ObservableCollection and Model-View-ViewModel is a ideal for a typical WPF application, these are programmers two of the best tools.

In this example I am using a model class , and want to find sum of inventory qty from batch list.

double qty=_batches.Sum((b) => b.qty));

Here _batches is representing the ObservableCollection of Model batch.

How to use common folder paths in C#

Reading files from application path may be one of key requirement of any application. Actually we can place many place you love to have, on a installation machine there can be restriction as well.

Like wise in a Windows system, installer may want to put apps and other files to Programfiles. This folder intended to work with executable,configuration files etc. You can’t programmatically create new folder or files in Programfiles folder, which may require some admin rights. So where we kept those documents and other data ?

It is wise to store such files on Application data folder or even on your Document folder. For reports and other stuffs Document folder is enough.

Access Special Folders

We can use the Enironment.SpecialFolder to access the App data and Documents and also can fetch path to those folders using GetFolderPath method of Environment class.

datapath = Environment.GetFolderPath(Environment.SpecialFolder
reportPath = Environment.GetFolderPath(Environment.

the first line will get the location of C:\Users\manoj\AppData\Roaming and the second will show the Document folder path .

Access application path

How to access application/executable path in C#. This can be done using Application.ExecutablePath and the GetFolderPath method


C# Tips: Create Directory if not exist

Do you know that , In C#.Net it is possible to check directory is exist on a particular path on a system using System.IO library.

This will be great help when we want to implement the software on a system, with folder structure we are using to store out put or backup folder structure. The following simple function may help you

using System.IO;
public static void AutoCreateDirectory(string dpath)
if (!Directory.Exists(dpath))
catch (Exception ee)
view raw autocreate_dir.cs hosted with ❤ by GitHub

How to set background image using ImageBrush in C# WPF

Back ground in WPF application can be set using XAML at design time or at run time. Using XAML we do it as follows

        <ImageBrush ImageSource="images\abstract-art-artistic-background-1103970 (1).jpg"/>

At Runtime

Using some code you can change back ground of WPF /C# application using ImageBrush and BitmapImage object as follows

  • Create Uri ,which defines the path of the image
  • Using Uri define a bitmap image object which can source for ImageBrush
  • Create a BitmapImage object and set the ImageBrush source
  • Set Background property with ImageBrush

All the above can be done with inline code as follows

 ImageBrush imageBrush = new ImageBrush(new BitmapImage(new Uri("D:\images\abstract-art-artistic-background-1103970 (1).jpg",UriKind.RelativeOrAbsolute)));
                this.Background = imageBrush;

Serialize Helper class for encrypt and serialize any C# object

Serialization is the process of storing objects / user defines classes into a disc files. It stores state of the object i.e. member variable values to disk. Deserialization is reverse of serialization i.e. it’s a process of reading objects from a file where they have been stored.

As you know encryption is to hide information from others .Encryption and decryption operations require a special key. Think of a key as a password for the encryption and decryption operations

Serialization and encryption

My Serialize Helper class assist you to serialize any object or object collection to binary data file and also it encrypt data using DESCryptoServiceProvider class. Using the BinaryFormatter we can serialize objects and save into a file. Like wise we can reverse the process too.

Helper class

Our Helper class has following functions

  • public static void SerialiZe<T>(string path)
  • public static T DeserialiZe<T>(string path)
public static class SerializeHelper
static byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 };
static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
static DESCryptoServiceProvider des = new DESCryptoServiceProvider();
public static void SerialiZe<T>(T data, string path)
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
using (var cryptoStream = new CryptoStream(fs, des.CreateEncryptor(key, iv), CryptoStreamMode.Write))
BinaryFormatter formatter = new BinaryFormatter();
// This is where you serialize the class
formatter.Serialize(cryptoStream, data);
public static T DeserialiZe<T>(string path)
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var cryptoStream = new CryptoStream(fs, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
BinaryFormatter formatter = new BinaryFormatter();
var deserialized = (T)formatter.Deserialize(cryptoStream);
return deserialized;
ObservableCollection<CustomClass> obList = new ObservableCollection<CustomClass>();
CustomClass obj= new CustomClass();
obj=new CustomClass(Value);
SerializeHelper.SerialiZe<ObservableCollection<<CustomClass>>(obList, @"data.pk");
var List = SerializeHelper.DeserialiZe<ObservableCollection<PackageClass>>(@"data.pk");
view raw SeralizeHelper.cs hosted with ❤ by GitHub

As you note that , we are using generic parameter which is an arbitrary type of T. You can use any custom class/ type in place of T.

Generic type offers better performance and re-usability

How to use

Make use of the Helper class , add it to your project and just use the static class method.

that’s it

Convert Doc file to PDF,XPS,SVG,XML,HTML using Spire in C#

There are many useful libraries around Nuget which can be made your application more productive. We already learned how to create PDF files from a Word Document using Interop and Docx.

Free Spire.Doc offer high performance operation on word documents. You can check the project on Codeplex Achive

Spire offer following feature

  • *Convert Word to PDF
  • *Convert Word to HTML
  • *Convert Word to Image
  • *Convert Word to XML
  • *Convert Word to RTF
  • *Convert Word to EMF
  • *Convert Word to XPS

How to Convert Doc to PDF

Add the library to your project using Nuget Package Manager

Visual Studio 2019 : Nuget Package Manager

How to convert a WordDocument to PDF in C#.Net

Word Document is an essential part of any application, it may help users to prepare reports etc. You can easily create Documents programamatically using Microsoft.Office.Interop.Word Library in C#.Net.

This Library also provide capability of converting document to two another monstly used file format, PDF and XPS. Let’s beggin

Reference Library

First up all add refrence to Microsoft.Office.Interop.Word and Include to the project

Microsoft Visual Studio Reference Manager

Start Converting

using Microsoft.Office.Interop.Word;

and do the following

  • Open the File want to convert with Document constructor
  • Use ExExportAsFixedFormat to convert document into pdf
 Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
                    var wordDocument = appWord.Documents.Open("mydoc.docx");
                    wordDocument.ExportAsFixedFormat("mydoc.pdf", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);

In the similary way you can convert document to XPS too

Ask Masrshal to realease resources

Finally we are no need to hold the Word resources , ask Marshal to release them. Do this when ever you use file resources.


Reading and Writing Json objects in C#

JSON objects are fast to read. From Python to C# JSON objects are widely used for the database as well as data transaction purposes, some of them are simple, some others are complicated.

So let begins with a simple C# Projects



  1. Build a class for constructing JSON string
  2. Write to JSON text file
  3. Read from the file back to JSON class