Session vs Cookies

For naive programmers the discrimination between session and cookies is usually perplex and sometimes even programming aficionado baffles in term of their internal implementation. General notion is cookies exist on client-side while session are created on server side and this is affirmative but there are some other aspects of this concept should be understood to fully exploit session and cookies capabilities and to take careful and right decision about where to store your confidential data.

First, concise definition would be, session and cookie is used to communicate data between client and server by sending and receiving involved data that become a part of protocol’s header and exchanged throughout the communication. These are used to overcome the problems related to the stateless nature of HTTP. Cookies can persist longer than a single session even if browser is closed contrary to session. In cookie, all stored data for a particular website or domain is exchanged however only session id in sessions.

The first major difference is related to the creation location.Session are created on server-side while cookies are on client-side. But where to keep data and why? The strategy can suggest that the data required more on client side than server side should be in cookies and the data that to and fro rapidly should be in session. Well, this is not entirely true.

The best approach towards where to store data is to view it form the storing and communication technique that must be helpful for system optimization and performance as these two are a goal of every system so the paradigm and anything could hurt these two should be avoided. The data huge in size and could slow the effective communication must not be at client-side as every time request sent to server all stored data in the cookie sent also as a part of it. Conclusively , we must maintain or optimized communication latency.

In the seek of communication latency and talking about small amount of data may be in KBs, can I put my password in cookies as good password’s length could be between 12 to 20 characters and that is manageable but what if my session hacked and intruder gets my password? Here security plays its role.  You hardly want your confidential data to transmit over unreliable channel because there could be loophole anywhere between your system and server and if your protocol header snatched you can become another victim of cybercrime. One of the modern security techniques is signing or encrypting cookie with some secret key or hash to make your cookie data more difficult to perceive. Therefore, Second point is to never put your confidential data in cookies unless you have dire desire or it should be encrypted as complex as can.

There are many other reason to decide where to put data with mediocre significance. Like, if you want to implement “Remember me” functionality, it leads you to store data in cookie. Some users are very careful and do not allow any cookie to be created on client side that’s why many popular website preferred to keep data in session. Some websites are cookie less as they keep session ID in query string but it is the least secure methodology as it is prone to be hacked unless it is encrypted nicely.

In the conclusion, there could be many factor that can influence your decision. Above all points should be considers and there could be many more. It is always system architect call to how the system should be design.


SQL Injection and its prevention

Security Features != Secure Features

In SQL injection, malicious SQL statement enter as an input which is the part of any system SQL query and produce unpleasant or unwarranted changes in system. 

Let say we have following query 
“SELECT * FROM Users WHERE UserId = ” + txtUserId; 
And as a value of txtUserId , user enter 105 or 1=1, now query become 
SELECT * FROM Users WHERE UserId = 105 or 1=1 
And user got unauthorized access 

Another example is system has following query 
“INSERT INTO Students VALUES (‘” + FNMName.Text + “‘, ” + LName.Text + “)” 
and user enter Robert’); DROP TABLE STUDENTS; — as a value of FNMName.Text 
In the result, query become 
INSERT INTO Students VALUES (‘Robert’); DROP TABLE Students; –‘, ‘Derper’) 
And as a consequences your students table has been dropped. 

How to prevent SQL injection

  1. Never trust on any data. Always escaped and synthesized all kind of data before insertion.  
  2. Always catch or exception and paraphrase for user with friendly message. Do not show actual details of occurred errors.  
  3. Your integrity of system highly depends on authorized access. Define roles, rights, permission for all user. Create long, difficult password. Set password expiry for moderate time period.  
  4. Apply latest security patches. Vulnerabilities are discovered by black-hat programmer so your system should be updated.  
  5. User over tools, like firewall, anti-virus, spam-filters, ISA server, etc to secure your system.  
  6. Never use inline queries or dynamic SQL. Stored procedures are the best choice.  
  7. Do not expose unnecessary database operation to public. Only provided the data which is intended to by the system.  
  8. Use RSA or any other good encryption technique to encrypt your data like password, credit card number and other confidential data. 

