Monday, 27 April 2015

Object Oriented Programming in JavaScript

JavaScript supports Object Oriented Programming but not in the same way as other OOP languages(c#, c++, php, Java, etc.) do. The main difference between JavaScript and the other languages is that, there are no Classes in JavaScript whereas Classes are very important for creating objects. However there are ways through which we can simulate the Class concept in JavaScript.
Another important difference is Data Hiding. There is no access specifier like (public, private and protected) in JavaScript but we can simulate the concept using variable scope in functions.
Object Oriented Programming Concepts
  1. Object
  2. Class
  3. Constructor
  4. Inheritance
  5. Encapsulation
  6. Abstraction
  7. Polymorphism

Preparing the work space

Create a new file "oops.html" and write this code on it. We will write all our JavaScript code on this file.

<html>
<head>
 <title>JavaScript Object Oriented Programming(OOPs) Tutorial</title>
</head>
<body>
<script type="text/javascript">
//Write your code here.....
</script>
</body>
</html>


1) Object
Any real time entity is considered as an Object. Every Object will have some properties and functions. For example consider a person as an object, then he will have properties like name, age, etc., and functions such as walk, talk, eat, think, etc. now let us see how to create objects in JavaScript. As mentioned previously there are so many ways to create objects in JavaScript like:

//1)Creating Object through literal
var obj={};
//2)Creating with Object.create
var obj= Object.create(null);
//3)Creating using new keyword
function Person(){}
var obj=new Person();

We can use any of the above way to create Object.

2) Class
There are no classes in JavaScript as it is Prototype based language. But we can simulate the class concept using JavaScript functions.

function Person(){
 //Properties
 this.name="aravind";
 this.age="23";
 //functions
 this.sayHi=function(){
  return this.name +" Says Hi";
 }
}
//Creating person instance
var p=new Person();
alert(p.sayHi());


3) Constructor
Actually Constructor is a concept that comes under Classes. Constructor is used to assign values to the properties of the Class while creating object using new operator. In above code we have used name and age as properties for Person class, now we will assign values while creating new objects for Person class as below.

function Person(name,age){
 //Assigning values through constructor
 this.name=name;
 this.age=age;
 //functions
 this.sayHi=function(){
  return this.name +" Says Hi";
 }
}
//Creating person instance
var p=new Person("aravind",23);
alert(p.sayHi());
//Creating Second person instance
var p=new Person("jon",23);
alert(p.sayHi());

4) Inheritance
Inheritance is a process of getting the properties and function of one class to other class. For example let’s consider "Student" Class, here the Student also has the properties of name and age which has been used in Person class. So it's much better to acquiring the properties of the Person instead of re-creating the properties. Now let’s see how we can do the inheritance concept in JavaScript.

function Student(){}
//1)Prototype based Inhertance
Student.prototype= new Person();
//2)Inhertance throught Object.create
Student.prototype=Object.create(Person);
var stobj=new Student();
alert(stobj.sayHi());

We can do inheritance in above two ways.

5) Encapsulation
Before going on to Encapsulation and Abstraction first we need to know what Data Hiding is and how can we achieve it in JavaScript. Date hiding is protecting the data form accessing it outside the scope. For example, In Person class we have Date of Birth (dob) properties which should be protected. Let's see how to do it.

function Person(){
 //this is private variable
 var dob="8 June 2012";
 //public properties and functions
 return{
  age:"23",
  name:"aravind",
  getDob:function(){
   return dob;
  }
 }
}
var pobj=new Person();
//this will get undefined
//because it is private to Person
console.log(pobj.dob);
//Will get dob value we using public
//funtion to get private data
console.log(pobj.getDob());

Wrapping up of public and private data into a single data unit is called Encapsulation. The above example is the one that best suites Encapsulation.

6) Abstraction
Abstraction means hiding the inner implementation details and showing only outer details. To understand Abstraction we need to understand Abstract and Interface concepts from Java. But we don't have any direct Abstract or Interface in JS.
Ok! now in-order to understand abstraction in JavaScript lets take a example form JavaScript library JQuery. In JQuery we will use
$("#ele")
to select select an element with id ele on a web page. Actually this code calls negative JavaScript code
document.getElementById("ele");
But we don't need to know that we can happy use the $("#ele") without knowing the inner details of the implementation.

7) Polymorphism
The word Polymorphism in OOPs means having more than one form. In JavaScript a Object, Property, Method can have more than one form. Polymorphism is a very cool feature for dynamic binding or late binding.

