Pages

6 Jun 2012

WCF - Concurrency, Sessions and Throttling

WCF allows different way for Session and Concurrency management.

Session Management: configures how service object life time is managed during client requests.

  • Per Call - a new service instance is made for each method call from client.
  • Per Session - a single instance will cater all calls from a client.
  • Single Instance - all client calls will work under a single instance of service object.


Concurrency Mode: configures how service instances servers multiple client requests at the same time.
  • Single - a single request will be catered by service object, other requests need to wait during this period.
  • Multiple - multiple requests will be processed by service object by spawning threads. This approach is beneficial for good throughput.
  • Re entrant - single requesting client has access to the WCF service object thread, but the thread can exit the WCF service to call another WCF service or can also call a WCF client through callback and reenter without deadlock.



By default WCF services is configured to have Per Call session, Single ConcurrencyMode.

Throttling behavior of WCF helps in putting upper limit for no of sessions, concurrent calls & instances. Following flags are used for this

  • MaxConcurrentCalls
  • MaxConcurrentInstances
  • MaxConcurrentSessions 


23 May 2012

Configure SIP for Voip

Just because Nokia N810 not having GSM  module doesn't mean we cannot make phone calls. N810 has very good support for Session Initiation Protocol. We can use speaker or included headset or Bluetooth devices to make or take calls.

How to configure voipbuster SIP account

  1. menu -> communication -> Internet call
  2. choose add account
  3. in second screen Service : SIP
  4. next screen for username - <voip_username>@voipbuster.com password - <voip-pwd>
  5. next screen for account name - <voip_username>
  6. That's it
Enjoy.

22 May 2012

Week numbers in Outlook 2010

Follow these steps to enable week number display in Outlook 2010

  • File -> options
  • click on Calender
  • Under display options



17 May 2012

Vulnerability vs Threat vs Attack

Basics of Security starts with following keywords

Vulnerability is a hole or weakness of an Operating System or Application. This could be due to design flaw or implementation flaw, which allows an intruder to cause harm.

Threat is something like a disease which affects Operation System or Application. Threat is normally identified by the changes that is makes like signature of binaries/files, registry keys etc..

Attack is techniques used to exploit vulnerabilities of an application.

12 May 2012

Copy column names along with results from MSSQL Management Stuido

Sometimes it helps in copying column names along with query results. This can be turned on/off easily in MSSQL Management Studio easily

Go to Tools -> Options page of Management Studio, then under Query Results -> SQL Server -> Results to Grid, check/ un-check the feature.

What is vshost.exe ?

Right next to Visual Studio build of a CLR executable, we notice another executable ending with .vshost.exe


vshost.exe is a hosting process introduced by Visual Studio, for following benefits

  • helps in creating App domain and associating debugger to that. Normally this is a slow process, however vshost.exe makes this noticeably fast.
  • initializes the debugger for partial trust debugging
  • supports intermediate window for design time expression evaluation.
Still don't wish to have *.vshost.exe next your binary, then go to project properties -> Debug
And un-check the option.

4 May 2012

Vector Vs List

Vectors and Lists are belong to sequence containers of C++ Standard Template Library. Primary difference between two comes from the internal data-structure used by both,

Vector
Internally vector uses a dynamic array (continues block of memory), which grows in forward direction.
This means random access and insertion/deletion in the end is faster. However if we insert/delete at the beginning or middle, operations will take more time as entire contents needs to be pushed/moved.

List
List is realized as (doubly) linked list.
So insertion/deletion any where is faster, which internally works as altering next of linked list nodes. By default list doesn't support random access, and hence search inside list is slower.

30 Apr 2012

Primary key vs Unique key


SQL allows two interesting keywords to decorate a table - Primary key and Unique key. Differences or similarities are as follows,


    • primary key does not allow nulls but unique key does
    • primary key does clustered indexing, whereas unique key does non clustered
    • both can be used for constraints
    • multiple unique keys can be defined for a table

MSSQL Management Studio: Database Diagram problem.

Recently I got an error message in Management Studio with database diagram. Error message is


To solve this:


  1. Right Click on interested database, choose properties
  2. Goto the Files Page
  3. Enter "sa" in the owner textbox.
  4. Save changes.
