29 June 2008

ASP.NET MVC - hint #2

Creating own Html Helper methods

To create own Html Helper method, we just must create a new static class which can be called "ExtendedHtmlHelper", then by using the new feature available from.Net Framework 3.0 we can extend the default Html Helper class definition.

public static string TextBoxCSS(this HtmlHelper helper, string name, string value, string cssClass, IDictionary<string, object> attributes)

{

    if (attributes == null)

        attributes = new Dictionary();

    attributes.Add(new KeyValuePair("class", cssClass));

    return helper.TextBox(name, value, attributes);

}


This is not all what we must do to be able to use the new TextBoxCSS method. Another thing is making our class visible for the View. We can realize this on two ways. The first bases on adding the "ExtendedHtmlHelper" namespace to the project web.config. This namespace should be exactly placed in

<system.web>

  <pages>

    <namespaces>

      <add namespace="Example.Utils" />

    </namespaces>

  </pages>

</system.web>


The second way is easier because it needs from us only replacing the current namespace of "ExtendedHtmlHelper" class with "System.Web.Mvc".

28 June 2008

ASP.NET MVC - hint #1

Assigning CSS class to Html Helper methods

When we decide to use Html Helper methods we can have a need to assign the CSS class to those methods. We can realize it by using the method argument which can be an object or an IDirectory called htmlAttributes. Assigning the CSS class attribute is pretty easy and we can do it by typing
new { class="myCssClass" }
If you have tried to do this in that way, you would probably noticed that the Visual Studio environment tries to inform you that this kind of the statement is not allowed. It's that because the word "class" interferes with other meaning of this word which is the class definition in C#. To use the above statement anyway we can do this in two ways. The first one is to precede the "class" word with char "@" so the new statement would look like this below.
new { @class="myCssClass" }
The second bases on using the upper letter of "C". I have to mention that this kind of the statement won't be agreeable with the XHTML standards. Below you can find the new working statement.
new { Class="myCssClass" }

06 February 2008

Adding ASP.NET MVC template to Visual Studio 2008 EE

As you found out after reading Readme file while installing ASP.NET Extensions there is no template projects which support ASP MVC for Visual Studio 2008 Express Edition. To solve this small problem I have browsed the internet to find other sources which can help me to build my own templates.

The best result I have got by visiting this page. I have also found templates which you can place in:

"My Documents"\Visual Studio 2008\Templates\ItemTemplates\Visual Web Developer - MvcViewPage.
"My Documents"\Visual Studio 2008\Templates\ProjectTemplate\Visual Web Developer - WebDevMvcAspNetSite

that will help you to start playing with MVC.

Labels: ,

07 December 2007

Data Pomp Import & Export in Oracle database

Today I would like to show how to export and import a data from oracle instance. To accomplish this task I will use the expdp and impdp. So let's start.

The first task:
1. Create a directory where that dmp file should be stored. (User who is going to export has to have granted privileges to writing and reading to this directory).

mkdir /home/exports

2. Create a mapped directory on database side. (User who is going to do the export and import has to have privileges to "CREATE ANY DIRECTORY").

conn sys/pass@ora10g as SYSDBA
alter user scott identified by tiger account unlock
grant CREATE ANY DIRECTORY to scott


create or replace directory dmpDir as '/home/exports/';

grant read, write on directory


Export and Imports commands
1. Tables:

expdp scott/tiger@ora10g tables=Table1,Table2 directory=dmpDir dumpfile=scottDmp.dmp logfile=scottDmpExp.log

impdp scott/tiger@ora10g tables=Table1,Table2 directory=dmpDir dumpfile=scottDmp.dmp logfile=scottDmpImp.log TABLE_EXISTS_ACTION=APPEND

TABLE_EXISTS_ACTION - determines how the import should be executed when the importing object already exists. Arguments: SKIP, APPEND (default), TRUNCATE and REPLACE.

2. Schemas:

expdp scott/tiger@ora10g schemas=SCOTT directory=dmpDir dumpfile=scottDmp.dmp logfile=scottDmpExp.log

impdp scott/tiger@ora10g schemas=SCOTT directory=dmpDir dumpfile=scottDmp.dmp logfile=scottDmpImp.log TABLE_EXISTS_ACTION=APPEND

3. Database:

expdp scott/tiger@ora10g full=Y directory=dmpDir dumpfile=scottDmp.dmp logfile=scottDmpExp.log