function Person(){
 this.sayHI=function(){}
};
//This will create Student Class
function Student(){};
Student.prototype=new Person();
Student.prototype.sayHI=function(l){
 return "Hi! I am a Student";
}
//This will create Teacher Object
function Teacher(){};
Teacher.prototype=new Person();
Teacher.prototype.sayHI=function(){
 return "Hi! I am a Teacher";
}
var sObj=new Student();
//object is instance of Person or not
//if not it won't execute our alert code.
if (sObj instanceof Person) {
    alert("Hurry! JavaScript supports OOps");
}

JavaScript supports Object Oriented Programming (OOP) Concepts. But it may not be the direct way. We need to create some simulation for some concepts.

About the author:
Deepak Shinde is technology lover and is important part of Systems Plus technology Think Tank. He works in systems Plus and actively contributes to technology. He can be contacted at: deepak.shinde@spluspl.com

Thursday, 16 April 2015

Bindings in WCF

WCF comes with number of built-in bindings and this article describes advantages and disadvantages of each of these bindings. It will help you to choose appropriate bindings depending on your requirements and create endpoints for communicating to clients.

What is WCF Bindings?

Bindings decide how WCF service endpoint should communicate with clients. 

Each WCF service endpoint requires binding to be specified, if not set explicitly it uses default basicHttpBinding. It gives communication details and defines below things.

Protocols: specifies what type of security can be used like reliable messaging or transaction context.
Encoding: specifies type of message encoding like binary or text.
Transport: specifies communication transport to be used like HTTP or TCP.

WCF Predefined Bindings

basicHttpBinding

basicHttpBinding is best when you have traditional ASMX(Active Server Methods) web services and needs to be replace with WCF. It supports text as well as MTOM encodings and it does not support WS-* standards like WS-Addressing, WS-Security and WS-ReliableMessaging.

basicHttpBinding uses HTTP or HTTPS protocols. You can configure SSL for Transport Layer security with basicHttpBinding.

WsHttpBinding
This is secure and interoperable bindings uses SOAP over HTTP. With WsHttpBinding messages are encrypted by default and achieve message level security. It supports reliability, transactions and security over internet. It supports HTTP or HTTPS protocols and text as well as MTOM encoding.

The difference between basicHttpBinding and WsHttpBinding is WsHttpBinding does support WS-* standards like WS-Addressing, WS-Security and WS-ReliableMessaging whereas basicHttpBinding does not.

wsDualHttpBinding 
wsDualHttpBinding is best when you required bidirectional communication with client. In some scenario when client makes call to WCF service, after processing of long running request service has to call client application for example updating shipment details to client application.

It supports reliability, transactions and security over internet. It supports HTTP or HTTPS protocols and text as well as MTOM encoding. You can implement Duplex message exchange pattern with wsDualHttpBinding.

webHttpBinding 
webHttpBinding is best when you wish to implement RESTful WCF service. This is secure and interoperable binding which sends information directly over HTTP or HTTPS without creating SOAP messages. It allows HTTP request to use plain old XML (POX) style messaging which reduces the message size on wire compare to SOAP messages.

netTcpBinding 
netTcpBinding is best when WCF service and its clients are in intranet infrastructure. As it supports only TCP protocol and not HTTP so service cannot be accessed over internet.

This is secure binding is used to send binary encoded SOAP messages with in intranet computers. It supports reliability, transaction and security. If your using netTcpBinding and host WCF service in IIS, you need to make some settings on system and IIS this article will help you for required settings.

netNamedPipeBinding 
When your WCF service and its clients reside on same computer netNamedPipeBinding is the best choice and gives best performance over other bindings. This is secure bindings. Binary encoded SOAP messages are sent over named pipes.

See how to implement netNamedPipeBinding in WCF services.

netPeerTcpBinding 
netPeerTcpBinding is best when you require more security for peer to peer communication as netTcpBinding does not provide it. It is secure binding and supports TCP protocols.

WsFederationHttpBinding
It is secure and interoperable binding supports federated security. It supports HTTP and HTTPS transport protocols as well as text and MTOM encodings.

netMsmqBinding 
netMsmqBinding is best when you have to execute service operations in queued manner. Service requests are placed in queue and executed one by one. With netMsmqBinding service operations will always be one way and does not return any response to client.

This is interoperable bindings and can be used on existing MSMQ applications that use COM or Application Programing Interface(API)

In real time applications you have to use multiple bindings for one service endpoints. For example internet applications should be able to access service through HTTP request at same time the back office application should be able to access service by netTcpBinding or netNamedPipeBinding to get performance benefits.

About Author:
Dhairut Dholakia is technology lover and is important part of Systems Plus technology Think Tank. He works in systems Plus and actively contributes to technology. He can be contacted at: dhairut.d@spluspl.com

