Visual Studio Ignore Bin, Obj Folders From GIT Repo

Found a very useful template file to exclude folders like bin and obj.

The template is available at the following github location:

https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

Just create a “.gitignore” file inside your project where you have setup your git repository and copy and paste the content from the link above to this file.

Get rid of bins!

Upload Image and Create Thumbnail

In this post, I will show an implementation of uploading image to server and creating a thumbnail version of the uploaded image. Creating a thumbnail is useful as it reduces image size and dimensions and improves application’s performance.

In your ASP.NET Controller’s HttpPost Action, you can get the uploaded image file as HttpPostedFileBase as:


HttpPostedFileBase file = Request.Files[0];

You can also check for the file’s ContentLength property to make sure the uploaded image is within certain allowed size range:


if (file.ContentLength > 20000000)//less than 2 mb
{
return Json(new { ErrorMessage = "Please upload an image of size smaller than 2 MB." }, JsonRequestBehavior.AllowGet);
}

When uploading an image, one important thing to keep in mind is the filename of the uploaded image. You want to be sure that you do not replace an existing file with the newly uploaded file. So, I usually rename the uploaded image to a unique filename.


string fname = file.FileName;
var extension = Path.GetExtension(fname);

string newFname = Guid.NewGuid().ToString();
var newFileName = newFname + extension;

Now, save the uploaded image to any specified folder like this:


// Get the complete folder path and store the file inside it.
newFileName = Path.Combine(Server.MapPath("~/Uploads/"), newFileName);
file.SaveAs(newFileName);

Next, create a file name for the thumbnail version of the image.


var thumbVersionFileName = newFname + "_thumb" + extension;

thumbVersionFileName = Path.Combine(Server.MapPath("~/Uploads/"), thumbVersionFileName);

Now to get the actual thumbnail size version, use the function below:


public static void CreateThumbnailImageVersion(string imagePath, int xSize, int ySize, string returnImagePath)
{
Image image = Image.FromFile(imagePath);
Image thumb = image.GetThumbnailImage(xSize, ySize, () => false, IntPtr.Zero);
thumb.Save(returnImagePath);

image.Dispose();
}

Implementing Inbox Messaging System in ASP.NET

In this post, I would like to write about creating a simple Messaging System for your application. Almost all user based applications require some form of messaging system. Mainly the messaging system is needed so that users within the application can send messages to one another and also, it is needed to show any form of message to the users by the Admin of the application.

I will first show the table design for this simple messaging system and then write about how one can create an implementation.

So, the table structure will basically look like this:

Most of the fields here need no clarification. The one important field that you have to make note of is “ParentMessageId“. This field is used to keep track of whether a message is a reply to a previous message or not.

Basically, if a new message was created, the ParentMessageId will be set as zero (0). If a message is a reply to a previous message, this value will be set as integer value of the previous MessageId value.

Next, the implementation, which would be something like this.


public interface IMessageService
{
void SendMessage(MessageModel messageModel);
List<MessageModel> GetAllCoversationsForUser(int userId);
int GetNewMessagesCount(int userId);
void SetMessageViewed(int messageId);
}

All we need are these four public methods and using these four methods, you can easily implement your Inbox Messaging System.

SendMessage: This method simply inserts a new entry inside our table. Again, as mentioned above, you will have to make sure that you check whether the message is an entirely new one i.e. between two users who not communicated in the past, or a reply to an existing thread. You can check that in this fashion:


var prevMessage = context.Messages.Filter(p => (p.ReceiverId == receiverId && p.SenderId == senderId) || (p.ReceiverId == senderId && p.SenderId == receiverId));

GetAllCoversationsForUser: Now, while retrieving the messages, first of all you have to retrieve all those messages where either the Sender or the Receiver user is the current user in context.


var messages = context.Messages.Filter(p => p.SenderId == userId || p.ReceiverId == userId).OrderByDescending(p=>p.MessageId);

Next, you will have to identify which one is the parent message and which ones are the child messages.

Identifying parent message is simple. All you have to do is check whether the ParentMessageId is equal to zero or not.

Below, I have shown the full implementation of how you can retrieve all the child messages for a given parent message.


private readonly List<MessageModel> messageHistory = new List<MessageModel>();

private void GetChildMessages(int messageId, List<MessageModel> lsMessages, int currentUserId)
{
var childMsg = lsMessages.FirstOrDefault(p => p.ParentMessageId == messageId);

if (childMsg != null)
{
messageHistory.Add(childMsg);
GetChildMessages(childMsg.MessageId, lsMessages, currentUserId);
}
}

In this way, using a recursive method, we can collect the child messages for a given parent message. All the child messages are available in the list “messageHistory “.

GetNewMessagesCount: This method is basically used to check if a user has any new unread messages or not so that you can show a new notification for him.

