Unit testing with Mock Objects

.NET, C#, NUnit, Rhino Mocks No Comments »

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A developer creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.

We use Mock object for NUnit testing if we have 2, 3 or more layer architecture.
In programming terms mock objects are objects that “imitate” some other objects, claiming to have the same attributes, methods etc. like the original.

Rhino Mocks allows you to easily create mock objects and setup a wide range of expectations on them using strongly typed notation instead of compiler-opaque strings.

To mock an object, its class MUST implement an interface.

Public class Car : ICar
{
  public int StartEngine();
  …
  // More methods to be implemented
}
MockRepository mockRepository = new MockRepository();

MyCar = mockRepository.CreateMock<ICar>();

Here is the scenario and source code in C# for demonstration.

We have one solution and 2 projects, representing 2 layers.
Project: DataLayer which gets some information from xml file, database or some other web service, …
DataLayer project has one class: PersonDAL.

using System;
using System.Collections.Generic;
using System.Text;

namespace DataLayer
{
    public class PersonDAL
    {
        private string _name;
        private string _id;
        private List
 lista = new List
();

        public PersonDAL(string name, string id)
        {
            _name = name;
            _id = id;
        }

        public List
 CreateList()
        {

            lista.Add(new PersonDAL("Peter", "1"));
            lista.Add(new PersonDAL("George", "2"));
            lista.Add(new PersonDAL("Michael", "3"));

            return lista;
        }

        public PersonDAL GetPersonByID(string id)
        {
            PersonDAL result = new PersonDAL("", "");
            result = null;

            foreach (PersonDAL person in lista)
            {
                if (person.ID == id)
                {
                    result = person;
                    break;
                }
            }
            return result;
        }

        public string ID
        {
            get { return _id; }
        }
        public string Name
        {
            get { return _name; }
        }

    }
}

it is a simple class which gets data from some resource. In this case, data are hardcoded but never mind.
The other project is BusinessLayer, it represents some business logic. It is Layer 2.
Person class:

using System;
using System.Collections.Generic;
using System.Text;

using DataLayer;

namespace BusinessLayer
{
    public class Person
    {
        public string _id;
        public string _name;  

        public Person(string id, string name)
        {
            _id = id;
            _name = name;
        }

    }
}

interface IPersonService:

using System;
using System.Collections.Generic;
using System.Text;

namespace BusinessLayer
{
    public interface IPersonService
    {
        List
 GetPersons();

        Person GetPersonByID(string id);
    }
}

and PersonService class:

using System;
using System.Collections.Generic;
using System.Text;

namespace BusinessLayer
{
    public class PersonService : IPersonService
    {

        DataLayer.PersonDAL person = new DataLayer.PersonDAL("", "");        

        public List
 GetPersons()
        {
            List
 list = new List
();

            foreach (DataLayer.PersonDAL  objPerson in person.CreateList())
            {
                list.Add(new Person(objPerson.ID, objPerson.Name));
            }

            return list;
        }

        public Person GetPersonByID(string id)
        {
            return new Person(person.GetPersonByID(id).ID,person.GetPersonByID(id).Name);
        }
    }
}

Ok, that is part of some huge application. Let’s code some Unit test here. Supose we do not have data resource at this moment and we can not test this with real data. We must fake it.
So, create new project, type of Class Library into this solution and call it: Test
Add references for both projects and references for NUnit.Framework and
Rhino.Mocks. This project for now has only one class. We use it for testing.
PersonServiceTest class:

 using System;
using System.Collections.Generic;
using NUnit.Framework;
using Rhino.Mocks;

using BusinessLayer;
using DataLayer;

[TestFixture]
public class PersonServiceTest
{

    [SetUp]
    public void TestInit()
    {

    }

    [Test]
    public void Test()
    {
        MockRepository mockRepository = new MockRepository();
        IPersonService personRepository = mockRepository.CreateMock();

        Person mockPerson = new Person("1", "Milan");
        Person objPerson;

        Expect.Call(personRepository.GetPersonByID("1")).Return(mockPerson);

        mockRepository.ReplayAll();

        objPerson = personRepository.GetPersonByID("1");
        Assert.AreEqual(objPerson._id, mockPerson._id);
    }
}