Friday, 10 April 2015

Dealing with Challenging Clients

You come across all types of people, in every organization. And if you are in the field of IT support or consulting, a huge part of your job is to handle client’s behavior. Though you may feel the urge to disregard such clients completely, this is not how it would work in a realistic business scenario.  Especially if you are a growing business, clients are hard to come by and losing one just isn't the option. Also, such a scenario would create bad relations and as you all know, a bad word spreads in a blink of an eye in our small corporate world.

A challenging client is basically the type of client who would challenge your work, question your ability and knowledge of the field, disagree to your opinions, and blame you for his / her ignorance about the project in hand. Sounds like a nightmare, right? And if experiences of people are to be believed, it really is a nightmare. But experiences also present many learning curves, which should be utilized in a positive manner.

Below are some of the key points to be remembered when dealing with challenging customers (some points are useful to avoid difficult situations with clients) :

1. Focus on the client
Concentrate on how the clients feel and make them your first priority. If they request something to be done urgently, do not tell them that you have a lot of work and that it is impossible. Instead, acknowledge their request and try to understand why the request is urgent.

2. Let clients know that they are not alone
In case your clients face some difficulties or problems related to work and which you are aware are faced by other clients too, make your clients aware about this. This will make them realize that they are not alone. Also, share your past experiences with them which might be helpful.

3. Acknowledge the client’s feelings
At times, clients who are displeased might demand something which you might not agree to. In such situations, completely agreeing or disagreeing with them might only make situations worse. Instead, try to acknowledge their thoughts and shift the conversation towards a feasible solution.

4. Communicate effectively
Communication is the most important factor when handling difficult situations and even otherwise. Make sure you chose your words carefully. Even though you are really angry at something the client said or did, don’t demonstrate that to the client. Be soft-spoken and try to make him/her understand the problems you are facing. Hence the chances of the situation getting worse because of you are significantly reduced.

5. Document everything
It is very important to document all the meetings and discussions you have had with the client. When the progress of the project takes an ugly turn, most of the clients turn to the consultants and start blaming them. If you have everything documented, you can always point to the notes and inform the client of what was initially decided.

6. Be honest
Honesty is very important to maintain the trust and good relation with client. Even if you are unsure of certain aspects of the project or your work is getting delayed due to some reason, it is beneficial to just be honest with the client and try to explain the situation to him / her. If you hide or lie to them, they will lose trust in you which is not good for long term.

7. Be patient
There will be many situations when dealing with clients where your patience would be put to test. In such panic circumstances, it is very common for clients to get hyper and blame consultants for whatever is going wrong. It is important to keep your calm at such times and patiently make the client understand that you are trying your best. This behavior would go a long way in maintaining good relations with the client and also handling the situation at hand.

8. Remember, you can’t win an argument
Trying to argue with your client will only make him / her dislike you. This does not mean you can let him / her speak to speak to you rudely. You must help them see your point of view rather than forcing them to see your point of view. If you think it is your fault, admit it. Even if it is not your fault, say things like “Sorry if I haven’t explained something clearly”. This will make your clients more willing to listen to your point of view. 

Please note that this is not a full-proof plan to deal with customers. Every situation brings its own surprises with it. However, remembering these points will help you tackle the situation with more confidence and you will also be able to maintain good relations with the client. 

About Author:
Kintu Racca is a consultant in Systems Plus Pvt. Ltd. Within Systems Plus, she actively contributes to the areas of Technology and Information Security. She can be contacted at kintu.r@spluspl.com

What is SOLID?

SOLID are five basic principles which help to create good software architecture. SOLID is an acronym where:-

  • S stands for SRP (Single responsibility principle)
  • O stands for OCP (Open closed principle)
  • L stands for LSP (Liskov substitution principle)
  • I stands for ISP ( Interface segregation principle)
  • D stands for DIP ( Dependency inversion principle)

“S”- Single responsibility principle

Meaning: An object should only have one reason to change; the longer the file or class; the more difficult it will be to achieve this. 

Have a look at the code below, can you guess what the problem is?

class Customer
{
public void Add()
{
try
{
// Database code goes here
}
catch (Exception ex)
{
System.IO.File.WriteAllText(@"c:\Error.txt", ex.ToString());
}
}
}

The above customer class is doing things WHICH HE IS NOT SUPPOSED TO DO. Customer class should do customer data validations, call the customer data access layer etc , but if you see the catch block closely it also doing LOGGING activity. In simple words its over loaded with lot of responsibility. So tomorrow if add a new logger like event viewer I need to go and change the “Customer”class, that’s very ODD.

