Feeds:
Posts
Comments

Abstract Factory

The abstract factory is a software design pattern used to create different family objects. The important thing here is that those classes must be related, in order to be used with an abstract class.

My example consist of 2 classes, named Circle and Rectangle. This 2 classes have something in common, they’re geometric figures and for example, both have an area formula.

I have seen a couple of examples in which the author just set the abstract class for the concrete classes. With this approach we will need to create an instance of the class based on the abstract class.

E.g. GeometricFigureAbstractClass obj = new Circle() (In this case, circle inherits from GeometricFigureAbstractClass, see example below).

I think this is not good enough, if all the classes contains in some way related methods why not just create a concrete and general class that will handle all of this behavior.

Now, first of all create the abstract class named GeometricFigure:

/// <summary>

/// Base class for all the geometric figures.

/// </summary>

abstract class GeometricFigure

{

public abstract string AreaFormula();

}

Now the concrete classes for that will inherit from GeometricFigure, in this case Circle and Rectangle.

/// <summary>

/// Circle concrete class, who inherits from GeometricFigures

/// </summary>

sealed class Circle : GeometricFigure

{

public override string AreaFormula()

{

return “pi * radius ^ 2″;

}

}

/// <summary>

/// Rectangle concrete class, who inherits from GeometricFigures

/// </summary>

sealed class Rectangle : GeometricFigure

{

public override string AreaFormula()

{

return “length * width”;

}

}

Now it’s time to create the factory, the class that will be in charge of creating the expected class from our request, using the enumerator we just created above.

/// <summary>

/// Class that creates an instance of a class that inherits from GeometricFigure

/// </summary>

sealed class GeometricFigureFactory

{

/// <summary>

/// Returns the concrete class instance that inherits from GeometricFigure

/// </summary>

/// <param name=”type”>The type of the concrete class to instantiate</param>

/// <returns></returns>

public GeometricFigure ReturnGeometricFigure(GeometricFigureType type)

{

GeometricFigure figure;

switch (type)

{

case GeometricFigureType.Circle:

figure = new Circle();

break;

default:

figure = new Rectangle();

break;

}

return figure;

}

}

This class contains a simple method called ReturnGeometricFigure that expects an enumeration type. This enum type will be the key in order to create the instance we requested, for example, if we need to create an instance of the class Circle just send the Circle enum type. It will return an instance of Circle, that inherits from GeometricFigure.

This is enough as an abstract factory, but we can go further.

Lets create a Manager, a class that will be used to get the information from the every single class of factory using one instance, my manager instance.

/// <summary>

/// Manager class that simplifies the abstract factory use. Can use all the classes that inherits from GeometricFigure

/// using the Factory class.

/// </summary>

sealed class GeometricFigureManager

{

public string GetAreaFormula(GeometricFigureType Type)

{

GeometricFigureFactory factory = new GeometricFigureFactory();

GeometricFigure figure = factory.ReturnGeometricFigure(Type);

return figure.AreaFormula();

}

}

As I said before, the Circle and the Rectangle both contains an area right?. What if I want to get the formula of the circle and the rectangle? we will need to create both instances, but with this manager we can have both. The Manager receives the GeometricFigureType, the manager creates the instance using the factory and will send the formula from the instantiated class.

In fact, we can use a Singleton pattern in order to have only one instance of the Manager in the whole application ;) .

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace AbstractFactorySample