impdp scott/tiger@ora10g
full=Y directory=dmpDir dumpfile=scottDmp.dmp logfile=scottDmpImp.log TABLE_EXISTS_ACTION=APPEND

If you would like to get more info about parameters, please type impdp help=y or expdp help=y.

good luck

Labels:

25 November 2007

2. Serialization - SoapFormatter

SoapFormatter serializes an object to a file with XML based format. This fact helps using it in SOAP protocol, which is intended to be read by variety of platforms. Another advantage to supports SoapFormatter is fact that, it traverses more successfully firewalls then BinaryFormatter. Using SoapFormatter requirets to add a reference to the System.Runtime.Serialization.Formatters .Soap.dll.

will be continued...

11 October 2007

1. Serialization - BinaryFormatter

Serialization is a process which stores an object as linear sequence of bytes. Deserialization is an opposite process which converts those bytes into the object. Those methods let us simply save object into a stream and then i.e. move it to another computer through the network.
The first way to serialize objects is using the BinaryFormatter. This formatter is the most efficient solution. Below I demonstrate how to use with Person type.
First definition of Business object:

[Serializable]

public class Person : IDeserializationCallback

{

#region Fields

private string _name;

private string _surname;

private int _age;

[NonSerialized]

private int _totalDays;

#endregion


#region Properties

public string Name

{

get { return this._name; }

}

public string Surname

{

get { return this._surname; }

}

public int Age

{

get { return this._age; }

}

public int TotalDays

{

get { return this._totalDays; }

}

#endregion


#region Constructors

public Person(string name, string surname, int age)

{

this._name = name;

this._surname = surname;

this._age = age;

}

#endregion


#region Methods

public void UpdateTotalDays()

{

this._totalDays = this._age * 365;

}

#endregion


#region IDeserializationCallback Members

public void OnDeserialization(object sender)

{

this.UpdateTotalDays();

}

#endregion

}


As you can see this type implements IDeserializationCallback interface. This interface contains only one method OnDeserialization, which is invoked when object is deserializing. So as a content of this method, we can put any initializing methods i.e. the Person type has a TotalDays property but this value in not serialized. That means if we serialize object and then deserialize it we will not able to see old value of TotalDays. Normally this property is counted by launching UpdateTotalDays method. So by taking advantage of IDeserializationCallback we can point that method to be execute while deserializing.
Second step is a static Serializer type:

public static class Serializer

{

#region Fields

public static readonly string SerializePath = @"c:\object.data";

#endregion

#region Methods

public static void Serialize(object graph)

{

FileStream serializationStream = new FileStream(Serializer.SerializePath, FileMode.OpenOrCreate);

BinaryFormatter bf = new BinaryFormatter();

bf.Serialize(serializationStream, graph);

serializationStream.Close();

}

public static object Deserialize()

{

FileStream serializationStream = new FileStream(Serializer.SerializePath, FileMode.Open);

BinaryFormatter bf = new BinaryFormatter();

object graph = bf.Deserialize(serializationStream);

serializationStream.Close();

return graph;

}

#endregion

}

This type is responsible for saving to and loading from object.data file into the Person type. Below I pasted the NUnit test which shows how the Serializer type works.

[Test]

public void SerializeAndDeserializeTest()

{

Person p = new Person("Jarek", "Jurczyk", 26);

p.UpdateTotalDays();

Assert.AreEqual("Jarek", p.Name);

Assert.AreEqual("Jurczyk", p.Surname);

Assert.AreEqual(26, p.Age);

Assert.AreEqual(9490, p.TotalDays);

Serializer.Serialize(p);

FileInfo fi = new FileInfo(Serializer.SerializePath);

Assert.AreEqual(true, fi.Exists);

p = null;

Assert.IsNull(p);

p = Serializer.Deserialize()as Person;

Assert.AreEqual("Jarek", p.Name);

Assert.AreEqual("Jurczyk", p.Surname);

Assert.AreEqual(26, p.Age);

Assert.AreEqual(9490, p.TotalDays);

}


More information:
  • If you don't want to serialize field set the attribute [NonSerialized] (you can apply on private fields)
  • Never change the name of field or class if the object is already serialized
  • Never remove serialized fields
  • If class has already been serialized add the new field but use the [OptionalField]
  • Don't apply the [NonSerialized] for fields which have been already serialized in previous version


In the next post I will describe the SoapFormatter

Labels: , ,