“O” - Open closed principle

Meaning: Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
Let’s continue with our same customer class example. I have added a simple customer type property to the class. This property decided if this is a “Gold” or “Silver” customer.
Depending on the same it calculates discount. Have a look at the “getDiscount” function which returns discount accordingly. 1 for Gold customer and 2 for Silver customer.

class Customer
{
private int _CustType;

public int CustType
{
get { return _CustType; }
set { _CustType = value; }
}

public double getDiscount(double TotalSales)
{
if (_CustType == 1)
{
return TotalSales - 100;
}
else
{
return TotalSales - 50;
}
}
}

The problem is if we add a new customer type we need to go and add one more “IF” condition in the “getDiscount” function, in other words we need to change the customer class.
How about rather than “MODIFYING” we go for “EXTENSION”. In other words every time a new customer type needs to be added we create a new class as shown in the below. So whatever is the current code they are untouched and we just need to test and check the new classes.

“L”- Liskov substitution principle

Meaning: If S is a subtype of T, then objects of type T may be replaced with objects of type S (in other words, objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, and so on).

public class Rectangle
{
protected int _width;
protected int _height;
public int Width
{
get { return _width; }
}
public int Height
{
get { return _height; }
}

public virtual void SetWidth(int width)
{
_width = width;
}   
public virtual void SetHeight(int height)
{
_height = height;
}
public int getArea()
{
return _width * _height;
}

public class Square : Rectangle  // In an "is a" relationship, the derived class is clearly a
//kind of the base class
{
public override void SetWidth(int width)
{
_width = width;
_height = width;
}

public override void SetHeight(int height)
{
_height = height;
_width = height;
}
}

public void AreaOfRectangle()
{
Rectangle r = RectangleFactory(); // Returns the rectangle type object
r.SetWidth(7);
r.SetHeight(3);
r.getArea();
}

So can you tell me the out put of the  r.getArea(); method . Yes very simple the expected output is

public  Rectangle RectangleFactory()
{
return new Square();
}

One thing i want to mention about the  RectangleFactory() is that , this method is now exposed to you. But think as if you are getting the Rectangle object just by using a factory dll or from any service where you have no idea what type of rectangle object will be return.

So what’s wrong there? Remember as I said earlier
Now the solution is to manage the class inheritance hierarchies correctly. Let’s introduce another class

public class Quadrilaterals
{
public virtual int Height { get; set; }
public virtual int Width { get; set; }
public int getArea()
{
return Height * Width;
}
}
public class Rectangle :Quadrilaterals
{

public override int Width
{
get { return base.Width; }
set { base.Width = value; }
}
public override int Height
{
get { return base.Height; }
set { base.Height = value; }
}  

}

public class Square : Quadrilaterals  // In an "is a" relationship, the derived class is clearly a
//kind of the base class
{
public override int Height
{
get { return base.Height; }
set { SetWidthAndHeight(value); }
}

public override int Width
{
get { return base.Width; }
set { SetWidthAndHeight(value); }
}

private void SetWidthAndHeight(int value)
{
base.Height = value;
base.Width = value;
}
}

“I” - Interface Segregation principle

Meaning: The principle states that no client should be forced to depend on methods that it does not use
Now assume that our customer class has become a SUPER HIT component and it’s consumed across 1000 clients and they are very happy using the customer class.

Now let’s say some new clients come up with a demand saying that we also want a method which will help us to “Read” customer data. So developers who are highly enthusiastic would like to change the “IDatabase” interfaceas shown below.

interface IDatabase
{
void Add(); // old client are happy with these.
voidRead(); // Added for new clients.
}

Now by changing the current interface you are doing an awful thing, disturbing the 1000 satisfied current client’s , even when they are not interested in the “Read” method. You are forcing them to use the “Read” method.
So the better solution would be to create a new interface rather than updating the current interface. So we can keep the current interface “IDatabase” as it is and add a new interface “IDatabaseV1” with the “Read” method the “V1” stands for version 1.

interface IDatabaseV1 : IDatabase // Gets the Add method
{
Void Read();
}

“D”- Dependency inversion principle

Meaning:
  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Abstractions should not depend on details. Details should depend on abstractions.
About the author:
Akash Singh Verma is a consultant in Systems Plus Pvt. Ltd. Within Systems Plus, he actively contributes to the areas of Technology and Information Security. He can be contacted at akash.v@spluspl.com

Thursday, 2 April 2015

SQL Server Security

Secure Installation:

1.Review installation requirements, system configuration checks, and security considerations for a SQL Server installation.

2. SQL Server Setup installs the following software components required by the product
a. SQL Server Native Client
b. SQL Server Setup support files

3.Physical security protect all related systems, media, backups, etc

4. Never place database unprotected on public net
a. Or on unprotected private net
b. Firewall protected
c. S/W mediating database access

5. Install on NTFS file system (Do not use FAT32 file system)
a. This allows securing the files appropriately

6. Do not install on a domain controller

7. Latest code is most secure code
a. Apply latest service packs and security patches

8. SQL Server utilities to configure SQL Server

Configuration Options:

1. Authentication mode
a. Use Integrated Security
More secure protocols (Kerberos and NTLM)
Kerberos allows for delegation
Allows for password policy enforcements
Typically does not require application to store passwords
b. If using Mixed mode (Standard SQL Authentication)
Use SSL to encrypt network traffic
Use strong passwords
Never use blank passwords

2. Login auditing
a. Audit failed login attempts at the very least

3. Disallow ad hoc queries

4. Choose static ports for named instances avoid opening UDP1434 at firewall
a. Media security including backups
b. Assume damage possible and have aggressive backup policy
c. Test disaster recovery system

5. Turn on appropriate level of auditing
a. Track critical user actions at a minimum (i.e: sysadmin actions, server role membership changes, password changes, login-related activity)
b. Keep overhead minimum

6. Encryption options
a. Protect sensitive data over the wire use SSL, IPSEC, VPN, etc.
b. File-level encryption

7. SQL supports Encrypted File System

Mid Tier to Database Connection:

SQL Security

1. End users authenticate at application level
a. Database trusts application to authenticate users

2. Connection to database using standard SQL login
a. Use low-privileged login account
b. Use strong passwords
c. Leverage SSL to protect authentication over the wire

3. Secure mid tier credentials data protection APIs
a. Encrypted using service’s credentials
b. Only same service account can decrypt

4. Disadvantages
a. Credentials storage required
b. Standard SQL authentication weaker than Windows authentication

5. Advantages
a. Works across firewalls and nontrusted domains
b. Connection pooling possible

Integrated Security

1. Run ASP.NET as low-privileged account

2. End users authenticate at application level

3. Database trusts application to authenticate users

4. Connection to database in context of ASP.NET account
a. Recommend low-privileged domain account
b. Alternatively, local Windows account on SQL Server box with same username and password
c. Useful if connection made across nontrusted domain
d. Account has only necessary runtime permissions in SQL
e. Is not a high-privileged account; not a sysadmin

5. Advantages
a. No storage of credentials needed
b. No need to pass credentials over the wire to SQL
c. Running as low-privileged account, minimizes potential damage from compromise
d. Connection pooling possible as single account is used

Preventing SQL Injection:

Attacker allowed sending SQL queries to backed end data store

Example:

Application Code:

var shipcity;
ShipCity = Request.form (“Shipcity”)
var sql = “SELECT * FROM OrdersTable
WHERE ShipCity = “’ + Shipcity + “’”;

Normal user: Inputs REDMOND in the form query to back-end is:

SELECT * FROM ORDERSTABLE WHERE SHIPCITY = ‘REDMOND’

Malicious user: Inputs REDMOND’ DROP TABLE ORDERTABLE – in the form  
Query to the back-end is:

SELECT * FROM ORDERSTABLE WHERE SHIPCITY = ‘REDMOND’ 
DROP TABLE ORDERSTABLE—’

SQL injection

1. Why SQL injection works?
a. Connection made in context of higher-privileged account
b. Application accepts arbitrary user input

2. Mitigating SQL injection
a. Validate all user input
b. Define set of valid input, accept only that
c. Reject all invalid input
d. Avoid using dynamic SQL in stored procedure
e. Run applications in minimally privileged contexts
f. Never run as sysadmin

Tips for App Dev Teams

1. Understanding various security issues
a. Different threat vectors, attack scenarios
b. Awareness of issues such as SQL injection, cross-site scripting, buffer-overflow attacks
2. Construct threat analysis for each S/W component
a. Enumerate component boundaries
b. Analyze component data flow, interfaces and interactions
 - Can it be compromised?
 - What data flows in and out?
c. Compromise could be through different kinds of threats
Escalation of privileges, tampering of data, spoofing, information disclosure, code injection
3. Code Review
 a. Develop Code review checklists
 b. Guideline for common security issues
 c. Directed code reviews — based on threat analysis
4. Generic file reviews — top-down approach.

About Author:
Amit Gupta is technology lead in Systems Plus Pvt. Ltd and keen to resolve challenges using his technical skills. He actively contributes to technology and can be contacted at: amit.gupta@spluspl.com