{

class Program

{

static void Main(string[] args)

{

//Regular abstract method way

//Create a circle instance, get area

GeometricFigure circle = new Circle();

string circleFormula = circle.AreaFormula();

//Create a rectangle instance, get area

GeometricFigure rect = new Rectangle();

string rectFormula = rect.AreaFormula();

//All this can be reduced to a single object

GeometricFigureManager manager = new GeometricFigureManager();

var formulaRect = manager.GetAreaFormula(GeometricFigureType.Rectangle);

var formulaCirc = manager.GetAreaFormula(GeometricFigureType.Circle);

}

}

/// <summary>

/// Base class for all the geometric figures.

/// </summary>

abstract class GeometricFigure

{

public abstract string AreaFormula();

}

/// <summary>

/// Circle concrete class, who inherits from GeometricFigures

/// </summary>

sealed class Circle : GeometricFigure

{

public override string AreaFormula()

{

return “pi * radius ^ 2″;

}

}

/// <summary>

/// Rectangle concrete class, who inherits from GeometricFigures

/// </summary>

sealed class Rectangle : GeometricFigure

{

public override string AreaFormula()

{

return “length * width”;

}

}

/// <summary>

/// Class that creates an instance of a class that inherits from GeometricFigure

/// </summary>

sealed class GeometricFigureFactory

{

/// <summary>

/// Returns the concrete class instance that inherits from GeometricFigure

/// </summary>

/// <param name=”type”>The type of the concrete class to instantiate</param>

/// <returns></returns>

public GeometricFigure ReturnGeometricFigure(GeometricFigureType type)

{

GeometricFigure figure;

switch (type)

{

case GeometricFigureType.Circle:

figure = new Circle();

break;

default:

figure = new Rectangle();

break;

}

return figure;

}

}

/// <summary>

/// Manager class that simplifies the abstract factory use. Can use all the classes that inherits from GeometricFigure

/// using the Factory class.

/// </summary>

sealed class GeometricFigureManager

{

public string GetAreaFormula(GeometricFigureType Type)

{

GeometricFigureFactory factory = new GeometricFigureFactory();

GeometricFigure figure = factory.ReturnGeometricFigure(Type);

return figure.AreaFormula();

}

}

/// <summary>

/// The classes that inherits from GeometricFigure

/// </summary>

public enum GeometricFigureType

{

Circle,

Rectangle

}

}


Cloning objects in .NET

This is a very easy sample of how to clone an object. Some objects in the .NET Framework contains the Clone method. But what if I want to do this with my own class? Don’t worry, that’s very easy to implement. This is how to do it!

using System;

namespace CloningSample

{

/// <summary>

/// Person class sample

/// Must implements the interface ICloneable found in System library.

/// This interface contains the Clone() Method that will return the Copy of the object.

/// </summary>

class Person : ICloneable

{

public string Name;

public int Age;

public DateTime BirthDate;

public object Clone()

{

//The MemberwiseClone() method returns a shallow copy of the current instantiation

return this.MemberwiseClone();

}

}

class Program

{

static void Main(string[] args)

{

//Create the Person object

Person person = new Person();

//Create the copy of the Person object

Person personCopy = person.Clone() as Person;

//Verify they are different objects

if (person.Equals(personCopy))

Console.WriteLine(“Hey duff this is not working at all…”);

else

Console.WriteLine(“Cool, they are different Person objects…”);

Console.Read();

}

}

}

Singleton sample with c#

Singleton is a design pattern used to restrict the instantiation of a class to one object. E.g. you may need a class that will contain the user information across the system, there is no need to create several instances of this class. The explanation of this will be given in this little sample, now have fun… :s

using System;

using System.Threading;

namespace SingletonSample

{

//Main class

class Program

{

static void Main(string[] args)

{

//Create the first instance of the object

CacheMemory cache = CacheMemory.Instance;

//Trying to create a second instance of the object

CacheMemory cache2 = CacheMemory.Instance;

//Show the time of creation of the object, both should have the same InstanceTime

Console.WriteLine(cache.ToString());

Console.WriteLine(cache2.ToString());

//InstanceTime doesnt mean they are the same object, PROVE IT

if (cache.Equals(cache2))

{

Console.WriteLine(“They are the same object, both have the same HashCode: “);

Console.WriteLine(“cache object hash: “ + cache.GetHashCode());

Console.WriteLine(“cache2 object hash: “ + cache2.GetHashCode());

}

else

Console.WriteLine(“You lied Duff, arent the same object :@”);

Console.Read();

}

}

/// <summary>

/// Set the class as sealed to avoid inheritance and the possibility to create several instances of the class

/// </summary>

public sealed class CacheMemory

{

static CacheMemory cache = null;

//Object used to lock the instance in a thread safe way.

static readonly object padlock = new object();

public static DateTime InstanceTime;

/// <summary>

/// Set the constructor as private. With this, the only way to create an instance of the class is using the Instance Property

/// </summary>

private CacheMemory() { }

/// <summary>

/// Instance property in order to create the instance of the class.

/// </summary>

public static CacheMemory Instance

{

get

{

//Lock the call to the Instance

//With this, only one call will enter into the get avoiding multiple instances of the CacheMemory class

lock (padlock)

{

//If the cache is null, then create a new Instance and set the Time of the creation of the object

if (cache == null)

{

cache = new CacheMemory();

InstanceTime = DateTime.Now;

}

//If already the object was created, return the object.

return cache;

}

}

}

/// <summary>

/// Override the ToString method in order to show the creation time of the object.

/// </summary>

/// <returns></returns>

public override string ToString()

{

return InstanceTime.ToString();

}

}

}

