Pages

Saturday, February 27, 2016

Difference between Abstraction and Encapsulation

One of the most confusing concept for developers to understand is the difference between abstraction and encapsulation. This is because the definition seem to say the same thing using different words.

Abstraction is defined as the process of  generalization thus showing only what is necessary.
Encapsulation on the other hand is defined as process of hiding the unnecessary details.

A real world example of abstraction and encapsulation is TV and a remote.

TV hides the complex circuitry inside it. This is similar to encapsulation. Remote provides us an interface to operate the TV without knowing the internal details. This is similar to abstraction.

In programming, encapsulation is achieved by using getters , setters and access modifiers. Also, every method is encapsulation as it hides the internal details.

Abstraction is achieved by using abstract classes and interfaces. They provide a common implementation which is used by derived classes thus providing generalization.


Thursday, February 25, 2016

Implement SQL EXISTS and IN operator using LINQ

LINQ (Language Integrated Query) is a set of features that extends query capabilities to language syntax of C# and Visual Basic.

In this post, we will see LINQ implementation of EXISTS condition and IN operator used in SQL.

Implement IN using LINQ:

    IN operator is used in SQL to check whether a value is contained in the sequence defined using IN operator. The syntax is as follows:

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)

Two important aspects of this operator is that it needs a column name(column_name in this case) and a set of values(value1, value2,... in this case) with which the column value is compared.

In LINQ, a similar implementation looks like below. It uses the Contains extension method

IEnumerable str = from c in db.table_name
        where new List(){value1,value2,...}.Contains(c.column_name) 
        select c;


Here db is the datacontext this is defined using the LINQ to SQL classes.

Implement EXISTS using LINQ:

    EXISTS operator checks whether at least one value satisfies the condition.

SELECT *
FROM customers
WHERE EXISTS (SELECT *
              FROM orders
              WHERE customers.customer_id = orders.customer_id);

The above query will select all results from customers if the sub query returns at least one result.

In LINQ, a similar implementation looks like below. It uses the Any element operator
if(db.Test1s.Any(s => s.name == "abc"))
{
   var str = from c in db.Test1s
             select c;
}
Here, the condition inside Any is equivalent to subquery and the statement inside if is equivalent to the main query in sql.

Saturday, February 20, 2016

Async and Await Keyword in C#

Async and Await keywords are used together to run a method asynchronously(not multi-threaded).  An async method will be run synchronously if it does not contain an await keyword. An async method either returns void or a task.

With these keywords, we run methods in an asynchronous way. Threads are optional. This style of code is more responsive. A network access can occur with no program freeze.

Eg: In the following example, the task run asynchronously. Thus, the two console.writeline statements are executed before the task completes.

using System;
using System.Threading.Tasks;
using System.Threading;
internal class Program
{
    private static void Main(string[] args)
    {
        var task = DoWork();
        Console.WriteLine("Task status: " + task.Status);
        Console.WriteLine("Waiting for ENTER");
        Console.ReadLine();
    }

    private static async Task DoWork()
    {
        Console.WriteLine("Entered DoWork(). Sleeping 3");
        // imitating time consuming code
        // in a real-world app this should be inside task, 
        // so method returns fast
        Thread.Sleep(3000);

        await Task.Run(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("async task iteration " + i);
                    // imitating time consuming code
                    Thread.Sleep(1000);
                }
            });

        Console.WriteLine("Exiting DoWork()");
    }
}
Output:
Entered DoWork(). Sleeping 3
async task iteration 0
Task status: WaitingForActivation
Waiting for ENTER
async task iteration 1
async task iteration 2
async task iteration 3
async task iteration 4
async task iteration 5
async task iteration 6
async task iteration 7
async task iteration 8
async task iteration 9
Exiting DoWork()

Friday, February 19, 2016

Setting Up Multithreading in PHP

Multi-threading in PHP is a very useful feature to take advantage of multi-core processors that is common today. However, multi-threading is not enabled by default.

To set up multi-threading in PHP, follow the following steps.

1. Check the PHP Extension Build for the php version you are using:

 After you have set up your website, go to the link:

localhost:8080/?phpinfo=1

The port number depends on the port you have used, it may be default 80 or any other port number
Look for PHP Extension Build in that page. Check the VC number. For me, its VC11. VC stands for Visual C++, the compiler version that was used to build the version of PHP that you are using. It is interesting to note that PHP which is itself a programming language is built using C and C++. Thus, a compiler need to be used to compile C code.

2. Go to http://windows.php.net/downloads/pecl/releases/pthreads/:

Click on the link above and select and download the latest version of zip file that has the same VC number as that of php version that you are using. For VC11, its 2.0.9. I downloaded php_pthreads-2.0.9-5.6-ts-vc11-x64.zip as I am using a 64 bit computer.

3. Extract the zip.

Move php_pthreads.dll to the php\ext\ directory.
Move pthreadVC2.dll to the php\ directory.

4. Change php.ini file

Open php\php.ini and add

extension=php_pthreads.dll

5. Restart your web server