Software Development Methodologies

Waterfall Model – An Orthodox approach:
It is iterative process used to adopt in software development. It is still suitable in a paradigm where rapid development is not required and requirements are not changing continuously and going back from one stage of cycle to previous stage is not very costly. 


  • Requirements. A detailed, written description of the software to be built. 
  • Design. The process of planning the implementation details of a software project. 
  • Implementation. The process of coding, testing, and debugging the individual parts of the software being developed. 
  • Integration and verification. The phase when the various portions of the software are being brought together for integration and broader testing. 
  • Installation and maintenance. The end of the SDLC, when the new software is deployed and moves into a cycle of post-release fixes and adjustments. 

The waterfall model approaches quality by suggesting that the more time spent analyzing and designing the software, the more likely flaws will be uncovered early in the process and subsequently avoided in the downstream development of the code. Critics argue that this methodology does not work well in practice because critical details of the program or application cannot truly be known until the development team is progressing through implementation. Additionally, since the model is stringent about finalizing specifications before coding begins, there is very limited opportunity for including any early customer or beta tester feedback into the release cycle, which constrains the team in addressing customer needs in a timely manner. Finally, complete end-to-end testing does not occur until late in the cycle, which adds risk to the quality of the application, when integration of critical elements begins. 

Agile Methods of Software Development

Agile are lightweight methods, emphasized on self-organizing, teams, face-to-face communication, lightweight documentation, and frequent releases.Follow will be discuss two famous Agile methodsScrum:
Scrum is an agile methodology. It does not address the practices required to create “goods” of any kind, but instead gives us the process that will take us from the inception of a vision to the final product, regardless of the actual development process. The Scrum process doesn’t tell you how to create quality. It shows you what the quality is, where your problems are, and challenges you to fix them. Scrum, like most agile methods, encourages small, self-organizing teams that work on a well-defined set of development tasks during a short release cycle. Scrum itself does little to prescribe any specific methods for managing the quality of the software being developed. 

Extreme programming(XP):
Extreme programing is an agile software development methodology. It gives us a process with which to create software in an agile and productive way. It deals with, though doesn’t specialize in the management of the development process, and focuses mostly on the engineering practices required to deliver software, with quality. 

  • Developer testing. Developers continually write, and often start by writing unit tests, which must pass for development to continue. 
  • Code refactoring. Developers are always restructuring the system without altering behavior to simplify, reduce duplicity, and add additional flexibility. 
  • Pair programming. Developers work in pairs to reduce coding mistakes. 
  • Continuous integration. Features are integrated and built every time a key development task is completed. 
  • Coding standards. Rules are established that emphasize communication through the code, which developers are required to follow. 

Take Away:

When  mixing Scrum and XP, which is by far the most common mix, you use all of Scrum’s management artifacts, e.g. Sprints, daily Scrums, retrospectives, burn down charts, and so on, and add XP’s TDD, refactoring, pair-programming and JIT design via User Stories.

  • XP works in iterations smaller than scrum. 
  • XP is far more customer-oriented than Scrum. 
  • XP welcomes changes on all stage will Scrum does not allow changes in requirement when sprint backlog is finalized.

Codeigniter with Model-View-Controller (MVC) architecture

Codeigniter with the power of MVC

PHP as being open source enjoys a lot of free available frameworks. Some are very huge and some are small. People adopt according to their needs.

I personally like Codeigniter by Ellis Lab due to its splicity and minimal setup time. . Sometime you have very strict timelines and you need Agile or rapid development. Here you feel a need for a framework that could be configure with zero or minimal configuration,structured and complete enough to fulfill your requirements. Codeigniter is suitable in this scenario.