First of all, this is not a Silverlight vs Flash post or a Silverlight vs any other web technology. I will stay focused on the benefits of Silverlight.

I used to make web applications using PHP, ASP.NET, Flash and several other techonology. When WPF and Silverlight appeared where I work, I just said “We dont need this, WinForms is ok, ASP.NET is ok if you include Ajax .NET and so many other technologies”. This is normal, when you already know  techonology you just dont want to move because you think that is going to be complicated, or because you dont know the advantages of a new techonology.

I started using WPF, and when I moved to Silverlight 2 Beta 1 I said “Oh my God why is this so difficult!”. I just did a chat web service using Windows Communication Foundation using Duplex Channels and Silverlight and now that I know how to take advantage of this… I can say I am very proud of and happy to join the new vision of Microsoft (and come on, I am not a  M$ fan but their technology is giving me something to eat lol), considering that here in Panama we are one of the first (if not the first) IT Outsourcing business using WPF and Silverlight.

I think they are going in the right direction and I believe Silverlight IS the future of the web. Flash is good, we all know that, PHP is good, Javascript is good… but for real and robust web applications I have no doubt that Silverlight will become the standard together with all the new Microsoft technologies. Silverlight is very scalable, so thats not a barrier to overcome for M$. Possibly not everybody have installed the Silverlight plugin right now, but thats is gonna change in the near future. From now on, I will stick to Silverlight… I love this new vision and if you dont know what is this new vision all about, I would like you to take a look to what is possible using Silverlight, thats is not just an “Animation Tool for the web”.

Silverlight really, really is the new web.

Sometimes you will need to create at runtime a generic type. For example, you just created a new User Control and you expect a collection to be used as DataContext. But this DataContext can be an Observable Collection of Employees or Manager objects. So, if you want to use it in your user control, you will need to get the type of the DataContext no matter the type of the content of the collection.

Now.. try to do the following…

Type newType = typeof(ObservableCollection<typeof(string)>);

You will get a compilation error, so basically you can’t create dinamically a Generic type in this way.

The Type class has a MakeGenericType method that you can use to do this at runtime. Check out this example:

using System;

using System.Collections.Generic;

using System.Collections.ObjectModel;

using System.Linq;

using System.Text;

namespace DynamicGenericTypes

