Archive for January, 2009

5 Basic SEO Rules

Thursday, January 29th, 2009

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

Tuesday, January 20th, 2009

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

Thursday, January 15th, 2009

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

Thursday, January 15th, 2009

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

Saturday, January 10th, 2009

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

Friday, January 9th, 2009

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

Monday, January 5th, 2009

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