NUnit testing

.NET, NUnit No Comments »

What Is Unit test?

A unit test verifies that a function or set of functions meet the requirements.  Unit tests inspect both black boxes or white boxes. NUnitis a unit-testing framework for all .Net languages.
Here is an example. Let’s take a look this class:

namespace Bank
{
    public class Account
    {
        private float balance;

        public void Deposit(float amount)
        {
            balance += amount;
        }
        public void Withdraw(float amount)
        {
            balance -= amount;
        }
        public void TransferFunds(Account destination, float amount)
        {
            destination.Deposit(amount);
            Withdraw(amount);

        }
        public float Balance
        {
            get { return balance; }
        }
    }
}

for this class we make corresponding unit test class like this:

using NUnit.Framework;
using Bank;

namespace Test
{
    [TestFixture]
    public class AccountTests
    {
        [Test]
        public void TestTransferFunds()
        {
            Account source = new Account();
            source.Deposit(200.00F);
            Account destination = new Account();
            destination.Deposit(150.00F);

            source.TransferFunds(destination, 100.00F);

            //Here are assertions
            //we check actual value with expected value
            Assert.AreEqual(250.00F, destination.Balance);
            Assert.AreEqual(100.00F, source.Balance);

        }
  }
}

Assertions are central part of unit testing in any of the xUnit frameworks. NUnit provides a rich set of assertions as static methods of the Assert class.
Example:
Assert.AreEqual( int expected, int actual );
There are:

  • StringAssert
  • CollectionAssert
  • FileAssert

From version 2.0 on, NUnit has used custom attributes.
All NUnit attributes are contained in the NUnit.Framework namespace. Each source file that contains tests must include a using statement for that namespace and the project must reference the framework assembly, nunit.framework.dll.

SetUpFixture Attribute

This is the attribute that marks a class that contains the one-time setup or teardown methods for all the test fixtures under a given namespace. The class may contain at most one method marked with the SetUpAttribute and one method marked with the TearDownAttribute.
Example:

[SetUpFixture]
public class MySetUpClass
{
  [SetUp]
  RunBeforeAnyTests()
  {
    // ...
  } 

  [TearDown]
  RunAfterAnyTests()
  {
    // ...
  }
}

Test Attribute (NUnit 2.0)

The Test attribute marks a specific method inside a class that has already been marked as a TestFixture, as a test method. The signature for a test method is defined as follows:
public void MethodName()

Example:

[Test]
public void Add()
{
	 /* ... */
}

SetUpAttribute

This attribute is used inside a TestFixture to provide a common set of functions that are performed just before each test method is called. A TestFixture can have only one SetUp method. If more than one is defined the TestFixture will compile successfully, but its tests will not run.

Example:

[TestFixture]
public class SuccessTests
{
  [SetUp]
  public void Init()
  {
 	/* ... */
  }
}

TearDownAttribute

This attribute is used inside a TestFixture to provide a common set of functions that are performed after each test method is run. A TestFixture can have only one TearDown method. If more than one is defined the TestFixture will compile successfully, but its tests will not run.
Example:

  [TestFixture]
  public class SuccessTests
  {
    [SetUp]
    public void Init()
    {
	/* ... */
    } 

    [TearDown]
    public void Dispose()
     {
	 /* ... */
     } 

     [Test]
     public void Add()
    {
        /* ... */

    }
}

At the end I want to tell you about ExpectedException Attribute.
We use it when we want to test some exception.
This is the way to specify that the execution of a test will throw an exception.

Example:

  [ExpectedException( typeof( ArgumentException ) )]
  public void TestMethod()
  {
 	...
  }

  [ExpectedException( typeof( ArgumentException ), ExpectedMessage="expected message" )]
  public void TestMethod()
  {
 	...
  }

Web programming: How to read cookie created by ASP.NET using JavaScript

.NET, ASP.NET No Comments »

All of you heard about “Cookies”. This is a way that web site remember some information about you in *.txt file located on your machine.

