Wednesday, September 5, 2018

Prepare dynamic expression (predicate) to IQueryable ( c# / .NET / Linq)


In the following example, the returning expression is for 'equal' operator. ( you can find other operations like 'GreaterThan','NotEqual' etc). Let 'TEntity' be the entity for which you want to prepare the predicate. Then, the parameter would be

 ParameterExpression parameter = Expression.Parameter(typeof(TEntity));

Lets say for column 'id' you want to create an expression to filter records with value equal to '5'. Then you can prepare the expression as

object valueObject = new object();
valueObject = (int)5;

var _expression = Expression.Equal(Expression.Property(parameter, "id"), Expression.Constant(valueObject, typeof(int)));
var  _lambdaExpression = Expression.Lambda<Func<TEntity, bool>>(_expression, parameter);

This _lambdaExpression can now be used as predicate for your queryable of TEntity as

var filteredList = MyQueryable.Where(_lambdaExpression).ToList();

Additionally, if you want to have AND/OR operations within the expression, you can do it as following.

let _expression1 and _expression2 be two expressions. For AND operation :

var _expression3 = Expression.And(_expression1, _expression2);

This _expression3 can now be used to create the lambda expression.

Note : namespace System.Linq.Expressions.Expression

Thursday, August 23, 2018

Minify js file using Microsoft.Ajax.Utilities.Minifier (c# / .NET)


Apart from inbuilt bundling and minification in MVC we might sometimes need to minify javascript files. You can get 'AjaxMin' from nuget and use it to compress the js file. 


string sourceDirectoryPath = @"C:\sourceFile.js";
string destinationDirectoryPath = @"C:\destinationFile.js";

var minifier = new Microsoft.Ajax.Utilities.Minifier();

var minifiedJSString = minifier.MinifyJavaScript(System.IO.File.ReadAllText(sourceDirectoryPath));

System.IO.File.WriteAllText(destinationDirectoryPath, minifiedJSString);

This code will fetch the source js file from source directory path, minify the text and save it to the destination directory path.

Wednesday, July 4, 2018

Access HttpContext using dependency injection in .net core mvc (c# , .NET CORE)


Add singleton service of IHttpContextAccessor in Startup.cs. 

 //IHttpContextAccessor 
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor,Microsoft.AspNetCore.Http.HttpContextAccessor>();

Then you can resolve IHttpContextAccessor using constructor ( or by using IServiceProvider )
            
private static IHttpContextAccessor _httpContextAccessor;
// constructor
public MyClass(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

or using IServiceProvider

   _httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();


Then, you can access the HttpContext ( or eg. set string in session) as :

 _httpContextAccessor.HttpContext.Session.SetString("key", "value");


Click the link to know about dependency injection using IServiceProvider

Wednesday, June 27, 2018

Resolve Dependency Injection (DI) using IServiceProvider(not in constructor) in .net core mvc (c# , .NET CORE)


Sometime we might need to inject classes which cannot be injected using public constructors (eg.  for internal classes/interfaces injection). 
For this situation, we can use IServiceProvider and resolve other dependencies using it. By default IServiceProviderof course, should be injected using the constructor.

Then the other dependencies can be resolved like the  below source code:

using Microsoft.Extensions.DependencyInjection;

Private IMyClass _myClass;

public MyClass(IServiceProvider serviceProvider)
        {
            _myClass = serviceProvider.GetService(typeof(IMyClass));
            //or 
           _myClass = serviceProvider.GetService<IMyClass>());  
        }

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.