03 October 2007

Unit testes and events

While my last project I met a problem with applying unit testes to asynchronous methods. My program had to load a big amount of data from database. The simple method DownloadData took too much time so I had decided to build and invoke asynchronous method like BeginDownloading. As the data was downloaded the OnDownloaded event was raised. The class had look similarly to this one below.

public class DatabaseFacade

{

public event EventHandler OnDownloaded;

public DatabaseFacade() { }

public virtual void BeginDownloading()

{

Console.WriteLine("Begin downloading");

System.Threading.Thread.Sleep(2000);

this.RaiseOnDownloaded();

}

protected virtual void RaiseOnDownloaded()

{

if (this.OnDownloaded != null)

this.OnDownloaded(this, new EventArgs());

}

}



Now it is the main problem how to test the type of DatabaseFacade with unit tests. It is not really easy because of the sequence invoking each test method. To solve this problem we have to apply the ManualResetEvent. The base task of this class is block the executing the method till the me object call Set which means that all waiting threads can proceed. If the method Set will not called in i.e. 5 seconds then the testing method will stop waiting for the call from ManualResetEvent and carry on executing. Below I attache an example:

[Test]

public void BeginDownloadingTest()

{

ManualResetEvent me = new ManualResetEvent(false);

bool raised = false;

DatabaseFacade df = new DatabaseFacade();

df.OnDownloaded += new EventHandler(delegate(object sender, EventArgs e)

{

raised = true;

Console.WriteLine("Done");

me.Set();

});

df.BeginDownloading();

me.WaitOne(5000, false);

Assert.IsTrue(raised);

}

Labels: , ,

20 September 2007

Compressing files

.Net framework supports two kinds of compressing types: GZipStream and DeflateStream. The different between these types is that the first one allows for headers that include extra information that might be helpful to decompress a file with the widely used gzip tool. Both of them use the same algorithm and both are free of patent protection so you can use them in commercial projects.
Below I will write the method to compress and decompress any data or file with using GZipStream. If you want to use the DeflateStream simply change the type in this code from GZipStream on DeflateStream.

public static void Compressing(string source, string destination)

{

FileStream src = null;

FileStream dest = null;

try

{

src = File.OpenRead(source);

dest = File.Create(destination);

GZipStream compress = new GZipStream(dest, CompressionMode.Compress);

int b = src.ReadByte();

while (b != -1)

{

compress.WriteByte((byte)b);

b = src.ReadByte();

}

}

finally

{

if (src != null)

src.Close();

if (dest != null)

dest.Close();

}

}

public static void Decompress(string source, string destination)

{

FileStream src = null;

FileStream dest = null;

try

{

src = File.OpenRead(source);

dest = File.Create(destination);

GZipStream compress = new GZipStream(src, CompressionMode.Decompress);

int b = compress.ReadByte();

while (b != -1)

{

dest.WriteByte((byte)b);

b = compress.ReadByte();

}

}

finally

{

if (src != null)

src.Close();

if (dest != null)

dest.Close();

}

}

Labels:

18 September 2007

Widening vs Narrowing

In .NET environment we have two ways for converting from one value type to our custom type. The first way is widening (implicit), by this conversions we don't lose precision i.e.

Int16 i16 = 0;

Int32 i32 = 100;

i32 = i16;


The second one is Narrowing (explicit) where is possible to lose some precision i.e.

Int16 i16 = 0;

Int32 i32 = 100;

i16 = (Int16)i32;



Below I will show you how to extend our type of explicit and implicit conversion.

class TestClass

{

public int ValueA;

public TestClass()

{

this.ValueA = 0;

}

public static explicit operator int(TestClass arg)

{

return arg.ValueA;

}

public static implicit operator TestClass(int arg)

{

TestClass t = new TestClass();

t.ValueA = arg;

return t;

}

}

Labels:

Boxing and unboxing

As everybody should know boxing and unboxing are tasks which take some valuable time. Of course we will not feel any different in invoking this function just couple times, but in case of hundred thousands invokes that can be noticeable. To build a faster programs I will describe couple good practices which you should be remember and use in this surface.
  • use overload methods for different arguments instead of using one which can accept only object argument

public virtual void DoIt(int i) { }

public virtual void DoIt(double d) { }

public virtual void DoIt(string s) { }

  • use generic types instead of using objects arguments

public List<int> collection = new List<int>();

  • overload methods ToString, Equals and ToHash in structurs to avoid boxing