Here is how we create cookie in C#, this is code behibnd of aspx page.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create a new HttpCookie named "MyLastVisit".
        HttpCookie myHttpCookie = new HttpCookie("MyLastVisit", DateTime.Now.ToString());

        // By default, the HttpOnly property is set to false
        // unless specified otherwise in configuration.

        //rename Cookie
        myHttpCookie.Name = "MyHttpCookie";
        Response.AppendCookie(myHttpCookie);

        // Show the name of the cookie.
        Response.Write(myHttpCookie.Name);

        // Create an HttpOnly cookie.
        HttpCookie myHttpOnlyCookie = new HttpCookie("MyLastVisit", DateTime.Now.ToString());

        // Setting the HttpOnly value to true, makes
        // this cookie accessible only to ASP.NET.

        myHttpOnlyCookie.HttpOnly = true;
        //rename Cookie
        myHttpOnlyCookie.Name = "MyHttpOnlyCookie";
        Response.AppendCookie(myHttpOnlyCookie);

        // Show the name of the HttpOnly cookie.
        Response.Write(myHttpOnlyCookie.Name);
    }
}

and this is java script code which reads cookie:





<script>

    // This code returns the cookie name.
    alert("Getting HTTP Cookie");
    alert(getCookie("MyHttpCookie"));

    // Because the cookie is set to HttpOnly,
    // this returns null.
    alert("Getting HTTP Only Cookie");
    alert(getCookie("MyHttpOnlyCookie"));

</script> 



5 Basic SEO Rules

Web Design No Comments »

This post is about SEO (Search engine optimization). SEO is the process of increasing the amount of visitors to a Web site by ranking high in the search results of a search engine. The higher a Web site ranks in the results of a search, the greater the chance that that site will be visited by a user. Here are basic rules:
#1 Don’t Re-Use Your Title Tag On Every Page
So each page must have different title tag.

#2 Keyword Research
Keyword research can also let you know how to target the content on your page, how to word each page’s title tag and whether people really are searching on your business name. It’s well worth the time spent to discover exactly what you need to target to have a successful website.

#3 Don’t Use Keywords In Images
If your keywords are embedded in images, the search engines have no clue that keyword is related to your page. They cannot “see” your images. So if the term “web design” is important to your business, make sure it’s actual text somewhere within your content, not part of an image.

#4 Check Your Robots.txt File
Check and double check your Robots.txt file. Make sure it’s in the root folder of your domain. Ensure all the folders and files you want to be found by the search engines are allowed. Any development folders, javascript folders, css folders or private folders, you do not want to end up in a search engine results should be disallowed.

For more information please check out: Robotstxt.org.
#5 Provide An HTML Version of Your Sitemap
If your navigation is currently in flash or javascript, this is a great alternative way of making sure the spiders find the site’s pages. Make sure that your link to your sitemap is a simple “a href” tag, not a link formed with javascript or flash as the spiders will not be able to follow that type of link.

It is quite small tutorial for the beginning. The rest is coming soon :)

Top 3 security mistakes which .NET developers make

.NET No Comments »

When you start programming, you can find beginners mistakes in misspelling, missing “;”, … But leter you’ll find there exists logical errors too. Your code has no errors or warnings, but application behavior is different. It is so called logical errors. This post is about some security mistakes which .net developer makes.

1-st Mistake: SQL Injection
SQL injection is passing SQL code into an application. These potential attack strings are parts of SQL query that can be executed on the database server if the Web application uses the string when forming a SQL statement without first parsing out certain characters.

For example, problems can arise when a developer does not protect against potentially malicious input such as a ” ‘ “, which could close the SQL string and give the user unintended system and application access. The simple and most common SQL query which developer use during login process looks like:

SELECT userID, fname, lname from users WHERE username = $username and password = $password

An example of SQL injection would be for the user to enter the following strings for the username and password:

‘ OR ‘1′ = ‘1

The SQL statement passed to the database now reads like this:

SELECT CustomerID FROM Customers WHERE EmailAddress = '' OR '1' = '1'
AND Password = '' OR '1' = '1'
SELECT userID, fname, lname from users WHERE username = '' OR '1' = '1' and password = '' OR '1' = '1'

Since the WHERE clause of the SQL statement will be satisfied by the always-true condition ‘1′ = ‘1′, the SQL statement will login you successfully.
Here is another example of a more destructive SQL injection. You may have text field for entering email address for newsletter. And what if someone put this for e-mail address.

'; DELETE FROM Customers;

The SQL now reads:

SELECT CustomerID FROM Customers WHERE EmailAddress = ”; DELETE FROM Customers;

If you really have table named Customers, all data will be erased.

2-nd Mistake : Cross-Site Scripting
Each user input must be validated. Especially if you show entered data to page in next screen.
Taking user input and returning it to the user without proper encoding causes cross-site scripting. Cross-site scripting occurs when dynamically generated Web pages display input that is not properly validated. This is also knows as XSS or CSS scripting. For cross-site scripting demonstartion, enter the following text into any form field whose value will be displayed on the page after it is posted back (for example, it can be a search filed):

<script>alert(’Some Message’)</script>

If, when the page posts back, you see a pop-up message box with the message “Some Message”, then that page is vulnerable to cross-site scripting.

How to solve it in .NET? By passing all user input through the Server.HTMLEncode() function, the cross-site scripting hole is automatically fixed.

3-hd Mistake: Enabling Debug Options in the Web.Config File
The section of the Web.Config file tells a .NET application how to deal with errors. An application should never show an end user a detailed error message. Instead, it should show a “friendly” message that says the site is having technical difficulties, and not give any technical details.

Attackers can get some valuable information from error messages. That means you have to enable detailed error messages. This is one of possible settings for tag in Web.config file.

    

Design Pattern - Adapter

Design Paterns, Java, OOP No Comments »

In all my previous posts I wrote about Creational Design Patterns: Singleton, Abstract Factory, Factory method, Prototype and Builder. In this posts I will introduce you with: Adapter - Structural Pattern.
Definition of “Adapter” says:
Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces, so it converts the interface of a class into another interface clients expect. Here is UML diagram

design pattern - adapter

design pattern - adapter


Here is the Java code which demonstrates using of Adapter pattern. This is abstract class Shape. I use it to define some very simple interface.

abstract class Shape {
	public abstract double GetVolume();
}

and now I create 2 clases which implements this interface

public class Square extends Shape {

	private int radius;

	public Square(int r)
	{
		radius = r;
	}

	public double GetVolume()
	{
		return radius * radius;
	}
}
public class Triangle extends Shape {

	private int a;

	public Triangle(int x)
	{
		a = x;
	}

	public double GetVolume()
	{
		return (a * a * Math.sqrt(3)) /4;
	}
}

and what if we have one more class but with the wrong interface (functionality is ok, but interface not)

public class XCircle {

	private int radius;

	public XCircle(int r)
	{
		radius = r;
	}

	public double XGetVolume()
	{
		return radius * radius * Math.PI;
	}
}

but we need Cirlce class. Here is what we do than:

public class Circle extends Shape {

	private int radius;
	private XCircle circle;
	public Circle(int r)
	{
		radius = r;
		circle = new XCircle(radius);
	}

	public double GetVolume()
	{
		return circle.XGetVolume();
	}
}

at the end here is simple client application to demonstrate how it works:

public class Circle extends Shape {

	private int radius;
	private XCircle circle;
	public Circle(int r)
	{
		radius = r;
		circle = new XCircle(radius);
	}

	public double GetVolume()
	{
		return circle.XGetVolume();
	}
}

that is all :)

HOW TO: Generate Thumbnails on the Fly using ASP.NET while uploading video file

.NET, C# No Comments »

In this tutorial our focus is on creating dynamic thumbnails with the help of .NET framework. Here is the scenario: We have simple aspx page with FileUpload and Button control. We will use FMPEG library, so you can have it installed before you start this example.
Here is the code of aspx page:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>








and code for web.config file:




  
    
    
  

	
	
		
		
    
	

as you can see, we save location of fmpeg and thumb path in web.config.

