C# WinForm and Sql Server CE Tutorial

Filed Under (Blog, Development, Programming) by fakhrul on 02-04-2010

1. Create a WinForm project.

Capture14-12-2009-13.45.4901-04-2010-21.57.13

* If you are using a 64 bit platform, make sure that the target platform is x86. If not you will be facing a problem later on.

2. Create a form like this.

Capture14-12-2009-13.45.4901-04-2010-22.03.35

3. Insert a new item, Local Database. Then click Add.

Capture14-12-2009-13.45.4901-04-2010-22.05.07

* Click cancel at Data Source Configuration Wizard, since we will not using this wizard for now.

4. Create table and columns like below.

Capture14-12-2009-13.45.4901-04-2010-22.08.14

5. Add reference “System.Data.SqlServerCe”.

Capture14-12-2009-13.45.4901-04-2010-22.09.51

6. Add this code at button Add.

private void btnAdd_Click(object sender, EventArgs e)
{
    string fileName = "Database1.sdf";
    string password = "";
    string connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", fileName, password);

    string sql = "insert into ValueList (ValueData) values ('" + txtValue.Text + "')";

    SqlCeConnection cn = null;
    try
    {
        cn = new SqlCeConnection(connectionString);

        SqlCeCommand cmd = new SqlCeCommand(sql, cn);

        if (cn.State == ConnectionState.Open)
            cn.Close();

        cn.Open();
        cmd.ExecuteNonQuery();
        MessageBox.Show("Data added");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        if (cn != null)
            cn.Close();
    }
}

7. Add this code at button Refresh.