SetMessageViewed: Finally, this method is used to update a message viewed identifier once a message has been viewed by the user. One important thing to make note of on writing implementation of this method is that you have to make sure the message Sender is not the same as current user in context.


if (!childMsg.IsViewed && currentUserId!=childMsg.SenderId)
{
messageService.SetMessageViewed(childMsg.MessageId);
}

If you do not check for this, you might end up updating messages to “viewed” even when the sender views the messages.

That’s about it for our Inbox Messaging System. Simple isn’t it?

Do not hesitate to put in your questions or confusions regarding this implementation if you have any on the comments section below and I would love to help you out.

Thanks!

Get Random Date From A Date Range

This is a quick trick to generate a random date between two date ranges.

First, create a function that generates a random number between two given values:


private static int RandomNumBetween(int smallNum, int bigNum)
{
Random rnd = new Random();
int randomValue = rnd.Next(smallNum, bigNum + 1);
return randomValue;
}

Now, use this function to generate any kind of date ranges like this:


var DOB = new DateTime(RandomNumBetween(1970, 1999), RandomNumBetween(1,12), RandomNumBetween(1,30));

 

C# : Write DataTable To CSV

Here’s a quick code to write data from database to a CSV format file in C# .NET.

I find this function really useful as I frequently come across this scenario where I have to create a report for the client.

Once our data is loaded into a DataTable, this function can be used.


public static string ToCsv(DataTable table)
{
var result = new StringBuilder();
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(table.Columns[i].ColumnName);
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}

foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append("'"+row[i].ToString());
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}

return result.ToString();
}

The first “foreach” loop creates table headers and the second loop writes data from rows.

Hope this will be useful to you as well ­čÖé

 

Visual Studio: Converting a Class Library to Portable Class Library

Before you even start asking GOOGLE about how to convert a Class Library Project to Portable Class Library (PCL) in Visual Studio, why don’t you try to do it by yourself?

In fact that is the best approach for this scenario because if you try to google for the solution, you will realize that none of the suggested answers actually agree.

@ StackOverflow:

@GeeksWithBlogs

The main reason the solutions provided do not work is that because of the difference in Visual Studio versions. The solutions vary by Visual Studio version: 2012, 2013, 2015 and now 2017.

Solution

As I said before, this will require some manual work from your side.

You will have to manually compare the differences between regular Class Library project and a Portable Class Library project.

To do this comparison, first create a new PCL project (no you do not have to move all of your class libraries to PCL project).

Once we have┬á a sample PCL project, we can compare the .csproj file of this project with the class library project’s .csproj file.

So, basically just add/remove the lines that are not available in you class library project from your portable class library project.

Once you have made necessary adjustments, Visual Studio will recognize the Class Library project as a Portable Class Library.

With this approach, you can also convert a Portable Class Library project back to Class Library project as well.

Good luck!

 

Reducing Cyclomatic Complexity Using Delegates

In the previous post we looked at what Cyclomatic Complexity is and why it is important to write programs with low Cyclomatic Complexity. Here I would like to show an example of reducing Cyclomatic Complexity with the use of Delegates.

This post is going to be extremely code intensive so buckle up guys!

Let’s start.

Say we have a few Math functions as below:


private static void Add(int x, int y)
{

}

private static void Subtract(int x, int y)
{

}

private static void Divide(int x, int y)
{

}

private static void Multiply(int x, int y)
{

}

And based on our user’s input, we would like to make proper requests to these methods:


private void Execute()
{
Console.WriteLine("Basic Math Operations");

Console.WriteLine("Enter value 1: ");
var x = Console.ReadLine();

Console.WriteLine("Enter value 2: ");
var y = Console.ReadLine();

Console.WriteLine("Enter operation type: ");
Console.WriteLine("Type A for Add, S for Subtract, D for Divide, M for multiply");

var operationRequested = Console.ReadLine();

if (operationRequested != null)
{
switch (operationRequested.ToUpper())
{
case "A":

break;
case "S":

break;
case "D":

break;
case "M":

break;
}
}
}

This “Execute” function already has Cyclomatic Complexity of 6 because of the 4 switch statements and 1 if condition.

Let’s add some more complexities to this code now.

First to check whether user inputs are proper data type of integer or not I have introduced validation “IsNumeric” which gets executed once.

I have also introduced another validation to check whether user is authorized to make a request or not with “IsUserAuthorized“. This has to be called for each switch case scenario.

So, our code looks like this:


private static void Execute()
{
Console.WriteLine("Basic Math Operations");

Console.WriteLine("Enter value 1: ");
var x = Console.ReadLine();

Console.WriteLine("Enter value 2: ");
var y = Console.ReadLine();

if (!IsNumeric(x) || !IsNumeric(y))
{
Console.WriteLine("Error!! Please enter integer values");
Execute();
}

Console.WriteLine("Enter operation type: ");
Console.WriteLine("Type A for Add, S for Subtract, D for Divide, M for multiply");

var operationRequested = Console.ReadLine();

if (operationRequested != null)
{
switch (operationRequested.ToUpper())
{
case "A":
if (IsUserAuthorized("A"))
{
Add(Convert.ToInt32(x), Convert.ToInt32(y));
}
else
{
Console.WriteLine("User not authorized");
}
break;
case "S":
if (IsUserAuthorized("S"))
{
Add(Convert.ToInt32(x), Convert.ToInt32(y));
}
else
{
Console.WriteLine("User not authorized");
}
break;
case "D":
if (IsUserAuthorized("D"))
{
Add(Convert.ToInt32(x), Convert.ToInt32(y));
}
else
{
Console.WriteLine("User not authorized");
}
break;
case "M":
if (IsUserAuthorized("M"))
{
Add(Convert.ToInt32(x), Convert.ToInt32(y));
}
else
{
Console.WriteLine("User not authorized");
}
break;
}
}
}

These additions have increased the Cyclomatic Complexity level for our code to 12! If we had more switch statements, the complexity would have grown much more higher.

Let’s try to bring down the complexity with the use of Delegates now.

As per MSDN,

“A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.”

Basically, a delegate allows us to pass a method as a parameter to another function which is very useful as we can see below:

Since all of our math functions have same signature, we can create a delegate for them like this:


private delegate void HandleRequest(int x, int y);

Next, let’s add a generic request handler function:


private static void CallRequestHandler(HandleRequest request, string requestType, int x, int y)
{
if (IsUserAuthorized(requestType))
{
request(x, y);
}
else
{
Console.WriteLine("User not authorized");
}
}

The “CallRequestHandler” takes a delegate and request type along with “x” and “y” values as parameters for executing the user requests.

Now all we need to do is use this function in our switch statements by passing proper Math functions as parameters:


switch (operationRequested.ToUpper())
{
case "A":
CallRequestHandler(Add, operationRequested.ToUpper(), Convert.ToInt32(x), Convert.ToInt32(y));
break;
case "S":
CallRequestHandler(Subtract, operationRequested.ToUpper(), Convert.ToInt32(x), Convert.ToInt32(y));
break;
case "D":
CallRequestHandler(Divide, operationRequested.ToUpper(), Convert.ToInt32(x), Convert.ToInt32(y));
break;
case "M":
CallRequestHandler(Multiply, operationRequested.ToUpper(), Convert.ToInt32(x), Convert.ToInt32(y));
break;
}

This drops down the Cyclomatic Complexity of the Execute function to 8 from 12.

Benefit? We are left with much cleaner and easily testable code!

Alright. That’s about it for this post. I hope you guys found it useful and hope to see you incorporate this kind of practice on your coding.

Please pass the comments/feedback/queries as comments below.

Thanks!

Cyclomatic Complexity

Cyclomatic Complexity is a software metric used to calculate the complexity of a program.

It is a measure of number of possible use case flows for a given program’s source code and is directly dependent upon the number of control flow statements (if/else statements and switch cases) within the code.

For example, a method with no control flow statements would have Cyclomatic Complexity  value of 1.

Cyclomatic Value as calculated by Visual Studio for a method that has no control flow statements:

And if we add one control flow statement, the Cyclomatic Complexity value will increase by 1.


private static void Divide(int x, int y)
{
if (x > y)
{

}
else
{

}
}

The code above has Cyclomatic Complexity of 2.

Basically, the Cyclomatic Complexity tells us how much complex our code is.

Since the more complex a code is, the more difficult it becomes to write a Test Case and validate it and so the higher value for Cyclomatic Complexity is usually associated with higher error prone code.

Hence, it is generally considered a good practice for software developers to write programs with low Cyclomatic Complexity.

Notes on Spring.NET DAO Code Configuration

In this short article, we will look at how Dependency Injection for Data Access Objects can be implemented using Spring.NET.

“Data Access support in Spring is aimed at making it easy to work with data access technologies like ADO.NET and Nhibernate in a standardized way.”- Spring.NET

First an interface that exposes the methods that can act on a database.


public interface IShapeDao
{
   DataTable GetShape();
}

Then some implementations for this interface.


// Implementation 1
public class CircleDao: AdoDaoSupport, IShapeDao
{
   public DataTable GetShape()
   {
       var sql = " Select * from tblCircle";
       return AdoTemplate.DataTableCreate(CommandType.Text, sql);
   }
}

// Implementation 2
public class RectangleDao: AdoDaoSupport, IShapeDao
{
   public DataTable GetShape()
   {
       var sql = " Select * from tblRectangle";
       return AdoTemplate.DataTableCreate(CommandType.Text, sql);
   }
}

Notice that no connection strings or database context are provided here.

Now, the Configuration class. Each dependent object will have its own virtual method as below:


