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.

Adding a text editor… Done!

Filed Under (Programming) by fakhrul on 07-11-2008

A lot of good stuffs that available in a Web 2.0. Before this, a web is only use to give the information. There is no two ways communication between the writer and the readers. A small company only can show their profiles and some of their product’s images. No comments can be inserted. No AJAX and RIA can make the product’s image more interesting. Luckily for us, we can add a comment now. :D

FCKEditor

FCKEditor

Long introduction isn’t it? :D. Just now, I just added a text editor’s plugin (FckEditor) into my web applications. It is a great AJAX plugin. I think, some of you already know about this plugin. Nevermind, this post purposely for the beginner. Like me :)

If you are a developer and never yet use this FckEditor, I think you should try it. Your customer should like it. The text will return in “html text”,

<p><b>Some Title</b><br/>Test of</p>

Just save into your database and display it in your page. :P

Domain Driven Design

Filed Under (Programming) by admin on 29-10-2008

When I start working at this company (Mediu), I had learned a new approach of designing software.  It is a Domain Driven Design (DDD). The primary focus of DDD is the domain logic. The approach is, before we start to code, we need to define what kind of domain should have and how it should related each other. Than it will drive you away. :D. You can refer to this link for more information about DDD.

Actually, until now, I still had some grey area about DDD. As a result, yesterday, I just bought this book for my reference. Hope this book will help me to master the DDD better. :). adios…

NHibernate Using Attributes Mapping

Filed Under (Programming) by admin on 29-07-2008

Tagged Under :

Today I will show how to use the NHibernate with the Attributes mapping. This example will use the Test Driven Development (TDD) technique, and the Domain Driven Design. I will use the NUnit framework for the unit testing.

Preparation

  1. Download NHibernate assemblies files.
  2. Download and install NUnit

We will create 3 “Class Library” projects in this example.

  • “Example.Domain” - Contain the Domain Class, and the IRepository interface.
  • “Example.DataAccess” – Contain the Repository concrete class.
  • “Example.Test.Domain” – Contains the unit test.

Create an “Example.Domain” class library.

 

Delete the default Class1.cs file from the project and add refferences of

  • NHibernate.dll
  • NHibernate.Mappings.Attribute.dll

Add a new domain class name “Account.cs”. This class will have 4 properties.

  • Id – auto generate Guid (Primary Key)
  • Name – Account holder name
  • Type – Account type
  • Balance

Add a new interface name as “IAccountRepository.cs”. This interface should contain all the basic method to access the repository such CRUD.

Create an “Example.DataAccess” class library.

Delete the default Class1.cs file from the project and add the refferences:

  • NHibernate.dll
  • NHibernate.Mappings.Attribute.dll
  • Example.Domain.dll

Create a new xml file name “hibernate.cfg.xml”. This file will be used by NHibernate for it’s configuration such as connection string. Below is the xml.

Change the property of the “hibernate.cfg.xml” file to “Copy Always”.

Create the NHibernateHelper.cs, this helper will be use by the Repository concrete class to handle the session and transaction.

Create the AccountRepository.cs concrete class that implements the IAccountRepository interface.

Create an “Example.Test.Domain” class library. ”. This library will use for our unit test.

Add the references

  • NHibernate.dll
  • NHibernate.Mapping.Attributes.dll
  • NUnit.framework.dll
  • Example.Domain.dll
  • Example.DataAccess.dll

Create a new test class name “AccountTest.cs”.

Compile it and run the Nunit test. The unit test should throw an error because we not yet implement the Repository.

 

Now we will implement the AccountRepositry for “Add(Account acc)”

And then run the Unit Test.

Now it turns to green. If you notice that, there is no test method such as Assert.AreEqual(…) had been implement in here. But that is fine for now, because the nhibernate should thrown an exception if there is a problem. You can download the code here to continue the test unit.