Alternative (haven't tried yet) is to give privilege by

ALTER AUTHORIZATION ON DATABASE::YourDatabaseName TO sa
GO

26 Apr 2012

Using SqlDataReader on multiple results.

Suppose we plan to execute multiple select query and how do we fetch result using SqlDataReader. Well this can be achieved by using SqlDataReader.NextResult

Example

Create test database and sample tables

create table employee (id int identity(1,1), name varchar(256), primary key(id))
create table employeeaddress (id int identity(1,1), empaddress varchar(256), primary key(id))


insert into employee values('Johan')
insert into employee values('Leon')


insert into employeeaddress values('Eindhoven, The Netherlands')

Now lets fetch results using SqlDataReader, C# program as follows

string cmdText = @"select * from employee;select * from employeeaddress";
            using (SqlConnection sqlCon = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=testDB;Integrated Security=SSPI;"))
            {
                using(SqlCommand sqlCmd = new SqlCommand(cmdText,sqlCon))
                {
                    sqlCon.Open();
                    SqlDataReader reader = sqlCmd.ExecuteReader();
                    int ResultIndex =1;
                    do
                    {
                        Console.WriteLine("Results from table - " + ResultIndex);
                        while (reader.Read())
                        {
                            Console.WriteLine(reader[0]);
                        }
                        
                        ++ResultIndex;
                    } while (reader.NextResult());
                    reader.Close();
                }
            }


25 Apr 2012

Simple shared_ptr implementation


auto_ptr does not allow sharing object, i.e. when auto_ptr is shared ownership transfers to rhs. This ensures that we have only one copy of pointer and pointer will be destroyed when scope is over. A simple auto_ptr implementation

However there are situations where we like to share our object pointer. For such need boost has shared_ptr implementation, my version of shared_ptr implementation is as follows



template <class T>
class MySharedPtr
{


public:
//constructor creates the dynamic interger to hold ref counting
explicit MySharedPtr(T* p = 0):m_ptr(p)
{
pRefCount = new int();
*pRefCount = 1;
}


~MySharedPtr()
{
//destroy only if ref count is 1 else null set member
if(1 == *pRefCount)
{
if(NULL != m_ptr)
delete m_ptr;
delete pRefCount;
}
else
{
m_ptr = NULL;
//decrement the counter when not deleteing object
--*pRefCount;
}

}


MySharedPtr(MySharedPtr<T> & rhs)
{
//during copy construction share the object pointer
// and ref counting pointer
this->m_ptr = rhs.m_ptr;
this->pRefCount = rhs.pRefCount;
//increment the counter as we have one more object now
++*pRefCount;
}


MySharedPtr<T>& operator = (MySharedPtr<T>& rhs)
{
if(this->m_ptr != rhs.m_ptr)
{
if(this->m_ptr != NULL)
{
//if rhs object counter is 1 then delete it otherwise
//decrement rhs counter
if(*this->pRefCount == 1)
{
delete m_ptr;
m_ptr = NULL;
delete pRefCount; 
pRefCount = NULL;
}
else
{
--*(this->pRefCount);
}
}
//assing rhs and increment counter
this->m_ptr = rhs.m_ptr;
this->pRefCount = rhs.pRefCount;
++*(rhs.pRefCount);
}
return *this;
}


private:
T* m_ptr;
//pointer to hold ref counter
int* pRefCount;
};

24 Apr 2012

MS SQL AutoClose

Something that solved one of our big problems AutoClose.

Recently in one of our project we exposed a stateless service with SQL 2005 Express back end. And we ended up with a crazy issue.

Issue is after 5-6 minutes the performance of the service went down. Thought it was in milli seconds, when clients made 100-200 calls, performance hit was visible.

Its like SQL maintains resources for a connection or execution of query, which SQL by default will recycle when there is no activity. This is a good feature, however in our case it proved very costly.

So turned the feature OFF.
create database employees;
alter database employee set AUTO_CLOSE OFF;

23 Apr 2012

Post increment vs Pre increment

Every time when the post increment operator is used it performs two tasks firstly it stores the value of the variable in temporary location (say in a register) and then it increments the value of the variable and save it to the memory location. The incremented value is then transferred from the register to wherever it was assigned.

Apart from that the pre increment does not have to transfer the value That's why it is quite faster than the post increment operator


//pre increment
int a = 1;
int b = ++a; // Now a is 2 and b is also 2.


//post increment
a = 1;
int b = a++; // Now a is 2 but b is 1.

auto_ptr concept extended to work with pool of memory.

Based on the concept of Simple auto_ptr implementation, following example shows class reusing allocated heap memory with the aid of a pool.

Features of this implementation are

  • consumers need not worry of destroying memory.
  • Assignment and copy constructor transfer ownership like auto_ptr
  • Destructor doesn't delete allocated memory, instead pushes memory to pool for reuse.
  • static function ClearPool clears memory pool in end.



class MemMgr
{
public:
MemMgr(char* p)
{
if(NULL == memPool.size())
{
//allocate memory only if pool is not having entries
cout<<"Pool size is zero"<<endl;
pMemory = new char[MemSize];

}
else
{
//dont allocate, reuse from pool
cout<<"Pool size is "<<memPool.size()<<endl;
pMemory = memPool.front();
memset(pMemory,0,MemSize);
memPool.pop_front();
}


strncpy((char*)pMemory, p, strlen(p));
((char*)pMemory)[strlen(p)]=0;
}


MemMgr(MemMgr& rhs)
{
//in copy constructor make sure the ownership is transfered
this->pMemory = rhs.pMemory;
rhs.pMemory = NULL;
}


MemMgr& operator =(MemMgr& rhs)
{
if(this->pMemory != rhs.pMemory)
{
//if rhs is different, push lhs to pool
if(NULL != this->pMemory)
{
memPool.push_back(this->pMemory);
this->pMemory = 0;
}
}
//assign rhs memory to lhs
this->pMemory = rhs.pMemory;
//set rhs pointer to null
rhs.pMemory = NULL;
return *this;
}


~MemMgr()
{
if(NULL != this->pMemory)
{
//dont delete memory, push to pool
memPool.push_back(this->pMemory);
this->pMemory = 0;
}
}
void Print()
{
cout<<(char*)pMemory<<endl;
}


//static function to clear pool in end
static void ClearPool()
{
cout<<"Pool size is "<<memPool.size()<<endl;
if(NULL != memPool.size())
{
void* pMem = 0;
for(list<void*>::iterator iter = memPool.begin(); iter != memPool.end(); iter++)
{
delete [] *(iter);
}
}
}


private:
static const int MemSize = 100;
       //our memory pool implemented with stl::list
static list<void*> memPool;
void* pMemory;
};


//don't forget to initialize static member
list<void*> MemMgr::memPool;

How delete[] works?

Let's consider the following code,

int size = 10;
A* pA = new A[size];
......
delete [] pA;

When we allocate an array of objects with new, allocated memory will have size stored on top of memory layout and then continuous memory for object * size. Now when we do a delete[] with out specifying how many to delete , size  will be read first and then destructor will be called for all objects.

This is again the reason why unexpected behavior when delete [] is used on new.

22 Apr 2012

Pure Virtual Destructor

Pure Virtual Destructor is an interesting concept available in C++, consider the following example


class Base
{
public:
AbstractBase(){}
void print(){}
virtual ~AbstractBase() =0{}
};


class Derived : Base
{
public:
Derived(){}
};


Interesting part is we can make class Base an abstract class with no pure virtual functions other than destructor. And derived class need not implement the pure virtual function of base as well.
Only this we need to make sure is pure virtual destructor always needs an implementation.

Insertion Sort - Sorting an array.

Insertion Sort is one of the ways to sort an array.

void InsertSort(int* arr, int size)
{
int temp = 0;
int j =0;
for(int i = 1; i< size; ++i)
{
temp = arr[i];
j = i-1;
while(j >= 0 && temp < arr[j])
{
arr[j+1] = arr[j];
--j;
}
arr[j+1]=temp;
}
}

MS SQL Delete vs Truncate

Both DELETE and TRUNCATE both can be rolled back when surrounded by TRANSACTION (if the current session is not closed). Other differences are as follows,


Truncate:
  • Truncate is faster and uses fewer system and transaction log resources than Delete.
  • Truncate removes the data by de-allocating the data pages used to store the table's data, and only the page de-allocations are recorded in the transaction log.
  • Truncate removes all rows from a table, but the table structure, its columns, constraints, indexes and so on, remains. The counter used by an identity for new rows is reset to the seed for the column.
  • Truncate cannot be TABLE on a table referenced by a FOREIGN KEY constraint. Because Truncate TABLE is not logged, it cannot activate a trigger.
  • Truncate cannot be rolled back.
  • Truncate is DDL Command.
  • Truncate Resets identity of the table
Delete:
  • Delete removes rows one at a time and records an entry in the transaction log for each Deleted row.
  • If you want to retain the identity counter, use Delete instead. If you want to remove table definition and its data, use the DROP TABLE statement.
  • Delete Can be used with or without a WHERE clause
  • Delete Activates Triggers.
  • Delete can be rolled back.
  • Delete is DML Command.
  • Delete does not reset identity of the table.

MS SQL Primary key vs Unique Key

In MS SQL environment the main differences between a Primary key and Unique key are

  • primary key does not allow nulls however unique key does allow.
  • primary key does clustered indexing, whereas unique key does non clustered indexing.
  • both can be used for constraints.
  • multiple unique keys can be defined for a table, but only a single primary key in a table.

SQL Pattern matching

MS SQL queries allows us to play with strings (pattern matching).
Let's create an employee table and insert values,


create table employees (id int identity(1,1), name varchar(256), primary key(id))


insert into employees values('James')
insert into employees values('Leon')


//now select will give following values
select * from employees
1 James
2 Leon 
  • if we need to query names starting 'J', we can use '%' to replace one or more characters. 
select name from employees where name like 'J%'
James

  • '%' can replace one ore more characters, however if we want to replace one character use '_'
select name from employees where name like '_eon'
Leon
  • if we want to query for names with a letter ranging between a group use '[]' 
select * from employees where name like '[h-k]%'
1 James
  • if we need to query for name with a letter not in a range use '[^]'
select * from employees where name like '[^h-k]%'
2 Leon