[Configuration]

public class MyConfiguration: IApplicationContextAware
{
    public IApplicationContext ApplicationContext { get; set; }

   [Definition(Names="circle"]
   [Lazy]
   [Scope(ObjectScope.Singleton)]
   public virtual IShapeDao CircleDao()
   {
      return new CircleDao();
   }

   [Definition(Names="rectangle"]
   [Lazy]
   [Scope(ObjectScope.Singleton)]
   public virtual IShapeDao RectangleDao()
   {
      return new RectangleDao();
   }
}

Next, all we need to do is initialize the ApplicationContext by passing the required dependency.In the program main process i.e. where the app begins and all the action starts, we initialize the ApplicationContext.


private IApplicationContext context;

public void InitContext()
{
   // Configure Spring programmatically
   var ctx = new CodeConfigApplicationContext();
   ctx.ScanWithAssemblyFilter(a => a.FullName.StartsWith("My.Assemble.Name.Path"));
   ctx.Refresh();
   context = ctx;
}

Finally, we can ask for our object from this context like this:


IShapeDao circleDao = context.GetObject<IShapeDao>("circle");
IShapeDao rectangleDao = context.GetObject<IShapeDao>("rectangle");

This is pretty much all the needed fundamentals for using Spring.NET DAO.

Happy Programming!

Uploading Unknown Format Excel File To A SQL Database

Introduction

Usually it is expected from client side to upload only structured Excel sheets (sheet with defined Column Names and data types for Rows) to load to server. But sometimes you might also require to dump whatever is in the Excel directly to your database. While there is a tool that is provided by SQL Management Studio for importing data from Excel files, this tutorial covers how you can automate such task using C# and .NET framework.

Steps

Two important pieces for uploading excel file of unknown column format to SQL database are:

  1. Reading Data from Excel into a Data Table
  2. Creating Table in SQL Server based on the Data Table

Once these two steps are done, the final step is simply to bulk load the data table into the table in SQL server.

Reading Data from Excel into a Data Table

I am using Excel Data Reader nuget package for this purpose.


/// <summary>
/// Gets a data table based on provided Excel File
/// </summary>
/// <param name="pathToExcelFile"></param>
/// <returns></returns>
public static DataTable GetTableFromExcel(string pathToExcelFile)
{
FileStream stream = File.Open(pathToExcelFile, FileMode.Open, FileAccess.Read);

IExcelDataReader excelReader;
if (Path.GetExtension(pathToExcelFile) == ".xls")
{
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else
{
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}

excelReader.IsFirstRowAsColumnNames = true;

//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
DataTable dt = null;
if (result != null && result.Tables.Count > 0)
{
dt = result.Tables[0];//get first sheet only
}
return dt;
}

Excel Data Reader package supports multiple sheets of Excel to be read into a Data Set at once and also allows other configurations such as: Supporting multiple file formats and Checking Column Names in First Row.

Creating Table in SQL Server based on the Data Table

Now, to generate a “Create Table” query, I found a very useful code on the Stack Overflow site for this purpose.


/// <summary>
/// Generates sql create table query for given data table
/// </summary>
/// <param name="tableName">name of the table to be created</param>
/// <param name="table">data table</param>
/// <returns></returns>
public static string GenerateCreateTableQuery(string tableName, DataTable table)
{
var sqlsc = "CREATE TABLE " + tableName + "(";
for (int i = 0; i < table.Columns.Count; i++)
{
sqlsc += "\n [" + table.Columns[i].ColumnName + "] ";
string columnType = table.Columns[i].DataType.ToString();
switch (columnType)
{
case "System.Int32":
sqlsc += " int ";
break;
case "System.Int64":
sqlsc += " bigint ";
break;
case "System.Int16":
sqlsc += " smallint";
break;
case "System.Byte":
sqlsc += " tinyint";
break;
case "System.Decimal":
sqlsc += " decimal ";
break;
case "System.DateTime":
sqlsc += " datetime ";
break;
case "System.String":
default:
sqlsc += string.Format(" nvarchar({0}) ", table.Columns[i].MaxLength == -1 ? "max" : table.Columns[i].MaxLength.ToString());
break;
}
if (table.Columns[i].AutoIncrement)
sqlsc += " IDENTITY(" + table.Columns[i].AutoIncrementSeed.ToString() + "," + table.Columns[i].AutoIncrementStep.ToString() + ") ";
if (!table.Columns[i].AllowDBNull)
sqlsc += " NOT NULL ";
sqlsc += ",";
}
return sqlsc.Substring(0, sqlsc.Length - 1) + "\n)";
}

Once we have the data and create table script, uploading to database is quite simple and can be achieved with following steps:

  1. Decide upon a table name
  2. Check if it exists or not in the server
  3. Create table if it doesn’t exist
  4. Bulk load data table into your newly created table.