{

class Program

{

static void Main(string[] args)

{

//Lets create at runtime an ObservableCollection and a SortedDictionary

Type runtimeObservable, runtimeSortedDic;

//Arguments to create the ObservableCollection of integers

Type observable = typeof(ObservableCollection<>);

Type[] ocArgs = new Type[] { typeof(Int32) };

//Arguments to create the SortedDictionary with Guid as Key and String as Value

Type sortedDic = typeof(SortedDictionary<,>);

Type[] sdArgs = new Type[] { typeof(Guid), typeof(String)};

//Get the collections generated at runtime using the CreateGenericType static method in the DuffsTypeCreator class

runtimeObservable = DuffsTypeCreator.CreateGenericType(observable, ocArgs);

runtimeSortedDic = DuffsTypeCreator.CreateGenericType(sortedDic, sdArgs);

/* Now lets do something to test if this works!

* Lets create an Observable Collection with 2 items and a SortedDictionary with 2 items

*/

ObservableCollection<int> ocTest = new ObservableCollection<int>();

ocTest.Add(100);

ocTest.Add(150);

SortedDictionary<Guid, string> sdTest = new SortedDictionary<Guid, string>();

sdTest.Add(Guid.NewGuid(), “Test1″);

sdTest.Add(Guid.NewGuid(), “Test2″);

//Check if the collections types are equal to the Runtime-created types

if (Type.Equals(ocTest.GetType(), runtimeObservable))

Console.WriteLine(“runtimeObservable is of type: “ + runtimeObservable.FullName);

Console.WriteLine();

Console.WriteLine(“———————–”);

Console.WriteLine();

if (Type.Equals(sdTest.GetType() , runtimeSortedDic))

Console.WriteLine(“runtimeSortedDic is of type: “ + runtimeSortedDic.FullName);

Console.Read();

}

}

/// <summary>

/// Creates a new Genetic type

/// </summary>

/// <param name=”GenericType”>The generic collection class to be used, e.g. ObservableCollection, List, SortedDictionary…</param>

/// <param name=”TemplateType”>The template (s) that belongs to the generic collection, e.g. if the generic type is a List the array can contain an item with a String type that will basically means a List of strings</param>

/// <returns>A runtime created Generic Type</returns>

class DuffsTypeCreator

{

internal static Type CreateGenericType(Type GenericType, Type[] TemplateType)

{

Type runtimeGeneric = GenericType;

Type[] args = TemplateType;

Type generic = runtimeGeneric.MakeGenericType(args);

return generic;

}

}

}

The Type class also contains a MakeArrayType and other interesting functions.

Regards.

Reflection with C#

Reflection is the capability of inspect metadata from an assembly and get the information it contains. In the following example I created a class named Person, that contains:

- 3 attributes: first name, last name and age

- 2 Constructors, a no parameter constructor and another with 2 input strings for first and last name

- 2 Properties to set and get first and last name

- A method that sets the age

- A ToString() method that returns all the attributes in a sentence

What I do in the Main static method is create 2 Person objects using only Reflection. Sometime and somewhere you will need to get information from another class for sure or even create dinamically objects because you can’t do it in the design stage.

In the code I explain each step in order to use Reflection in c#…

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Reflection;

namespace Duff_Reflection

{

class Program

{

static void Main(string[] args)

{

//Lets define a Type for my class Person

Type personType = typeof(Person);

//Create an instance using the Constructor that contains 2 String input parameters

//The GetConstructor Method accepts an array of Types, indicating what Types will be used in the constructor to call, in this case 2 strings

//LOOK, in several cases this will be repeated throughout the whole sample (the array stuff indicating types or values), I’ll not repeat it.

ConstructorInfo info = personType.GetConstructor(new Type[] { typeof(String), typeof(String) });

object personCreated = info.Invoke(new object[] { “Luis”, “Del Vasto” });

//Create an instance using the default Constructor (No parameters)

object personCreated2 = Activator.CreateInstance(personType);

//From now on, we have 2 Person objects, using both constructors

//Lets asign to the first Person instance created the age

MethodInfo assignAge = personType.GetMethod(“setAge”);

assignAge.Invoke(personCreated, new object[] { 22 });

//Lets asign to the second Person instance created the age

assignAge.Invoke(personCreated2, new object[] { 50 });

//In the second object, the first and last name haven’t been set yet, lets do it

//In order to set the values to the firstName and lastName attributes, I will use the

//2 Properties declared in the same class, I’ll retrieve them and assign the values.

PropertyInfo fname = personType.GetProperty(“FirstName”);

PropertyInfo lname = personType.GetProperty(“LastName”);

fname.SetValue(personCreated2, “Ruben”, null);

lname.SetValue(personCreated2, “Gonzales”, null);

//Print the info!

Console.WriteLine(personCreated.ToString());

Console.WriteLine(personCreated2.ToString());

Console.Read();

}

}

//Custom class Person

class Person

{

string firstName, lastName;

int age;

public string FirstName

{

get { return firstName; }

set { firstName = value; }

}

public string LastName

{

get { return lastName; }

set { lastName = value; }

}

public Person()

{ }

public Person(string fName, string lName)

{

firstName = fName;

lastName = lName;

}

public void setAge(int param_age)

{

age = param_age;

}

public override string ToString()

{

return “My name is “ + firstName + ” “ + lastName + ” and I’m “ + age;

}

}

}