struct TestStruct

{

public int ValueA;

public int ValueB;

public TestClass()

{

ValueA = 0;

ValueB = 0;

}

public override string ToString()

{

return String.Format("{0} {1}", this.ValueA, this.ValueB);

}

public override bool Equals(object obj)

{

if (obj == null)

return false;

if (this.GetType() != obj.GetType())

return false;

TestStruct comperable = (TestStruct)obj;

if (!this.ValueA.Equals(comperable.ValueA) || !this.ValueB.Equals(comperable.ValueB))

return false;

return true;

}

public override int GetHashCode()

{

return this.ValueA ^ this.ValueB;

}

}

17 September 2007

Dynamically calling generic methods

Generic methods are very useful in building OO applications. Last time while factoring my old code I found some problems to invoke a method with generic type. So when I found this solution I decided to share with you. This sample is very easy to implement in many ways but my point is to show you how to use method with dynamical type.

In example I have a class Display.

public class Display

{

public string display(T value)

{

return string.Format("value: {0} type: {1}", value, typeof(T).Name);

}

}


Now I would like to invoke the "Display" method with variable type i.e. int, string, double and so on. The easiest way is replacing i.e. T with int.

[TestFixture]

public class DisplayTest

{

[Test]

public void Display_display_Test()

{

Display d = new Display();

string result = d.display<int>(100);

Assert.AreEqual("value: 100 type: Int32", result);

}

}


I know that is now correct answer because I have to know which type is going to be used. The right answer it is an example below.

[TestFixture]

public class DisplayTest

{

[Test]

public void Display_display_Test()

{

Display d = new Display();

int i = 100;

MethodInfo mi = typeof(Display).GetMethod("display");

MethodInfo miGeneric = mi.MakeGenericMethod(i.GetType());

string result = (string)miGeneric.Invoke(d, new object[] { i });

Assert.AreEqual("value: 100 type: Int32", result);

}

}

30 July 2007

Programming Languages Ranking

Browsing the Internet I have found a helpful link for people who are choosing which programming language to choose.
Bye

Labels:

09 March 2007

Spring, Nhibernate, log4net - PART I

Finally I had some more time to bound these tools. First thing which I did was launching the spring. It was quiet easy to do. I downloaded the newest version of the framework from here.
After unzipping the package I created a new console project where I added the new references from spring framework (Spring.Core, Common.Logging, Common.Logging.Log4Net). To make this framework working the first thing which I had to do was adding App.config (application configuration file). This file is a main configuration file which can be split into sections. Spring uses couple sections like context, objects, parsers, resources and many others. For my example I will use only context and objects. In first section you are able to define where the objects definition is, the second one define all objects uses in application. To get more info refer to www.springframework.org. To don't waste more time I will paste my configuration file:

<configuration>

<configsections>

<sectiongroup name="spring">

<section name="context" type="Spring.Context.Support.ContextHandler , Spring.Core">

<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core">

</section>

</section>

<spring>

<context>

<resource uri="config://spring/objects">

</resource>

<objects xmlns=" http://www.springframework.net">

</objects>

</context>

</spring>
</sectiongroup>

</configsections>

</configuration>


As you can see in my simple configuration file there is no objects defined yet. They will be add later on. Another thing which I would you like to recommend is adding the definition schema of spring objects to the system. This will avoid making the mistakes that you probably made while defining objects. To do it you have to simply copy the file spring-objects.xsd to {Microsoft Visual Studio 8}\Xml\Schemas, after that restart the visual studio environment.
Ok when my configuration file is prepared it can build the IApplicationContext. This interface provides the same functionality as the IObjectFactory and complements it which features as such AOP and message resources. To get more info go to spring homepage. To get the IApplicationObject you have to in the begging of the Main method type something like that:

static void Main()
{
IApplicationContext ctx= ContextRegistry.GetContext();
}

Good habit is wrapping ctx object as public properties, to be available for all classes.
In next part of this article I will bring closer the log4net and nhibernate sections.

Labels: ,

21 February 2007

INotifyPropertyChanged Interface

Sometimes in my applications I use some binding mechanism. It helps me to build the huge forms. To show the way how it works at the begging I will create a small class Person which contains one property Surname linking with textbox.

public class Person

{

private string _surname;

public string Surname

{

get { return this._surname; }

set { this._surname = value; }

}


public Person(string surname)

{

this._surname = surname;

}

}

