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.