For every framework, it is always considerable to choose best architecture for its organization, extensibility and management. Codeigniter uses Model-View-Controller MVC which is the most popular among all for PHP.

MVC is architecture to control access and customized provided information in desired fashion. Codeigniter comply it very well and developers enjoy coding their applications due to its simplicity and power of MVC.

To implement MVC in PHP, you have to have Object Oriented Programming (OOP) concepts. I will not OOP concepts are because these are out of the scope for this article but I am writing another detailed article on this topic and will release soon.

Something about Model – View – Controller (MVC)

  • Controllers receive all requests from users and call models and views to render the information as directed in the request.
  • Models are modulation for any database or other system. Models do not play role in every request received by controllers. Actually controllers manage model when there is any change occurred in model. Views are not aware of any change in models, its controller responsibility to notify related views about the change.
  • Views are customized output representations, generated as per current models state and request sent to controller.

MVC is controlled and desired separation or abstraction for result outputs. User never has access to models or views, he/she only interact with controllers. Controllers are the component, which received calls, sends commands to models to know about its state, do any mention change in models, call views to tell about changes in models and render customized output for views according to direction provide in the call and current state of models. One controller can call many models and views.
There are many variations in MVC architecture.

MVC in Codeigniter

Codeigniter has very simple directory structure. In application folder, you create your web application. Inside application, controller will go to controllers folder, model to models folder and views to views folder. There are many other folders in application folder for many other purposes.

A big attraction for MVC in PHP is to handle web request smartly with SEO-friendly, User-friendly or clean URL.

Consider following request to Codeigniter web application


After index.php, first parameter is controller name (users), second is function name inside controller (update) and last one is the parameter (97), which will be provided to the function in the controller.

With the help of some tweaks in your .htacess, you can get rid of index.php in above URL and can get neat and clean URL as follow


But how models, views, controller are accessed in Codeigniter. There are some rules you have to follow to route the web request to correct controller. For the sample URL

  • There must be user.php in application/controllers folder.
  • User.php must have a class named Users (Note he first letter is capital here).
  • User class must be inherited by CI_Controller class( A parent controller class for all controllers).
  • Users class must have public function named update.
  • Update function must have a parameter, to which the last parameter (97) will be provided.

Function name and parameters are optional in URL. If function name is not provided, Codeigniter will take index as a function name by default. The number of parameters function has, the number of parameters you have to provide in the URL and they will be passed to the function’s parameters as they occurred in URL

Codeigniter load any model through model method of load object as follow


After that you will have class level variable Applicants_model ($Applicants_model) which is the object for model class Applicants_model. Now you can call any method from Applicants_model class with the variable you got, as follow


To load Applicants_model


  • There must be applicants.php file in application/models folder.
  • applicants.php must contain Applicants_model class.
  • Applicants_model class must be inherited by CI_Model class (A parent model class for all models).
  • Applicants_model class must have function named insert.

Same for views, controllers can call views as follow

$this->load->view('applicants_view', $data);

Second parameter is an array of data that will be passed to the view. Second parameter is optional and if it is array it will be extracted and its each key will be available as a variable in called view. Mainly its keys are extracted by PHP extract function.

To load applicants_view

  • There must be applicants_view.php file in application/views folder.

As an architecture overview, any web request received by Codeigniter is directed to the controller specified in web request’s URL. This eliminates the direct access to models and views and make controllers the sole responsible to trigger and control all operations. Then, to handle operations for views and models, functionality is provided to controller to load any model and view for interaction. By loading any model, a controller now has rights to do any changes, get any information or check any expected changes. After that, controller can notify any view about this change, pass information to customize it as needed and render it as an output. Clearly model and views are unaware of each other, controller is the glue, which becomes channel to transit any change between views and models.

Often neglected areas of Web development

Being web developer you want your product to be successful. Following are the areas which is usually ignored or provide poor attention but these areas are major stakeholders in the success of optimized web application.

Target audience:

