C# WinForm and Sql Server CE Tutorial
Filed Under (Blog, Development, Programming) by fakhrul on 02-04-2010
1. Create a WinForm project.
* 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.
3. Insert a new item, Local Database. Then click Add.
* Click cancel at Data Source Configuration Wizard, since we will not using this wizard for now.
4. Create table and columns like below.
5. Add reference “System.Data.SqlServerCe”.
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.
Trip to Cameron Highlands
Filed Under (Blog) by fakhrul on 03-01-2010
Alhamdulillah, rancangan aku nak ke Cameron Highlands dah tertunai jugak. Dah lama aku nak ke sana, last aku pegi tahun 1998, dah lebih 10 tahun dah pon. Dulu pegi ngan kawan-kawan. Kali ni pegi dengan wife. Huhu.. maybe next time, boleh pegi dengan anak pulak. Aku ikut highway PLUS, then exit kat Simpang Pulai. Kalau exit ikut Tapah pon boleh, tapi jalan kat situ tak berapa selesa sangat. Jalan dia sempit sket.
Trip kali ni pegi 3 hari 2 malam. Bertolak 25/12 sampai la 27/12. Kitorang stay kat Hill View Inn, Tanah Rata. Rate bilik kira ok la. During peak season ni, RM160 per room per night. So total spent untuk hotel ni RM 320 untuk 2 malam.
![]()
So, destinasi pertama kitorang ialah, tea plantantion kat Cameron Valley. Location nya kat Tanah Rata. Lebih kurang 2 km dari hotel. Kitorang sampai sana pukul 8 pagi, huhu. We are the first visitor on that day. Kedai pon baru bukak. :).
Healthy Strawberry Farm, Big Red Strawberry Farm, Cactus Point, Pasar Malam Berinchang, dan Green View Garden. Semua ni tempat-tempat menarik kat Cameron Highland yang kitorang sempat pergi.
Apa2 pon, trip kali ni best gila. (Maybe sbb pegi ngan wife kot
). Sampai rumah je, terus pikir untuk next trip. Hehe. Destinasi belum di ketahui lagi.
Managed/Unmanaged Code Interoperability
Filed Under (Blog) by fakhrul on 23-12-2009
I just read the article here regarding to the managed and unmanaged code interoperability. Below is the summary.
Call unmanaged APIs from managed code
This can be done for both flat APIs (eg. kernel32.dll and user32.dll) and COM APIs (eg. Microsoft® Word, Excel).
Expose managed APIs to unmanaged code
Examples of doing this include creating an add-in for a COM-based application like Windows Media® Player or embedding a managed Windows Forms control on an MFC form.
1. Guidelines
Call unmanaged APIs from managed code
Calling Unmanaged Flat APIs
There are two mechanisms for calling into unmanaged flat APIs from managed code: through Platform Invoke (available in all managed languages) or through C++ interop (available in C++).
1. For calling just a few unmanaged methods or for calling simple flat APIs, the suggestion is to use platform invoke.
2. For wrapping complex unmanaged flat APIs, or for wrapping unmanaged flat APIs that are changing while managed code is under development, the suggestion is to use C++ interop.
Calling COM APIs
There are two ways to call COM components from managed code: through COM interop (available in all managed languages) or through C++ interop (available in C++).
1. For calling OLE Automation-compatible COM components, the suggestion is to use COM interop.
2. For calling COM components based on Interface Definition Language (IDL), the suggestion is to use C++ interop.
Exposing Managed APIs to Unmanaged Code
Directly Accessing a Managed API
If an unmanaged client is written in C++, it can be compiled with the Visual Studio .NET C++ compiler as a "mixed mode image." After this is done, the unmanaged client can directly access any managed API. However, some coding rules do apply to accessing managed objects from unmanaged code; check the C++ documentation for more details.
Exposing a Managed API as a COM API
Every public managed class can be exposed to unmanaged clients through COM interop.
Exposing a Managed API as a Flat API
Expose your managed API as a flat API only if absolutely necessary. If you have no choice, be sure to check the C++ documentation and be fully aware of all the limitations.
2. Performance
With every transition from managed code to unmanaged code (and vice versa), there is some performance overhead. The amount of overhead depends on the types of parameters used. The CLR interop layer uses three levels of interop call optimization based on transition type and parameter types: just-in-time (JIT) inlining, compiled assembly stubs, and interpreted marshaling stubs (in order of fastest to slowest type of call).
Approximate overhead for a platform invoke call: 10 machine instructions (on an x86 processor)
Approximate overhead for a COM interop call: 50 machine instructions (on an x86 processor)
1. If you control the interface between managed and unmanaged code, make it "chunky" rather than "chatty," to reduce the total number of transitions made.
Chatty interfaces are interfaces that make a lot of transitions without performing any significant work.
Chunky interfaces are interfaces that make only a few transitions, and the amount of work done on the other side of the boundary is significant.
2. Avoid Unicode/ANSI conversions if possible.
3. For high-performance scenarios, declaring parameters and fields as IntPtr can boost performance, albeit at the expense of ease-of-use and maintainability.
4. Sometimes it is faster to do manual marshaling using methods available on the Marshal class, rather than rely on default interop marshaling. For example, if large arrays of strings must be passed across an interop boundary, but only a few elements will be needed, declaring the array as an IntPtr and accessing only those few elements manually will be much faster.
5. Use InAttribute and OutAttribute wisely to reduce unnecessary marshaling.
6. The interop marshaler uses default rules when deciding if a certain parameter needs to be marshaled in before the call and marshaled out after the call. These rules are based on the level of indirection and the parameter type. Some of these operations might not be necessary depending on the method’s semantics.
7. Use SetLastError=false on platform invoke signatures only if you will call Marshal.GetLastWin32Error afterwards.
8. Setting SetLastError=true on platform invoke signatures requires additional work from the interop layer to preserve the last error code. Use this feature only when you rely on this information and will use it after you make the call.
9. If, and only if, unmanaged calls are exposed in a non-exploitable fashion, use SuppressUnmanagedCodeSecurityAttribute to reduce the number of security checks.
References:
http://msdn.microsoft.com/en-us/library/ms973872.aspx
http://msdn.microsoft.com/en-us/library/aa720203%28VS.71%29.aspx
How to uninstall SQL Server 2005 manually (not from Add or Remove Program)
Filed Under (Blog) by fakhrul on 14-10-2009
Yesterday, I had facing this problem during my development. I need to reinstall my Sql Server but I cannot see Sql Server in my Add or Remove Program. :(. Thanks to google. I found this solution:
Run the command to uninstall the SQL Server components
At a command prompt, run the following command:
"%ProgramFiles%\Microsoft SQL Server\90\Setup Bootstrap\ARPWrapper.exe /Remove"
Reference : http://support.microsoft.com/?kbid=909967
Good reason not to wash your car!
Filed Under (Blog) by fakhrul on 05-10-2009
Targus Laptop Bag
Filed Under (Blog) by fakhrul on 29-09-2009
![]()
I just bought a new laptop bag.
. This is the first laptop bag that I had bought. Before this, I am using a bag that my boss gave to me 3 years ago. And some of the part was broken.
For me, it is necessary to have a comfortable bag. I am travelling a lot lately. Mostly, to Manila. Carrying a heavy notebook and electronic gadgets all over the place is hurting myself. And this is the main reason why I bought this even though my wife said that “It’s expensive”
Last week, I went to Digital Mall, Petaling Jaya and found this bag. It is simple bag with a fewer compartments. There is one big compartment which I can put my mouse, charger, cables, gadgets, and document also. There is also have an audio extension so that I can put the mp3 player inside the bag. But I don’t have mp3 player. :). It’s ok, I will get it soon.
Features:
- Fits laptops with up to 15.4” wide screens.
- A padded laptop compartment to secure and protect your notebook.
- Wet compartment for the storage of wet umbrella or towel.
- Headphone extension cable so you can listen to your music whilst keeping your iPod securely tucked away
- Hidden security pocket at back panel secures and organize valuables.
- Hidden rain cover for convenience.
- Contoured padded backing and ergonomic adjustable shoulder straps to reduce strain and add support.
For the full spec, click here.
A WPF application? Why?
Filed Under (Blog) by fakhrul on 05-08-2009
“Windows Presentation Foundation is an extremely powerful set of tools that lets you create richer applications with minimal effort. I went with WPF over Windows Form applications for the transparency and glow effect I get for free. I also have access to another control that did the layout for me too.” – Coding4Fun
But unlucky for me, my company still using .NET framework 2.0 with Visual Studio 2005 IDE. There is no chance for me to discover the WPF in deep. To whom it may concern, we are now 5 years behind the technology. Visual Studio 2010 its alread in the market. :(. It’s bad for us.. sigh..
.NET Auto Increment Version Number
Filed Under (Blog) by fakhrul on 30-07-2009
I just found a good tools to auto increment the software revision number when you build the project.
Normally the standard revision number for .NET contains 4 parts :
1 - Major Version
0 - Minor Version
0 - Build Number
1 – Revision
So, by default, this tools will auto generate the last 2 portion. The Build Number and the Revision. The Build Number will increase base on the date while the Revision will increase every time you build the project.
You can try and get it from here. If it is useful, and it’s good for you..
Others useful links:
Notes on How To Mentoring a Junior Developer
Filed Under (Blog) by fakhrul on 29-07-2009
- Make mentoring a priority – Give your full effort to them. If they ask, answer it. Don’t let they find out the answer by themselves. Maybe the answer they had found are not really what you want
- Have a road map - Plan and list what the new employee should do.
- Be tolerant of mistakes
- Assign appropriate projects - Don’t give an entry-level programmer a complex project. Maybe can start with an existing project and fixing a bug.
- Give and accept feedback
- Listen to the new employee’s side
- Treat the developer with respect
Resources : http://blogs.techrepublic.com.com/programming-and-development/?p=1493&tag=nl.e055














