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 IServiceProvider, of 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.

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();

Monday, December 11, 2017

Get end day of the month ( jquery / javascript)


This is a simple workout to find the end day of the month for selected date in javascript. Below is the workout on how you can do it.

Lets suppose for May 2017, you want to find the end of the month. On you javascript code you can write the following.

var _Year = 2017;
var _Month = 5;
var _date = (new Date(_Year, _Month, 0, 0, 0, 0));
var endOfMonth = _date.getDate();

endOfMonth is the end day of the month for given year and given month. You can change the year and month yourself or make it dynamic based on arguments by creating a function.

For end of month in sql check the link : http://iamfixed.blogspot.com/2017/11/get-end-of-month-in-mssql-2008-r2-2012.html

jquery ajax cache false ( MVC / c# / jquery / ajax )


Not reaching debug point on jquery ajax call



It may happen that we are using jquery ajax call and the program does not reach debug point in your controller action. This happens when ajax cache is enabled. Disabling of the cache during your ajax call can solve this problem. Below you can see an example.


$.ajax({
                url: _your_url,              
                cache: false,
                success: function (result) {
                    // _success_
                },
                error: function (req, err) {
                   // _error_
                }
            });

Enable the cache only when your ajax call returns the same result even on multiple requests. But if you need to get fresh data from controller action each time on your ajax call, better disable the cache.

Friday, December 8, 2017

Zero (or any character) Padding in javascript / jquery


This is a small manual function written in javascript to pad a certain character to a string. In practical, the string usually can a number which needs to be formatted in order to display properly. These numbers can be days, months or year for a date viewer or any number which follows a padding pattern before some operations.

    // obj : string you want to pad.
    // _lenght : length of you padded result string
    // paddingChar : the padding character which you want to add
    function Padding(obj, _length, paddingChar) {

        var str = String(obj);             
        var returnStr = "";
        if (str.length < _length) {
            for (var i = str.length ; i < parseInt(_length) ; i++) { returnStr += paddingChar; }
        }

        return returnStr + str;
    }

Call the function like this :

var result = Padding(12,5,'0');

It should return '00012'.

Monday, December 4, 2017

CRM Dynamics - ExecuteMultipleRequest error


The request channel timed out while waiting for a reply after 00:01:59.8499880. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.



Set the time out for OrganizationServiceProxy . By default, the timeout is 2 minutes. i.e :

_yourOrganizationProxy.Timeout = new TimeSpan(0,10,0); // sets timeout for 10 minutes


To understand further about executing multiple requests from CRM SDK, check the following link :
https://msdn.microsoft.com/en-us/library/jj863631.aspx

Thursday, November 30, 2017

Simple function to check if the number is prime (c# / .NET)


The function is for the beginners as a sample function to check if the input number is a prime number. It takes a number as argument and returns a boolean result. I have used a very basic algorithm to check if the number is prime. Also, negative numbers are neglected.

public bool IsPrime(int number)
        {
            if (number < 2)
                return false;
            else if (number <= 3)
                return true;

            for (int i = 2; i < number; i++)
            {
                if (number % i == 0)
                    return false;
            }
            return true;
        }

Further, you can use the following facts and optimize above function to find if the number is prime.
  • The number divisible by itself and by 1 is a prime number.
  • 2 is only the even prime number. 
  • if the sum of individual digits of the number is divisible by 3, then the number is divisible by 3
  • We do not consider 0 and 1 as a prime number.
  • Except 5, no numbers ending with 5 is prime.


Override 'Equals(object obj)' Function in a class (c# / .NET)


Lets suppose 'MyClass' is the name of class for which you want to override 'Equals(object obj)' function. In order to override this function, we also need to override 'GetHashCode()' function. For further information you can check the links below :

https://msdn.microsoft.com/en-us/library/system.object.gethashcode(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.object.equals(v=vs.110).aspx
https://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden


You can override the function as below.

public class MyClass
    {

        // This function will override the Equals(arg) function when called for MyClass Object.
        public override bool Equals(object obj)
        {

            bool yourReturnBoolean = base.Equals(obj); // write your logic to define this boolean value here.

            return yourReturnBoolean;
        }

        // This function will override the GetHashCode() function
        public override int GetHashCode()
        {
            return base.GetHashCode(); // logic to calculate the hash code
        }
       
    }


Now let's create an object for the class and call 'Equals(object obj)' function.

MyClass obj = new MyClass();           
bool booleanResult = obj.Equals(destinationObject);


Try it yourself and see the result.