Monday, May 28, 2018

Simple generic model mapper in c#


During development we can have many cases where model mapping is required. YES, there are already many tools for this purpose eg Automapper. Well, below you can find a generic function which maps a model to another.

TSource is the source class and TDestination is the destination class. The function returns an object of TDestination class. For properties in destination class, it tries to map available mapping values in source class.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace MapperTools
{
    public static class ModelMapper 
    {        
        public static TDestination Map<TSource, TDestination>(TSource sourceObj) where TDestination : class, new()
        {
            TDestination returnObj = new TDestination();
            foreach (var returnPropertyInfo in returnObj.GetType().GetProperties())
            {
                var sourcePropertyInfo = sourceObj.GetType().GetProperty(returnPropertyInfo.Name);
                if (sourcePropertyInfo != null)
                {
                    var sourceValue = sourcePropertyInfo.GetValue(sourceObj);
                    returnPropertyInfo.SetValue(returnObj, sourceValue);
                }                
            }           
            return returnObj;
        }

    }
}

Use :
var destinationModel = ModelMapper.Map<SourceModel, DestinationModel>(sourceModelObject);

Thursday, January 25, 2018

LINQ with DataTable ( c# / .NET )



In .NET, LINQ has made us easier to query and manipulate most of the data sources along with DataTables. DataTables can be parsed as enumerable and hence can be easily manipulated by LINQ. This has made developers very easier to play with data of the datatable. Fetching, filtering and selection of data within DataTables would not be so easy without linq. The below sample code in console application proves it. The code populates some dummy data inside a datatable, uses linq to filter the datatable and uses the filtered values to display it in console window. You can take this reference as implement it in your code.

Note: The following namespaces are required : 

using System.Data;
using System.Linq;

Code :

class Program
    {
        static void Main(string[] args)
        {
            // Datatable variable 'dt' with columns ID,Name
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Name"typeof(string));

            // loading dummy data to the datatable
            DataRow dr1 = dt.NewRow(); dr1["ID"] = 1; dr1["Name"] = "John"; dt.Rows.Add(dr1);
            DataRow dr2 = dt.NewRow(); dr2["ID"] = 2; dr2["Name"] = "Peter"; dt.Rows.Add(dr2);
            DataRow dr3 = dt.NewRow(); dr3["ID"] = 3; dr3["Name"] = "Misha"; dt.Rows.Add(dr3);
            DataRow dr4 = dt.NewRow(); dr4["ID"] = 4; dr4["Name"] = "Pema"; dt.Rows.Add(dr4);

            // converting datatable to enumerable and using lambda expression to get filtered enumerable data row collection
            // it filters rows from datatable with name starting from "Pe"
            EnumerableRowCollection<DataRow> filteredRows = dt.AsEnumerable().Where(x => x.Field<string>("Name").StartsWith("Pe"));

            // accessing the enumerable row collection using foreach
            foreach (var row in filteredRows.AsEnumerable())
            {
                int id = row.Field<int>("ID");
                string name = row.Field<string>("Name");
                // display the result in console
                Console.WriteLine("Name : " + name + "  with ID : " + id);

            }

            // accessing specific FirstOrDefault record using lambda expression with a filter for field "ID"
            //it picks first or default row with ID having value "4"
            DataRow specificRecord = filteredRows.AsEnumerable().FirstOrDefault(x => x.Field<int>("ID") == 4);
            int specificID = specificRecord.Field<int>("ID");
            string specificName = specificRecord.Field<string>("Name");
            // display the result in console
            Console.WriteLine("\nSpecific record Name : " + specificName + " with ID : " + specificID);

            Console.ReadKey();
        }
    }

Sunday, January 21, 2018

Best practices to be followed by software developers


  • Know the purpose of your project/task.

It is very important to understand the requirements before we starting to code. If you are aware of your task, you can plan your work flow, write efficient code and finish it on time.  You should know what your program is meant to do and how you are going to do it. You also need to have some ideas on what are the best tools for your job. Additionally, you can also think of frameworks, programming languages, application type ( web, desktop  etc) which suits best for your task.

  • Proper and meaningful naming of classes,variables and functions

Naming of classes, variables and functions are very important in order to write understandable and maintainable code. You should make a habit of providing a related name for them. For example, if you are writing a helper class to get user data from data source, you can name your class like 'UserDataHelper'. Also the same applies for functions and variables. Random naming can lead you in confusion and make it difficult to understand the code logic. You can follow certain predefined patterns like camel casing, pascal casing etc.

  • Write understandable Code with proper comments

It is a good practice to write comments for functions,variables or any other important part of code to provide the basic idea of it. In software development life cycle, since we have to work in a team, we have to write codes which other developers can also understand. Therefore, it is always good to write a brief note on what the code snippet or the function is about. Also, proper indentation and spacing makes your code clean and easily readable. Additionally, We can also generate help document file if we write comments for the classes and functions properly. We can use tools like SandCastle to generate chm document file.

  • Make your code reusable (Code Refactoring)

Refactoring of codes is one of the best practices in programming. Reuse of common function for a common logic leads to writing fewer codes. The common function can have defined arguments and return some result which can be adapted by multiple calling sources. For example, if we need user information in many places, we can make a common function named as 'GetUserInformation', write the logic inside this function and use it. This too helps in code maintainability. It is a bad practice to write common logic in different places (i.e code duplication). It will create a blunder while implementing any changes dependent to this common logic. If not refactored, we need to fix these changes in each and every duplicate references of the logic.

  • Make your code dynamic / configuration of hard coded values

Hard coded texts and numbers like connection strings and keys should be strictly prohibited inside the code. If not done so, even small changes can lead to recompilation of software and hence can cost you time and money in your professional career. Therefore, it is better to have these values dynamically in either databases or in configuration files which you can access and implement in your code. Thus, these values can be changed and adapted by the system easily without affecting the existing system.

  • Make your code flexible for further extensions

A good software developer always thinks about potential requirements before developing the system. In our practical life, it is very obvious that the software will have further versions,extensions and upgrades. Hence it is one of the best practices to make your code open for further implementations.

  • Classify and group your classes based on their tasks

Grouping of classes is very important for developers in order to separate their tasks and working layers. A software might need to cover many areas of the project and integrate everything inside it. For example, a web application for online food ordering system can have multiple areas like user management, product management, order management, payment methods management etc. In order to make stable and maintainable system we have to separate these areas inside our software by classifying them into groups. We can create multiple class libraries for work units and further sub divide the tasks into unique groups. For example, that can be done using grouping of classes under specific namespaces ( packages in java).      

  • Handle the errors properly

Development along with error handling is also a critical part of software development. We develop the software based on certain logic but we also need to take care of the potential errors and exceptions that might occur during run time of the software. We can use try catch block to try our codes and catch any exceptions and further process them accordingly.

  • Always perform developers test

It is very important to test the program first by the developer himself. Before handing the project to test for quality assurance, developers should test their codes if it gives corresponding output and the logic is met. These can be very helpful for prevention of potential bugs which might be later reported by quality assurance. It will save both time and money.

Saturday, December 30, 2017

Implement google map inside iframe


This blog is about implementing google map in your website using an iframe. Integrating map in website has never been so easy but now we can do it in just a moment. Here are the steps on how you can use google map inside your iframe.

  • Open maps.google.com in your browser.
  • Search your map location which you want to show in your website.


For example, I searched Frankfurt,Germany



  • Click menu button --> Share or embed map





  • Then Click 'Embed Map' tab. you can find an iframe link for your map.




Thursday, December 21, 2017

Web Application Vs Desktop Application


Web Application

  • Hosted in central server.
  • Easy maintenance, customization, integration and upgrade.
  • High scalability, accessibility and sharing.
  • Less resources required for clients. A compatible browser like Chrome or Firefox is enough.
  • Platform independent. Any sort of device within the network and a browsing application is enough.
  • High dependency on network ( internet or intranet )
  • Application failure can cause whole system down and affect all clients.
  • Hosting Servers need to be powerful and hence can be expensive( also online web hosting packages can be comparatively expensive)
  • Slow application development and complicated installation/hosting.

Desktop Application

  • Application installed on local machine ( i.e on client's computer)
  • Independent of networks and also able to work offline.
  • Faster to develop and install.
  • Secured due to local application installation
  • Highly compatible for softwares regarding hardwares
  • Requires manual installation by each client
  • Scalability limited due to resources
  • Local storage and resource usage eg. hardwares and memory
  • Low data portability.


Anyway, web and desktop applications have their own pros and cons. They have their own importance based on requirements and should be developed corresponding to the situation. We
cannot just rank any one of them as first or second.

Lets suppose if your clients are world wide spreaded and you need to perform frequent communication, data sharing or need to work on common business framework, then its good to have web application.

But lets suppose you want to build an application which will access your hardware (i.e camera, microphone, graphics card etc) or lets say you don't have a powerful central server which is able to hold multiple requests from your clients, you can think of a good desktop application which will use your client's resource for the application performance and you can use your server as a central database server.

So, based on the infrastructures you have and also the business requirements from your client, you have to choose the efficient type of application.

Wednesday, December 20, 2017

Select all files inside a directory/folder (c# / .NET)


The below function implements the inbuilt libraries in .net to get all possible files inside a folder/directory. No matter how many number of folders or child folders it contains, it searches all the folders and returns a list of all file paths. It is a recursive function and hence can be a good example for the beginners to understand how recursive function works. 

        // Returns List of file paths for given search directory path.
        public List<String> SearchFiles(string searchDirectoryPath)
        {
            try
            {
                //declaration of list of full filepaths
                List<String> fileList = new List<String>();

                // fetch all files in the directory
                foreach (string file in Directory.GetFiles(searchDirectoryPath))
                {
                    fileList.Add(file);
                }

                // recursive function call for other directories inside of the current directory
                foreach (string directory in Directory.GetDirectories(searchDirectoryPath))
                {
                    fileList.AddRange(SearchFiles(directory));
                }

                //return the list of filepaths
                return fileList;
            }
            catch (Exception ex)
            {
                // throws exception if caught
                throw ex;
            }
        }


Call this function to get list of full file paths like below :


var allFiles = SearchFiles(@"D:\YourFolder");

Note : You will need  System.IO to use Directory class.

ConnectionStrings and AppSettings value from config file. ( c# / .NET)


We have faced the issues and difficulties of hard coded strings and values in our application several times. Keys, connection strings, user credentials and other dynamic settings are not supposed to be hard coded during application development. If done so, they can causes many limitations to our application and even small changes might require recompilation of application and several human hours for development and deployment.

Hence, in our application, we can put these dynamic settings in a config file and read it from there. In .net, We have a library System.Configuration to read these settings and connection strings. Below you can find the code implementation of config file as well as the library in c#.

Code implementation in config file :


<connectionStrings>
<add name="_NameOfConnectionString_" connectionString="_ConnectionString_" providerName="System.Data.SqlClient" />
</connectionStrings>

<appSettings>
    <add key="_key1Name_" value="123" />
    <add key="_key2Name_" value="abc" />
</appSettings>

To access these configuration values in our code, we can write our code as following.

Code implementation in class file :


//used namespace
using System.Configuration;

// you can access the appsettings in your code like below
string key1Value = ConfigurationManager.AppSettings["_key1Name_"];
string key2value = ConfigurationManager.AppSettings["_key2Name_"];

// you can access the connection string in your code like below
string connectionstring = ConfigurationManager.ConnectionStrings["_NameOfConnectionString_"].ToString();