and here is the code which will uplaod video and save it’s thumb:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string thumbpath, thumbname, inputfile;
        string thumbargs;        

        thumbpath = ConfigurationManager.AppSettings.GetValues("thumbpath")[0];

        inputfile = thumbpath + fileUpload.FileName; 

        fileUpload.PostedFile.SaveAs( inputfile);

        thumbname = thumbpath + fileUpload.PostedFile.FileName.Substring(0, fileUpload.PostedFile.FileName.LastIndexOf(".")) + ".jpg";
        thumbargs = "-i " + inputfile + " -f image2 -ss 1 -vframes 1 -s 150x150 " + thumbname; 

        Process thumbproc = new Process();
        thumbproc = new Process();
        thumbproc.StartInfo.FileName = thumbpath = ConfigurationManager.AppSettings.GetValues("ffmpegPath")[0];
        thumbproc.StartInfo.Arguments = thumbargs;
        thumbproc.StartInfo.UseShellExecute = false;
        thumbproc.StartInfo.CreateNoWindow = false;
        thumbproc.StartInfo.RedirectStandardOutput = false;
        try
        {
            thumbproc.Start();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        thumbproc.WaitForExit();
        thumbproc.Close();
    }
}

Design Patterns: Prototype

Design Paterns, Java, OOP No Comments »