Identify your audience. Your design should be according to the need of your audience. If IT based company design should be corporate but if it is any musical store then it should be colorful, full with melodies. If website contains financial transaction, then security and session handle must be given extra attention.

Software development model:

Usually, web developers are so into coding that they start coding without thinking how they will proceed. Before start development, try to structure your project in modules. Estimate time and resources and analyze which software development model is suitable for your project. There are a lot of models and pattern for software and web development especially in open source. As web development is subset of software development, so you can software development mode full or partially per need, as often all steps are not applied. Some widely used models are Agile Programming, Prototype, RAD. Be careful with Timelines. It will be yours biggest success if you finish on time with desire product.

Requirements gathering and specification:

Obviously you should have all requirements in your hand. The functional or must-meet requirements should be gathered and compiled in the start but non-functional or good-to-have can be added later. Note that these requirements must be freeze or finalize before start development. Any new requirement must be accommodate in next major version like 2.0 or in a minor version like 1.0.1. Create a UML, ERD, DRD or some initial design that will help you in future for development and testing.


Many people are so eager to move their project to production that they neglect the importance of testing. As soon as development complete, they start SQA team to finish testing and provide sign-off. It’s up to you. You can go as deeper as you want in testing. Test your code in the way that all scenarios should be covered. Create test cases with all possible values and scenarios of dynamic variables. Perform code analysis and code coverage, identify bottlenecks. Analyze execution plan and optimized queries.


One step that is necessary in web development is the promotion of your site. You can promote you site in different blog, forums, community sites, wikis. You can write your own blogs or blog can be a part of your web where people can come and write something. SEO (Search Engine Optimization) is a technique use for site promotion. Now-a-days the widest used approach is through social networks like Facebook and Twitter.


In last you must monitor your site carefully. You can do logging in your site to get possible errors. Watch your web logs daily in the start. Also, you should have a feed-back form on your web as you can get the problems of users and will fix or add in next release. No one is perfect and there is always a room for mistakes and weaknesses so evolution never ends but your product will be maturing gradually.

PHP password generator

Simple password generator class in PHP. Allow users to choose what kind of characters should be in the password

After long and hectic day with office work in the night I relax to do some coding (by the way I spend 80% of my office time doing coding :P). So, I decided to write a “Create Password” utility. This is just for the sake of code something because there are many fancy libraries for this purpose already available, as open source rocks!!!

First I thought what password could have, alphabets small and capital, number and special character but user must have flexibility to exclude any of this option so I came up with a class having all options.


abstract class Options
	const SmallAlphabets = 0;
	const CapitalAlphabets = 1;
	const IsNumeric = 2;	
	const IsSpecialCharacters = 3;

I made it abstract, as I did not need to implement any function inside the class. It worked as enumeration.

Then I created a function to allow user to enable what options he wants and set options in constructor as the set on the generation of class object. User can omit code to disable any option