private void btnRefresh_Click(object sender, EventArgs e)
 {
     string fileName = "Database1.sdf";
     string password = "";
     string connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", fileName, password);

     string sql = "select * from ValueList";

     SqlCeConnection cn = null;
     try
     {
         cn = new SqlCeConnection(connectionString);

         SqlCeCommand cmd = new SqlCeCommand(sql, cn);

         if (cn.State == ConnectionState.Open)
             cn.Close();

         cn.Open();
         SqlCeDataReader scdr = cmd.ExecuteReader();

         listView1.Items.Clear();
         while (scdr.Read())
         {
             listView1.Items.Add(new ListViewItem(new string[] {scdr.GetInt32(0).ToString(), scdr.GetString(1)}));
         }
         scdr.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     finally
     {
         if (cn != null)
             cn.Close();
     }
 }

8. You are done.

S.O.L.I.D Principles

Filed Under (Development, Programming) by fakhrul on 28-05-2009

What is S.O.L.I.D?

It is a collection of best practice, object oriented design principles which can be applied to your code.

S – SRP (Single Responsibility Principle)

There should never be more than one reason for a class to change.

O – OCP (Open Close Principle)

Software entities (Classes, Modules, Functions, etc.) should be open for extension but closed for modification.

LLSP (Liskov Substitution Principle)

Functions that use… references to base classes must be able to use objects of derived classes without knowing it.

IISP (Interface Segregation Principle)

Clients should not be forced to depend upon interfaces that they do not use.

DDIP (Dependency Inversion Principle)

High level modules should not depend upon low level modules. Both should depend upon abstraction.

How to protect your software?

Filed Under (Blog, Development, Programming) by fakhrul on 21-05-2009

During dinner last night, my colleagues and me had discussing about the software protection and licensing. We want to create a license for our application so that we can charge our customer per license. The question is, how can we do that?

 

There are several options that had been highlight last night.

1. Using a dongle. It is a hardware that can be plug into the usb port. Anybody want to use the software must plug in the dongle.

2. For a web base application, we can limit how many user can login in one time. Track the active user session. If over limit, block the access.

3. Encrypted the password for those who can use the systems.

 

After googling, I had found out some other interesting point on how to protect the software.

Basically, there are 2 common ways to protect the software (for executable file)

1. Using 3rd party software.

2. Build your own protection in your code.

 

Using 3rd party software.

There are a lot of 3rd party software that we can use to protect our software. The utilities may include the licensing and obfuscator. Below is some of the tools

1. Intellilock  - A lot of developers in the internet had recommended this tools.

2. Solo Server

3. Microsoft Licensing – One of developer said that “It is crazy expensive for small business”

4. Microsoft Shareware Starter kit

5. Aspack

 

Build your own protection in your code.

Below are some of common ways on how to do a protection in your own code.

1. Hardware protection

Using hardware mechanism such as Dongle. Dongle can be use as a key to start the software. Your software will be sell together with the dongle. So the licensing is base on how many dongle. To run the software, the verification thru dongle need to be done first.

pros: The software can use anywhere if you have a dongle.

cons: Hardware cost + development time.

 

2. Online registration/verification code. Verify through online once.

pros: Cheap

cons: Need an internet connection.

 

3. Encrypted key that holds portion of program algorithm. (can’t just skip over the check)

Common way to do the encryption key is using a public-private key.

  • - To generate the key, we can base on Processor Id or Hard disk Id or MAC address.
  • - You can also put the expire date, and other extended data in your key. Encrypt it with MD5 or others algorithm so that customer cannot simply read and change the expiry date.

pros: Cheap

cons: Extra development time

4. Controlling your expiry date base on when it build.

If you are hosting your homepage on a server that you control, you could have the downloadable trial-version of your software automatically compile to a new binary every night. This compile will replace a hardcoded datetime-value in your program for when the software expires.

pros: Easy

cons: User can cheat by changing the date on you computer but most people won’t do that.

8 Best Quotes For Developer

Filed Under (Blog, Development) by fakhrul on 13-04-2009

1. Learning is a treasure that will follow its owner everywhere.

2. The only way to predict the future is to invent it.

3. Learning is easier than doing and don’t confuse the two.

4. Develop a passion for learning, if you do, you will never cease to grow.

5. Knowing is not enough, we must apply. Willng is not enough, we must do.

6. I never teach my pupils, I only attempt to provide the conditions in which they can learn.

7. The man who can make hard things easy is the educator.

8. Don’t just learn the tricks of the trade. Learn the trade.

PC reboot when installing the Sql Server Express 2005

Filed Under (Development) by fakhrul on 10-04-2009

Problem

Today, I had faced a weird problem when installing the Sql Server Express 2005 (SqlExpr).  I cannot install the SqlExpr into the PC. I had tried 2 times at the difference PC and both are failed.

The problem happens at the half way of the installing process. It suddenly restart the PC by it self. There is no signal or dialog box prompting that there is an error during the installation.

My colleague suggested to me to upgrade the PC’s memory. Current the memory is 512MB. Then, I re-check the requirement spec for SqlExpr from Microsoft website. Here is it:


SQL Server 2005 (32-bit)

Processor type1

Processor speed2

Memory (RAM)3

SQL Server 2005 Enterprise Edition4
SQL Server 2005 Developer Edition
SQL Server 2005 Standard Edition

Pentium III-compatible processor or higher

Minimum: 600 MHz
Recommended: 1 GHz or higher

Minimum: 512 MB
Recommended: 1 GB or more
Maximum: Operating system maximum

SQL Server 2005 Workgroup Edition

Pentium III-compatible processor or higher

Minimum: 600 MHz
Recommended: 1 GHz or higher

Minimum: 512 MB
Recommended: 1 GB or more
Maximum: Operating system maximum

SQL Server 2005 Express Edition

Pentium III-compatible processor or higher

Minimum: 500 MHz
Recommended: 1 GHz or higher
Minimum: 192 MB

Recommended: 512 MB or more
Maximum: Operating system maximum

SQL Server 2005 Express Edition with Advanced Services

Pentium III-compatible processor or higher

Minimum: 600 MHz
Recommended: 1 GHz or higher

Minimum: 512 MB
Recommended: 1 GB or more
Maximum: Operating system maximum


So, the PC’s spec had meet the requirement (at least the minimum requirement :)). So it is not because of memory. Even though if we upgrade the memory, the problem will still be the same.

But, to make sure  this is not cause by memory. (My level of confidence is so poor), I had tried to install the SqlExpr at the 2nd PC which memory is 2GB. Unfortunately, the same problem happens. Its reboot again.

Solution
Later, I had look at the Event Viewer log. The log told that there is an error when accessing the temporary file.

Actually, when you double click the SQLEXPR.EXE (SqlServ installer), it will extract the installation folder into some temporary folder. Normally the folder name is some GUID. So this temporary folder will be use during the installation process. Because of some reason (I don’t know why), the installer can’t read the file in the temporary folder and cause it to reboot.

Later I had decided to extract the installation file to a certain folder manually. And then, run the setup.exe. Thanks god, it is work. Pheww.. At last, I had successfully installed the SqlServ.

To extract the file manually, you can give this argument “SQLEXPR.EXE /x:c:\sqlinstaller” in the command prompt. This argument will extract the installation file into “C:\SQLINSTALLER\”.

Wassalam.

How to use XmlSerializer Class?

Filed Under (Development) by fakhrul on 23-03-2009