Next step is creating a new form on which will be placed the earlier mentioned textbox control. After that we have to simply override the OnLoad method.

protected override void OnLoad(EventArgs e)

{

base.OnLoad(e);

this.textBox1.DataBindings.Add("Text", this.p, "Surname");

}


Ok it is done. We can test it. Everything look quite nice, but what would happen if we change the p.Surname during application is running. Nothing. That's the problem the changes are not affected if we change the property Surname. To fix it we have to equip our Person class with INotifyPropertyChanged interface. This interface will add a new event to our class body. So if we have a new event We must use it.

public string Surname

{

get { return this._surname; }

set

{

this._surname = value;

if ( this.PropertyChanged != null)

this.PropertyChanged(this, new PropertyChangedEventArgs("Surname"));

}

}


Now when we start the application and we change Surname property we will find out that the textbox control has been changed too. That is what we wanted. Notice that PropertyChangedEventArgs constructor takes one string arg "PropertyName". This argument should be exact name of the property which is already changing.
Good luck

14 February 2007

Valentin's day

This day is good day for writing something about my private live especially my wife. The 10th June 2006 is a day when once in my life I was sure of what I had said. On this day I said "Yes" which meant that I want to spend my whole live with me wife - Aga.Since this time I have never regret my decision, oops! maybe once but not any more. It was day after married when I could not be on my last exam, so I got bad note, but after this time was only flours and butterflies. :) Currently we live in small town where is about 20k people. You can see our building here. This place is great everywhere is near and only familiar faces.
I love taking pictures so below I place my Aga picture.



And another one :)



ko
.ci.

It's almost over ...

A sigh of relief.
For about six months I have been making my own Engineering thesis. It consists of program and theory document. The program is written in .NET (C#) and based on Microsoft SQL Server 2005. The main thing which it does, is tracking working-hours of company stuff and registering them into database.(I will bring closer this application soon on blog with screenshots and pieces of code) The second part is pure text with couples screenshots and some UML charts. I sent my last part of Engineering thesis to my professor couple days ago. Currently I look forward to having any response from him to correct some small details and I will be ready to defend it. I think I will get my Engineering degree in march.

29 December 2006

Work at Accenture

At the beginning of the month I went to Accenture Company Office localized in Warsaw. This company is one of the biggest company in the World making a software in Java, .NET, C++ ... to get more info go there: http://www.accenture.com . I was invited to do some tests of effectiveness and have a interview about giving me a job. The tests waren't hard but time which was spent to do them had been walking away so quickly. To do I had questions about SQL (relations, aggregations, inner, outer joins) in fact them ware quite easy but the time had been killing me, next I had to describe some terms like SSL and others which I completely forgot now, next c++ , playing with incrementing and decrementing toys, pointers, OOP, after c++ on my plate hit a .NET, here I had got boxing and unboxing objects, and others which I do not remember now, next were ASP, CSS, Java Script I am now going to describe all of them because, first I do not remember them, second them were easy:). The last test was linked with unix and here I crashed my self. The problem was not that I do not know unix but .... I did not have manual pages hehehe. :) The last step of my voyage to Warsaw was interview, speaking about technologies, patterns, solutions and of course questions like why ... when ... how much .. . Ok couple days ago I got a phone from Warsaw the very kind women congratulated me pasting my tests successfully, she had said that I able to work for them. All conditions like money, medical insurance, eLearning platform and many others are so cool ... but like always decisions are not easy. I have to think of it ...

20 December 2006

.NET 3.0 on the Board

Since the .net 3.0 framework is available I have been sticking around to install it. Yesterday I finally did it. I had not to much time to play with that but the X-mas time is coming on, that means I will have more time to spare for it.

13 December 2006

BindingList

Binding is very useful stuff but I often forget of using it. The last time was different, I used and I met a little problem with synchronizing ListBox with List. Adding a new object to the list did not have any effect in my ListBox control. So I went to speak with my friend - google. He said that I should use a BindindList instead of List. I did it and it really works. The code looks like:

1 public class FrmMain : Form

2 {

3 private BindingList _objects;

4

5 private FrmMain()

6 {

7 InitializeComponent();

8

9 this._objects = new BindingList();

10

11 this.lbObjects.DataSource = this._objects;

12 this.lbObjects.DisplayMember = "Name";

13 this.lbObjects.ValueMember = "Id";

14 }

15 }