function UseInPassword($options){
/** set correponding bit value to 1 to keep track of allowed options */
$this->optionsTrack = $this->optionsTrack | pow(2,$options);

Here, I did a trick, I played with logical operators and I set the bit in an integer corresponding the value any option had in Options class.

GetPassword is the main function. User called that from outside. I wanted to generate all characters equally. For example, password length is 6 and user enable only SmallAlphabets, then 6 small alphabets will be created but if SmallAlphabets and IsNumeric is enabled then 3 small alphabets and there number. What if user enables all? There are four options and length is 6. 6 is not divisible by 4 so we cannot generate all options equally. We have to take reminder to generate more characters equal to reminder to fulfill password length. So each option generated once to make 4 characters and code will generate 2 more character in the sequence of their values in Options class. As follow

Count the options set by user by checking corresponding bit


for($i = 0 ; $i < 5 ; $i++){			
			$mask = $this->optionsTrack & pow(2,$i);
			if($mask > 0){
				$allowedOptions .= strval($i);

Get count of characters per option


$initialOptionCount = intval($this->passwordLength / $optionsCount);	
$reminder = $this->passwordLength % $optionsCount;	

Get final count as if password length is not completely divisible by the count of allowed option then we have to generate some character one more time


$finalOptionsCount = $initialOptionCount + ($i < $reminder ? 1 : 0);

Complete commented code is below and on git Hub and easy to understand.

Complete PHP code for Password generator


// namespacess
namespace junaid\code\pword\generator;

/** enumeration class to define what password would have and what would not have */
abstract class Options
	const SmallAlphabets = 0;
	const CapitalAlphabets = 1;
	const IsNumeric = 2;	
	const IsSpecialCharacters = 3;

/** passsword generator class */
class Generator{
	public $passwordLength;
	public $optionsTrack;	
	/** below you can update a list of special character 	 
	 	and add or remove characters according to your will */ 
	private $specialCharacters = [
	function __construct(){
		$this->passwordLength = 7;
	/** enable different type of characters by passing corresponding Options value
	 	See in constructor how I enable all options by four calls of this function */
	function UseInPassword($options){
		/** set correponding bit value to 1 to keep track of allowed options */
		$this->optionsTrack = $this->optionsTrack | pow(2,$options);
	function GetPassword(){
		if(0 == $this->optionsTrack)
			exit("No parameter set....");
		$optionsCount = null;
		$allowedOptions = "";
		/** count what are the options set by user by ANDing corresponding bit value with power of 2 */
		for($i = 0 ; $i < 5 ; $i++){			
			$mask = $this->optionsTrack & pow(2,$i);
			if($mask > 0){
				$allowedOptions .= strval($i);
		/** get count of characters per option need to be created */
		$initialOptionCount = intval($this->passwordLength / $optionsCount);		
		$reminder = $this->passwordLength % $optionsCount;
		$passwordArray = array();

		/** generate characters and put in array */
		for($i = 0 ; $i < strlen($allowedOptions) ; $i++){
			/** if provided lenght is not divisble by the count of allowed options
			  	some options need to be created more than other to get no of character 
			  	equal to password length */			
			$finalOptionsCount = $initialOptionCount + ($i < $reminder ? 1 : 0);
			for($j = 0 ; $j < $finalOptionsCount ; $j++){
				$passwordArray[] = $this->GetSingleCharacter($allowedOptions[$i]);
		/** shuffle */
		return implode($passwordArray);
	/** return character on the basis of provided option value */
	function GetSingleCharacter($switch)
			case Options::CapitalAlphabets:
				$tmp = chr(rand(65,90));
			case Options::SmallAlphabets:
				$tmp = chr(rand(97,122));
			case Options::IsNumeric:
				$tmp = rand(0,9);
			case Options::IsSpecialCharacters:
				$tmp = $this->specialCharacters[rand(0,sizeof($this->specialCharacters)-1)];
		return $tmp;
	function __desctruct(){

use junaid\code\pword\generator as ns;
$obj = new ns\Generator;
echo $obj->GetPassword();


How to create BizTalk pipeline custom component?


I worked on a project named Levy. In this project we were getting transactions from another system in a flat file. BizTalk read that file from FTP location. Sometimes, we had huge number of transactions and flat file took 30 to 45 seconds to be written, and BizTalk started to read the file while the file was still writing by another system. This scenario caused partial file read situation.

We could not be sure about the exact timing of generation of file so we could not schedule any service window or sets polling on FTP receive location. This scenario occurred seldom so we decided to through error when it occurred and inform ITD Ops to run job again (which was creating file on FTP location).

Records in flat file were delimited by carriage return (\r\n as it is on windows) and fields inside every record were positional. We noticed that whenever partial file read by BizTalk, there was carriage return in the last, as file read line by line and every line had carriage return in the end. Therefore, we decided not to put carriage return after the last line, and check applied in receive pipeline, if carriage return was present at the end of the stream, it was partial read, otherwise flat file was good.

For this purpose, I created receive pipeline component for disassemble stage, and in case of partial file, I sent email to ITD Ops and wrote error in event log.

Extending Flat file disassembler component using FFDasmComp

In this tutorial, I will inherit may class library to FFDasmComp and implement few basic methods from IBaseComponent and IDisassemblerComponent interfaces. I cannot share actual project as it is condemned by policies of my current employer. I am going to simulate what I did with a sample project.

Open visual studio and create new project. Select C# and select Class library in template section. Give the name of the project as you want. I gave mine as CheckLevyFileFormat. I also rename class file to “CheckPartialFileRead“ as I never like “Class1” as a class name.


Now you have to add references of two assemblies. Right click on references in solution explorer, click add reference, click on browse tag, go to your BizTalk server 2010 installation directory(Normally in program files) and add Microsoft.BizTalk.Pipeline assembly


Do the same for Microsoft.BizTalk.Pipeline.Components. This assembly can be found inside BizTalk server 2010 installation directory or could be inside Pipeline Components folder, inside the installation directory. Check both locations.

Now, we need to add some code. First some namespaces required.

using System.IO;
using System.Xml;
using Microsoft.BizTalk.Message.Interop;
using Microsoft.BizTalk.Component.Interop;
using System.Runtime.InteropServices;
using Microsoft.BizTalk.ParsingEngine;
using Microsoft.BizTalk.Component;
using System.Text;

Later, we need to implement three basic functions of IBaseComponent

public new string Name
        return &amp;quot;CheckPartialFileRead Disassembler&amp;quot;;

public new string Version
        return &amp;quot;1.0&amp;quot;;

public new string Description
        return &amp;quot;Check Levy Partial File Read Disassembler&amp;quot;;

The name you defined will appear when you add your new developed component in toolbox.

Now, the most important function is Disassemble. Following is the code which is quite self-explanatory. We are getting file content and break them into lines and check each line. Let say, length of each line must be 12(originally it was different in Levy project). As I do not remove empty entries when I split string into string array ( by passing StringSplitOptions.None in String.Split function), if there is “\r\n” in the end then last line will be an empty string and exception will be thrown.

public new void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
        //jha1-- read flat file contents
        StreamReader _streamReader = new StreamReader(pInMsg.BodyPart.GetOriginalDataStream());
        int _lineNumber = 0;

        string _levyContents = _streamReader.ReadToEnd();

        //jha1-- break it into lines
        string[] _lineArray = _levyContents.Split(new string[] { &amp;quot;\r\n&amp;quot; }, StringSplitOptions.None);

        //jha1-- check all lines. All lines lenght must be 12 according to Levy spces
        //jha1-- this will also cover
        foreach (string _line in _lineArray)

            if (12 != _line.Length)
                throw new Exception(string.Format(&amp;quot;Error at line no. {0}. Length of all lines must be equal to 12&amp;quot;, _lineNumber));

        _streamReader.BaseStream.Position = 0;
        base.Disassemble(pContext, pInMsg);
    catch (Exception ex)
        System.Diagnostics.EventLog.WriteEntry(&amp;quot;Disassemble - Exception&amp;quot;, ex.ToString());
        throw ex;

Full code can be found in attached zip.

Assign SNK to make this assembly strong name. Build the project, GAC the assembly and place into Pipeline Components folder in your BizTalk server installation directory.


Now create New BizTalk empty project and add new receive pipeline


Now right click on toolbox and click choose items


Click on BizTalk Pipeline Components tag and you will see your custom created pipeline component listed there.


It the component and it starts to appear into toolbox.


No you can use it like any other component. Drag and drop it into Dissemble stage.

Now to test it, I created a sample schema with three fields and sample orchestration that will just receive and print XML.



Build your solution, assign strong-name key, deploy on BizTalk, configure and apply your pipeline to receive location and test results.

Whole project is available on following location