This must be the result of the Console sample:

Reflection Console sample

We all have noticed that when using a ListView, if you select a ListViewItem it gets a blue background as a default, and if you deselect the same ListViewItem the backgrund will change to gray. How can you change this “by default” backgrounds?. Using the System.Windows.SystemColors class located in the PresentationFramework.dll.

This class contains the colors and brushes used in the system by default.

Take a look to this example:

XAML:

<Window x:Class=”WPFListViewHighlight.Window1″

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Title=”Window1″ Height=”200″ Width=”300″>

<Grid>

<Grid.RowDefinitions>

<RowDefinition Height=”5*” />

<RowDefinition Height=”*” />

</Grid.RowDefinitions>

<ListView Grid.Row=”0″ Name=”lvSample” ItemsSource=”{Binding}” >

<ListView.View>

<GridView AllowsColumnReorder=”True”>

<GridViewColumn DisplayMemberBinding=”{Binding Path=FirstName}” Width=”100″ />

<GridViewColumn DisplayMemberBinding=”{Binding Path=LastName}” Width=”100″ />

<GridViewColumn DisplayMemberBinding=”{Binding Path=ID}” Width=”80″ />

</GridView>

</ListView.View>

</ListView>

<Button Grid.Row=”1″ HorizontalAlignment=”Center” Height=”25″>Select</Button>

</Grid>

</Window>

Code Behind:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

namespace WPFListViewHighlight