Prototype pattern: used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:

  • avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
  • avoid the inherent cost of creating a new object in the standard way (e.g., using the ‘new’ keyword) when it is prohibitively expensive for a given application.
    Here is UML diagram for Prototype pattern.
    Design Patterns - Prototype

    Design Patterns - Prototype


    Here is the code examples:

    /**
     * The Animal abstract class is the prototype in the "Prototype" Pattern. The
     * animal class contains properties that describe on a abstract level the different
     * prototypes that can exist in the pattern example.
     */
    public abstract class Animal implements Cloneable {
    	protected int numberOfLegs = 0;
    	protected String description = "";
    	protected String name = "";
    	public abstract String helloAnimal();	
    
    	/**
    	 * The clone method creates a clone of the current Animal object.
    	 */
    	public Animal clone() {
    		Animal clonedAnimal = null;
    		try {
    			clonedAnimal = (Animal) super.clone();
    			clonedAnimal.setDescription(description);
    			clonedAnimal.setNumberOfLegs(numberOfLegs);
    			clonedAnimal.setName(name);
    
    		} catch (CloneNotSupportedException e) {
    			e.printStackTrace();
    		}
    		return clonedAnimal;
    	}  
    
    	public String getDescription() {
    		return description;
    	}
    
    	public void setDescription(String description) {
    		this.description = description;
    	}
    
    	public int getNumberOfLegs() {
    		return numberOfLegs;
    	}
    
    	public void setNumberOfLegs(int numberOfLegs) {
    		this.numberOfLegs = numberOfLegs;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    }
    
    /**
     * The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator
     * class contains two concrete prototypes that is initialized during the initialization of
     * the class. The AnimalCreator class forms part of the "Prototype" pattern by returning
     * a cloned object (Animal) to the client, withou the client knowing the type of the prototype.
     */
    public class AnimalCreator {
    
    	private Animal sheep = new Sheep();	
    
    	private Animal chicken = new Chicken();
    
    	public AnimalCreator() {
    		sheep.setName("Sheep");
    		sheep.setNumberOfLegs(4);
    		sheep.setDescription("Four legged creature that makes wool.");
    
    		chicken.setName("Chicken");
    		chicken.setNumberOfLegs(2);
    		chicken.setDescription("Two legged creature that crosses roads.");
    	} 
    
    	public Animal retrieveAnimal(String kindOfAnimal) {
    		if ("Chicken".equals(kindOfAnimal)) {
    			return (Animal) chicken.clone();
    		} else if ("Sheep".equals(kindOfAnimal)) {
    			return (Animal) sheep.clone();
    		} // if
    
    		return null;
    	} // method retrieveAnimal
    }
    
    public class Chicken extends Animal {
    	private int numberOfClones = 0;
    	public String helloAnimal() {
    	StringBuffer chickenTalk = new StringBuffer();
    	chickenTalk.append("Cluck cluck World. I am ");
    	chickenTalk.append(name);
    	chickenTalk.append(". I have ");
    	chickenTalk.append(numberOfLegs);
    	chickenTalk.append(" legs.");
    	return chickenTalk.toString();
    	} // helloAnimal
    
    	public Chicken clone() {
    		Chicken clonedChicken = (Chicken) super.clone();
    		String chickenName = clonedChicken.getName();
    		numberOfClones++;
    		clonedChicken.setName(chickenName + numberOfClones);
    		return clonedChicken;
    	} // method clone
    }
    
    public class Sheep extends Animal {
    	private int numberOfClones = 0;
    	public String helloAnimal() {
    	StringBuffer sheepTalk = new StringBuffer();
    	sheepTalk.append("Meeeeeee World. I am ");
    	sheepTalk.append(name);
    	sheepTalk.append(". I have ");
    	sheepTalk.append(numberOfLegs);
    	sheepTalk.append(" legs.");
    	return sheepTalk.toString();
    	}
    
    	public Sheep clone() {
    		Sheep clonedSheep = (Sheep) super.clone();
    		String sheepName = clonedSheep.getName();
    		numberOfClones++;
    		clonedSheep.setName(sheepName + numberOfClones);
    		return clonedSheep;
    	} 
    
    }
    

    and for the end client class

    public class AnimalClient {
    	public static void main(String[] args) {
    		AnimalCreator animalCreator = new AnimalCreator();
    		Animal[] animalFarm = new Animal[8];
    		animalFarm[0] = animalCreator.retrieveAnimal("Chicken");
    		animalFarm[1] = animalCreator.retrieveAnimal("Chicken");
    		animalFarm[2] = animalCreator.retrieveAnimal("Chicken");
    		animalFarm[3] = animalCreator.retrieveAnimal("Chicken");
    
    		animalFarm[4] = animalCreator.retrieveAnimal("Sheep");
    		animalFarm[5] = animalCreator.retrieveAnimal("Sheep");
    		animalFarm[6] = animalCreator.retrieveAnimal("Sheep");
    		animalFarm[7] = animalCreator.retrieveAnimal("Sheep");
    
    		for (int i= 0; i< =7; i++) {
    			System.out.println(animalFarm[i].helloAnimal());
    		} // for
    	}
    }
    

Design Patterns: Builder

Design Paterns, Java, OOP No Comments »

In software engineering, creational design patterns are design patterns that we’re using in object creation. Creational design patterns solve this problem by somehow controlling this object creation.

Here is the list of creational design patterns:

  • Abstract Factory
  • Builder
  • Factory Method
  • Prototype
  • Singleton

Now let’s get back to Builder pattern.
here is UML

Design pattern - Builder

Design pattern - Builder


The intention of Builder Pattern is to abstract steps of construction of object so that different implementations of these steps can construct different representations of objects.
Often, the Builder Pattern is used to build Products in accordance to the Composite pattern, a structure pattern.
Example

public class Director
{
  // Builder uses a complex series of steps
  public void Construct(VehicleBuilder vehicleBuilder)
  {
    vehicleBuilder.BuildFrame();
    vehicleBuilder.BuildEngine();
    vehicleBuilder.BuildWheels();
    vehicleBuilder.BuildDoors();
  }
}
public abstract class VehicleBuilder {
    protected Vehicle vehicle;
    // Property
    public Vehicle getVehicle()
    {
    	return vehicle;
    }

    public abstract void BuildFrame();
    public abstract void BuildEngine();
    public abstract void BuildWheels();
    public abstract void BuildDoors();
}
public class ScooterBuilder extends VehicleBuilder {

	public void BuildFrame()
    {
      vehicle = new Vehicle("Scooter");
      vehicle.AddObject("frame", "Scooter Frame");
    }

    public void BuildEngine()
    {
      vehicle.AddObject("engine", "50 cc");
    }

    public void BuildWheels()
    {
      vehicle.AddObject("wheels", "2");
    }

    public void BuildDoors()
    {
      vehicle.AddObject("doors", "0");
    }
}
public class MotorCycleBuilder extends VehicleBuilder {

	public void BuildFrame()
    {
      vehicle = new Vehicle("MotorCycle");
      vehicle.AddObject("frame", "MotorCycle Frame");
    }

    public void BuildEngine()
    {
      vehicle.AddObject("engine", "500 cc");
    }

    public void BuildWheels()
    {
      vehicle.AddObject("wheels", "2");
    }

    public void BuildDoors()
    {
      vehicle.AddObject("doors", "0");
    }
}
public class CarBuilder extends VehicleBuilder {

	public void BuildFrame()
    {
      vehicle = new Vehicle("Car");
      vehicle.AddObject("frame", "Car Frame");
    }

    public void BuildEngine()
    {
      vehicle.AddObject("engine", "2500 cc");
    }

    public  void BuildWheels()
    {
      vehicle.AddObject("wheels", "4");
    }

    public void BuildDoors()
    {
      vehicle.AddObject("doors", "4");
    }
}
import java.util.*;

//"Product"
public class Vehicle {
	 private String type;
	    private Hashtable parts = new Hashtable();

	    // Constructor
	    public Vehicle(String type)
	    {
	      this.type = type;
	    }

	    public void AddObject(String key, String value)
	    {
	    	parts.put(key, value);
	    }

	    public String GetObject(String key)
	    {
	    	return parts.get(key);
	    }	    

	    public void Show()
	    {
	      System.out.println("\n---------------------------");
	      System.out.println("Vehicle Type: " + type);
	      System.out.println(" Frame : " + parts.get("frame"));
	      System.out.println(" Engine : " + parts.get("engine"));
	      System.out.println(" #Wheels: " + parts.get("wheels"));
	      System.out.println(" #Doors : " + parts.get("doors"));
	    }
}

and for the end, here is the client to show how all of this works together!

public class Client {

    public static void main(String[] args)
    {
      // Create shop with vehicle builders
      Director director = new Director();
      VehicleBuilder b1 = new ScooterBuilder();
      VehicleBuilder b2 = new CarBuilder();
      VehicleBuilder b3 = new MotorCycleBuilder();

      // Construct and display vehicles
      director.Construct(b1);
      b1.getVehicle().Show();

      director.Construct(b2);
      b2.getVehicle().Show();

      director.Construct(b3);
      b3.getVehicle().Show();

    }
}

Configuration files and ConnectionStrings

.NET, C# No Comments »

One of the first things I’ve learned as .NET developer was using of App.config or Web.config files. Almost every application in which development I took a part had some database. Here is the brief sample how to connect to SQL Server from C#:

			string connString = @"Server=(LOCAL);Database=Northwind;User ID=sa;Password=;";
			string sqlString =  "SELECT * FROM PRODUCTS";
			DataSet ds = new DataSet();
			SqlConnection conn = new SqlConnection(connString);
			conn.Open();
			SqlDataAdapter da = new SqlDataAdapter(sqlString, conn);

			da.Fill(ds);
			dgrProducts.DataSource = ds;
			dgrProducts.DataBind();
			conn.Close();

This code will open connection to database, read table and fill data set. Then we bind data from data set to dataGrid or GridView (control named dgrProducts).
But it is not a good practice to keep connection string hard coded. Place it into configuration file.

< ?xml version="1.0" encoding="utf-8" ?>

	
	
		
	

and here is how you can read value from configuration file. It is a good practice to create new project, type of Class Library for that.

using System;
using System.Configuration;

namespace ConnectionString
{
	public class Configuration
	{
		public static string ReadConnectionString
		{
			get
			{
				return ConfigurationSettings.AppSettings.Get("ConnectionString");
			}
		}
	}
}

this sample runs on .NET 1.1 framework
For 3.0 .NET we use:

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace ConnectionString
{
    public class Configuration
    {
        protected static string ConnectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["ConnectionString"].
                    ToString();
            }
        }
    }
}

As you can see we use System.Configuration reference.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in