For our new system, we are planning to use the XmlSerializer Class to serialize our object into the database. So what is XmlSerializer can do?

Definition

Serializes and deserializes objects into and from XML documents. The XmlSerializer enables you to control how objects are encoded into XML.

This is a very useful class if you want to persist your object. You can store your object either in the text file or maybe in database. Later, if you want to get your object back, you can deserialize it. In our case, we prefer to put in the database.

How to use it?

I had made some simple program to show how to use the XmlSerializer Class. This will serialize to the xml file. You can also refer to the MSDN to know more. Here is the code snippets:

using System;

using System.Xml.Serialization;

using System.IO;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Press any key to start serialize...");

Console.ReadKey();

DoSerializeToFile();

Console.WriteLine("Press any key to start deserialize...");

Console.ReadKey();

DoDeserializeFromFile();

Console.ReadKey();

}

private static void DoDeserializeFromFile()

{

try

{

Console.WriteLine("Start deserialize process");

// Initialize the XmlSerializer

XmlSerializer serializer = new XmlSerializer(typeof(Student));

//Initialize  the text reader. This will read the student.xml file in your BIN folder

TextReader reader = new StreamReader("student.xml");

//Start the deserialize

Student student = (Student)serializer.Deserialize(reader);

//display the result

Console.WriteLine("Date\t" + student.DateJoin.ToShortDateString());

Console.WriteLine("Current Term\t" + student.CurrentTerm);

for (int i = 0; i < student.ResultByTerm.Length; i++)

{

Console.WriteLine("Current Term\t" + student.ResultByTerm[i]);

}

Console.WriteLine("Deserialize completed");

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

private static void DoSerializeToFile()

{

try

{

Console.WriteLine("Start serialize process");

// Initialize the XmlSerializer

XmlSerializer serializer = new XmlSerializer(typeof(Student));

//Initialize  the writer. This will create the student.xml file in your BIN folder

TextWriter writer = new StreamWriter("student.xml");

//Create a Student object

Student student = new Student();

student.DateJoin = DateTime.Now;

student.CurrentTerm = 2;

student.ResultByTerm = new int[2];

student.ResultByTerm[0] = 4;

student.ResultByTerm[1] = 5;

//Serialize to writer (write to xml)

serializer.Serialize(writer, student);

//clise writer

writer.Close();

Console.WriteLine("Serialize completed");

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

}

}

[XmlRootAttribute]

public class Student

{

[XmlAttribute]

public DateTime DateJoin { get; set; }

[XmlAttribute]

public int CurrentTerm { get; set; }

[XmlArrayAttribute]

public int[] ResultByTerm { get; set; }

}

}

Introduction to Object Relational Mapping (ORM) in .NET

Filed Under (Development, ORM) by fakhrul on 21-03-2009

Definition

By refering to the wikipedia, the Object Relational Mapping (ORM) is defined as

A programming technique for converting data between incompatible type systems in relational databases and object-oriented programming languages. This creates, in effect, a “virtual object database” that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.

ORM is place between the database and the .NET object. For example, we have a class name as Student and the table name as TBL_STUDENT. The ORM are used to map the class Student and the TBL_STUDENT. There are 2 way to map the object and the table, one way is using the xml file, and other is using the .NET atrribute. In Nhibernate, I am using the attribute mapping because it is much easier.

 

Why you use it?

  1. You can apply the Domain Driven Design (DDD) easily. 
  2. ORM generate the sql statement for you.
  3. It is price less. Free. There are a lot of open source for ORM.
  4. Support for multiple database. It’s flexible to change which DBMS you want to use. All setting is in the config files.
  5. Good performance. As you know, the ORM frameworks are develop from the expert all over the world. So you don’t worry about it. The only thing you need to worry is, how to use it. (Fortunately, almost all of the API was documented well.)
  6. The source code are provided (for open source ORM). You have the code and you can change it if you are need to do.
  7. Support are available. You can ask a question and discuss anything regarding to the ORM in the forum. 
  8. Faster development process. Forget the learning curve because I think you only need not more than a week to know how to use it.  Once you now, you will be suprise how fast it can be. :D

 

Last word

There are a lot of ORM framework for .NET. For example Spring.Net, NHibernate and  Castle ActiveRecord. I had experience in using NHibernate and Castle ActiveRecord. Castle ActiveRecord is actually sit on top of NHibernate. It was build by a group of geek to simplify the use of NHibernate. 

There are also a lot of tutorial and reference you can get from the internet. You can google it, the keyword is “ORM”, “NHibernate”, “Castle active record”. 

Hope this post had give you an idea about the ORM. Thanks.

 

Other links

http://aspalliance.com/1069_Introducing_Object_Relational_Mapper.1

http://en.wikipedia.org/wiki/Object-relational_mapping

http://www.hibernate.org/343.html

http://www.castleproject.org/ActiveRecord/

Using Castle ActiveRecord and MySql in ASP.NET

Filed Under (Development, ORM) by fakhrul on 07-03-2009

I had started a development of my project using the Asp.Net (Code behind), Castle ActiveRecord and MySql. Here are some of the important points for configuration to make sure it will runs smoothly.

Firstly you need to have all the necessary library:

  1. Castle Active Record
  2. My Sql Connector for .NET

Note: You can put all the assemblies either in the GAC directory or you can create a new folder in your solution folder and puts in there. You can name it as “Libraries”. I suggest you to create a new folder in your solution directory and put every dependency library there. By doing this, you can minimize the chances of missing library.

Secondly, you need to add the reference of

1. Castle Active Record

  • Castle.ActiveRecord.dll
  • Castle.Core.dll
  • Castle.Components.Validator.dll
  • Castle.DynamicProxy.dll
  • NHibernate.dll
  • Iesi.Collections.dll
  • log4net.dll

2. MySql Connector

  • MySql.Data

Then, add the web.config as below


<configuration>

<configsections>
<section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/>
</configsections>

<activerecord isWeb="true">
<config>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.MySqlDataDriver"/>
<add key="hibernate.dialect" value="NHibernate.Dialect.MySQLDialect"/>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.connection.connection_string" value="Database=DB_NAME;Data Source=DB_IP;User Id=DB_LOGIN;Password=DB_PASSWORD"/>
</config>
</activerecord>

</configuration>

Lastly, add the ActiveRecord initialization inside your Global.asax


protected void Application_Start(object sender, EventArgs e)
{
Castle.ActiveRecord.Framework.IConfigurationSource cfgSource = Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler.Instance;

Castle.ActiveRecord.ActiveRecordStarter.Initialize(new[] { System.Reflection.Assembly.Load("Sample.Domain") }, cfgSource);

}

Generating sql using sql

Filed Under (Development) by fakhrul on 18-12-2008

Today is my “SQL script” day. A little bit of C# coding and the rest is a SQL script. My colleague needs to update her table for 99 rows. Of course she can change it one by one using a normal form but that will waste a lot of time. So I decided to make a script for her.

The script is like this:


select s.MatrixNo, u.Name,
'update mdl_user set idnumber = ''' + cast(s.MatrixNo as varchar(100)) + ''' where username = ''' + cast(u.Name as varchar(100)) + ''''
from Student s
inner join User u
where s.MatrixNo in
(
'MMU01223',
'MMU01224',
...
'MMU00004',
'MMU00977',
)

After execute this, it will generate the other script in column no 3.

It will produce something like this:


update mdl_user set idnumber = 'A4583E1C-EF25-4476-937B-15FAC1509303' where username = 'userName1'
update mdl_user set idnumber = 'A9145152-1354-487D-B5D7-2A619D46FDBE' where username = 'userName2'
...
update mdl_user set idnumber = 'E202DC3C-A157-4C13-AF32-9B6E011D2C36' where username = 'userName3'
update mdl_user set idnumber = '9533C44E-F3E2-49FD-A012-9B6E011D2C3F' where username = 'userName4'
update mdl_user set idnumber = 'A6D46AB8-14B7-4DAF-A362-9B6E011D2C3F' where username = 'userName5'
update mdl_user set idnumber = '148153AF-84C1-4833-8F2F-9B6E011D2C43' where username = 'userName6'

With this, we had saved a lot of time. :)

Check Browser Compability

Filed Under (Development, Tools) by fakhrul on 03-11-2008

I had been informed by my client (also is my friend) that my web UI is not aligned properly when he opened from his old PC. I am thinking for a while and then realized that maybe it is a cross platform problem. 

Then yesterday, I went to his office and had a look on it by myself. I am surprise when I looking on it, it’s totally unaligned. He opened it using MSIE 6.0.  Yes, my assumption is correct.  It is a common issue in the web development.

Today, while reading a blog. I’d found a good tool to check the browser compability. It’s a web application tool and no need to install. What you need to do is, insert the url. Select what type of browser that you want to test and then click submit. This will generate the screenshots of your url that open in a different browser.

Below is some screen shot that I had did with my web.

Firefox 2.0

Internet Explorer 7.0

Internet Explorer 6.0