{

/// <summary>

/// Interaction logic for Window1.xaml

/// </summary>

public partial class Window1 : Window

{

List<Employee> list;

public Window1()

{

InitializeComponent();

list = new List<Employee>();

Employee newEmployee1 = new Employee(“Mike”, “Wakamole”, “999-4563″);

Employee newEmployee2 = new Employee(“Luis”, “Del Vasto”, “999-4563″);

Employee newEmployee3 = new Employee(“Loving”, “C#”, “000-5263″);

Employee newEmployee4 = new Employee(“Josue”, “Spartan”, “2222-463″);

list.Add(newEmployee1);

list.Add(newEmployee2);

list.Add(newEmployee3);

list.Add(newEmployee4);

lvSample.DataContext = list;

}

}

public class Employee

{

private string fname, lname, id;

public Employee(string f, string l, string i)

{

fname = f;

lname = l;

id = i;

}

public string FirstName

{

get { return fname; }

set { fname = value; }

}

public string LastName

{

get { return lname; }

set { lname = value; }

}

public string ID

{

get { return id; }

set { id = value; }

}

}

}

What I have in the XAML is a simple ListView using a Grid view and a button in the bottom. The ListView has a binding with a List of four employees defined with my Employee class. Now, if you select and deselect that selected item clicking the button you will see this:

selected item by default

deselected item by default

Now lets play with the System.Windows.SystemColors class. In order to change this “by default” colors we need to know that the static property HighlightBrushKey is used to get the SolidColorBrush when a item was selected, and the static property ControlBrushKey paints the face of a three-dimensional display element, in this case we will use it to change the gray background color when the item was deselected. Lets add the following resource to the XAML:

<Window.Resources>

<Style TargetType=”ListViewItem”>

<Style.Resources>

<SolidColorBrush x:Key=”{x:Static SystemColors.HighlightBrushKey}” Color=”Green”/>

<SolidColorBrush x:Key=”{x:Static SystemColors.ControlBrushKey}” Color=”LightBlue”/>

</Style.Resources>

</Style>

</Window.Resources>

With this resource, when an item is selected the background will be painted to green and when deselected the background will be painted to lightblue. Besides, you can take a look to the others static properties and do your application different.

This is the XAML after this addition:

<Window x:Class=”WPFListViewHighlight.Window1″

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Title=”Window1″ Height=”200″ Width=”300″>

<Window.Resources>

<Style TargetType=”ListViewItem”>

<Style.Resources>

<SolidColorBrush x:Key=”{x:Static SystemColors.HighlightBrushKey}” Color=”Green”/>

<SolidColorBrush x:Key=”{x:Static SystemColors.ControlBrushKey}” Color=”LightBlue”/>

</Style.Resources>

</Style>

</Window.Resources>

<Grid>

<Grid.RowDefinitions>

<RowDefinition Height=”5*” />

<RowDefinition Height=”*” />

</Grid.RowDefinitions>

<ListView Grid.Row=”0″ Name=”lvSample” ItemsSource=”{Binding}” >

<ListView.View>

<GridView AllowsColumnReorder=”True”>

<GridViewColumn DisplayMemberBinding=”{Binding Path=FirstName}” Width=”100″ />

<GridViewColumn DisplayMemberBinding=”{Binding Path=LastName}” Width=”100″ />

<GridViewColumn DisplayMemberBinding=”{Binding Path=ID}” Width=”80″ />

</GridView>

</ListView.View>

</ListView>

<Button Grid.Row=”1″ HorizontalAlignment=”Center” Height=”25″>Select</Button>

</Grid>

</Window>

This is the result:

Here is when selected…

333.jpg

Here is when deselected…

222.jpg

Regards…

OOP looks so easy until you start Abstract classes and Interfaces, then OOP looks complex. Besides, get an easy explanation about this topics is almost unlikely (just take a look to the MSDN examples). I did an easy to understand sample using an abstract class named Employee, that is the base class for Manager and Agent. Remember, abstract classes can’t be instantiated, it can ONLY be used as base class for other classes.

Imagine that you have two types of employees in your department, a manager and agents. The salaries are calculated in different ways depending of the position and experience. But they also have several common attributes that you can apply in a class. Would be dumb, as an example, declare Age, First Name and the same attributes in both classes. Here is where abstract class apply.

Let’s do an abstract class for this example named Employee

Public MustInherit Class Employee

Public FirstName As String

Public LastName As String

Public ID As String

Public Age As Int16

Public Position As String

Public YearsOfExperience As Int16

Public Shared HoursPerWeek As Int16 = 48

Public Sub GetPosition()

Console.WriteLine(FirstName + ” “ + LastName + ” is a “ + Position)

End Sub

Public Sub GetAge()

Console.WriteLine(FirstName + ” “ + LastName + ” is “ + Age.ToString())

End Sub

MustOverride Sub GetSalaryPerWeek()

End Class

This abstract class have public attributes (first name, last name, id, position and years of experience) that will be common for managers and agents. Also it has a shared (static) member named hours per week, that contains the quantity of hours that the employees works weekly.

A class is abstract only when it has at least one MustOverride (or virtual) member in the class. If not, the “abstract class” makes no sense at all. Now lets do a Manager class that inherits from Employee class. In this example our GetSalaryPerWeek must be override and all the implementation must be done in the classes that inherits from it. As I said before, the managers salary and agents salary are calculated in different ways and this is what we are going to implement in our derived classes Manager and Agent.

Public Class Manager

Inherits Employee

Public Overrides Sub GetSalaryPerWeek()

Dim salary, bonus As Double

salary = Employee.HoursPerWeek * 20.0

bonus = salary * YearsOfExperience / 100

salary += bonus

Console.WriteLine(FirstName + ” “ + LastName + ” salary is “ + salary.ToString())

End Sub

End Class

Our Manager class only got one member, the GetSalaryPerWeek that overrides our MustOverride GetSalaryPerWeek() defined in our abstract class Employee. In this example, we multiply the hours per week by the salary per hour ($20.00 for the manager) and then we get a bonus depending on the experience of the employee.

In our main method just define all the attributes of our classes Manager and Agent and call the methods. Remember, you can’t create an Employee object because abstract classes only can be used as base class for other classes. Our Manager and Employee classes inherits all the attributes and functions of our base class Employee.

This is the code if you want to take a look:

Module Abstract

Public MustInherit Class Employee

Public FirstName As String

Public LastName As String

Public ID As String

Public Age As Int16

Public Position As String

Public YearsOfExperience As Int16

Public Shared HoursPerWeek As Int16 = 48

Public Sub GetPosition()

Console.WriteLine(FirstName + ” “ + LastName + ” is a “ + Position)

End Sub

Public Sub GetAge()

Console.WriteLine(FirstName + ” “ + LastName + ” is “ + Age.ToString())

End Sub

MustOverride Sub GetSalaryPerWeek()

End Class

Public Class Manager

Inherits Employee

Public Overrides Sub GetSalaryPerWeek()

Dim salary, bonus As Double

salary = Employee.HoursPerWeek * 20.0

bonus = salary * YearsOfExperience / 100

salary += bonus

Console.WriteLine(FirstName + ” “ + LastName + ” salary is “ + salary.ToString())

End Sub

End Class

Public Class Agent

Inherits Employee

Public Overrides Sub GetSalaryPerWeek()

Dim salary As Double

salary = Employee.HoursPerWeek * 12.85

Console.WriteLine(FirstName + ” “ + LastName + ” salary is “ + salary.ToString())

End Sub

End Class

Sub Main()

Dim manager As New Manager()

Dim agent As New Agent()

With manager

.FirstName = “Nestor”

.LastName = “Martinez”

.ID = “1230-5897″

.Position = “IQ Manager”

.YearsOfExperience = 12

.Age = “26″

End With

With agent

.FirstName = “Fernando”

.LastName = “Romero”

.ID = “1230-0000″

.Position = “Sales agent”

.Age = “23″

End With

manager.GetPosition()

manager.GetAge()

manager.GetSalaryPerWeek()

Console.WriteLine(“————————-”)

agent.GetPosition()

agent.GetAge()

agent.GetSalaryPerWeek()

Console.ReadLine()

End Sub

End Module

This should be the result of this code:

Console

This is a simple way to create a csv file from a dataset. Just need to create an instance of the CSV class with the file path and the dataset as source and then apply the Create method and that’s it.

using System;

using System.Collections.Generic;

using System.Data;

using System.IO;

using System.Text;

namespace System.CSV

{

public class CSV

{

protected StreamWriter writer;

protected FileStream stream;

private string file_path;

private DataSet csvSource;

private const string filename_extension = “.csv”;

public DataSet Source

{

get { return csvSource; }

}

public string FilePath

{

get { return file_path; }

}

public CSV(DataSet source, string path)

{

csvSource = source;

try

{

stream = File.Create(path + filename_extension);

writer = new StreamWriter(stream, Encoding.Default);

}

catch (UnauthorizedAccessException unauthorized)

{

new UnauthorizedAccessException(“You aren’t authorize to access (if exists) or create this file: “ + unauthorized.Message);

}

catch (PathTooLongException toolong)

{

new PathTooLongException(“The name of the file is too long: “ + toolong.Message);

}

catch (ArgumentException invalidpath)

{

new ArgumentException(“Invalid path for the file: “ + invalidpath.Message);

}

catch (Exception general)

{

new Exception(“An exception ocurred: “ + general.Message);

}

}

public void Create()

{

StringBuilder content = new StringBuilder();

if (Source != null && (FilePath != null && FilePath.Length > 0))

{

if (Source.Tables.Count == 0)

{

DataTable table = Source.Tables[0];

int qtyColumns = (table.Rows[0] as DataRow).ItemArray.Length;

if (table.Rows.Count > 0)

{

foreach (DataRow currentRow in table.Rows)

{

string chunk = null;

for (int iterator = 0; iterator <= qtyColumns – 1; iterator++)

{

chunk = (string)currentRow[iterator];

if (iterator < qtyColumns – 1 && iterator > 0)

chunk += ” , “;

}

if (chunk != null)

content.Append(chunk);

}

}

writer.Write(content.ToString());

}

else

{

new Exception(“Only one table can be included in a CSV file”);

}

}

else

{

new Exception(“No source or file path was set”);

}

}

}

}

Applet – Calculator

During college, I did this Applet to learn how does this work. Some of the variables names are in Spanish.

This is simple, the Calculator class inherist from JApplet, create a Container for it. Create a new instance of the CalculatorPanel that inherits from JPanel and insert this instance to the container object that we created for the Calculator class. There are 2 internal classes inside CalculatorPanel, Numeros (Numbers in english) and Comandos (Commands in english). Numeros will be the handler of the event when a number has been clicked and Comandos will be in charged of the event when all others buttons are clicked ( +, -, etc);

Remember, Applets doesn’t have a main static function.

Here is the code:

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class Calculator extends JApplet {

public void init () {

Container contenedor = getContentPane();

CalculatorPanel cp = new CalculatorPanel();

contenedor.add(cp);

}

}

class CalculatorPanel extends JPanel {

JPanel ptexto, pbotones;

JButton botones;

JTextField text;

boolean start,numinsertado;

String lastcomando;

double resultado ;

ActionListener listener = new Numeros();

ActionListener comando = new Comandos();

CalculatorPanel() {

setLayout(new BorderLayout());

start = true;

numinsertado = true;

lastcomando = “=”;

resultado = 0.00;

pbotones = new JPanel();

ptexto = new JPanel();

text = new JTextField(20);

text.setEditable(false);

pbotones.setLayout(new GridLayout(4,4,3,3));

addButton(“0″,listener);

addButton(“1″,listener);

addButton(“2″,listener);

addButton(“3″,listener);

addButton(“4″,listener);

addButton(“5″,listener);

addButton(“6″,listener);

addButton(“7″,listener);

addButton(“8″,listener);

addButton(“9″,listener);

addButton(“.”,listener);

addButton(“+”,comando);

addButton(“-”,comando);

addButton(“/”,comando);

addButton(“*”,comando);

addButton(“=”,comando);

ptexto.add(text);

add(ptexto, BorderLayout.NORTH);

add(pbotones, BorderLayout.CENTER);

}

void addButton(String bot, ActionListener oyente) {

botones = new JButton(bot);

botones.addActionListener(oyente);

pbotones.add(botones);}

class Numeros implements ActionListener {

public void actionPerformed(ActionEvent ev) {

String etiqueta = ev.getActionCommand();

if (start) {

text.setText(“”);

start=false;

}

text.setText(text.getText() + etiqueta);

numinsertado = true;

}}

class Comandos implements ActionListener {

public void actionPerformed (ActionEvent exe) {

try{

String eti = exe.getActionCommand();

if (numinsertado){

double numero = Double.parseDouble(text.getText());

calculo (lastcomando,numero);

numinsertado = false;

}

start = true;

lastcomando = eti;

if (lastcomando.equals(“=”))

text.setText(resultado + “”);}

catch(Exception ex) {

JOptionPane.showMessageDialog(null,“Program can’t continue”,“ERROR”,JOptionPane.ERROR_MESSAGE);

text.setText(“”);

start = true;

numinsertado = true;

lastcomando = “=”;

resultado = 0.00;

}

}}

void calculo(String bt,double num1) {

if (bt.equals(“+”)) resultado +=num1;

else if (bt.equals(“-”)) resultado -=num1;

else if (bt.equals(“*”)) resultado *=num1;

else if (bt.equals(“/”)) resultado /=num1;

else if (bt.equals(“=”)) resultado = num1;

text.setText(resultado + “”);

}

}

Now, when you compile this code, 4 classes will be created. You need to embed this code to an HTML document.

When I was at college the applet tag wasn’t deprecated, it’s now. But this will work out:

<applet code = “Calculator.class” width =”270″ height =”270″>
</applet>

Just to let you know, the object tag should be used when trying to add java applets to html.

Older Posts »