Halaman

Sabtu, 23 Oktober 2010

Programs close very frequent for Data Execution Prevention

Data Execution Prevention (DEP) is a security feature that helps prevent damage from viruses and other security threats by monitoring your programs to make sure they use system memory safely.Harmful programs can try to attack Windows by attempting to run (also known as execute) code from system memory locations reserved for Windows and other authorized programs. These types of attacks can harm your programs and files.

DEP can help protect your computer by monitoring your programs to make sure that they use system memory safely. If DEP notices a program on your computer using memory incorrectly, it closes the program and notifies you.

This happened to me very frequent. For example, when using IE, FF and Opera, the web browser suddenly terminate, and closed. The same cases also appear, while working with Adobe, MSOffice, OpenOffice.

I open Task Manager and found strange program "in my opinion", DOIMEK.EXE.
The file reside in User's home directory. I watch another file exist with same size to ALG.EXE, with SHR attributes, and dated 2010-10-21.

I run msconfig, in Startup tab, unchecked Doimek.exe and one other name that I forgot, to not load at start.
After rebooting, still...CPU Usage is too high for long time, specially for doimek.exe


No relevant results while Googling doimek.exe and alg.exe, at time of writing this post, probably I am wrong with those file, but I have remove them from my machine, and CPU Usage is decrease.

Pinging General Failure after uninstalling Norton

My machine has Vista installed and Norton as anti virus and for internet security.
I just remove Norton by using Uninstall in Vista's Control Panel and could not found
any uninstallation program that come with it.
The anti virus has gone, but two Live Update still reside as Service and one service named like Symantec Application ... ( I forgot the complete name). They could not be uninstalled. I leave them as is, than try to work with my local web with results:

- My local web could not be reach.
- Try with three kinds of different software databases to test local connection, no success.
- Try a ping command to domain name, even localhost or 127.0.0.1, come with General Failure reply.
- As administrator try to reset winsock and IPv4:
C:\Windows\System32>netsh winsock reset catalog
C:\Windows\System32>netsh int ipv4 reset reset.log
C:\Windows\System32>netsh int ipv6 reset reset.log
restart the machine, still General Failure.

Then I arrived here and use it to completely remove Norton software.
It works again.

Minggu, 17 Oktober 2010

SQL math

What the result of these SQL Statements:

SELECT 1/2, 2 - (2 * (1/2));

SELECT 1 * 1.52, 1.0 * 1.52, 1.0 * 1.520, 1.00 * 1.520;

Please try with any kind of database software!

Sabtu, 09 Oktober 2010

Using PHP Radius Extension


The FreeRADIUS server software package includes several tools to assist in testing and using the server, some pf them is Radclient and Radtest. To work with applications such as Web inventory Systems, the system has to connect with Radius server using Radius Client. Today I use PHP Radius Extension as Radius client.

PHP Radius client library
This package is PECL extension for Radius (Remote Authentication Dial In User Service). This extension is based on the libradius of FreeBSD. It allows clients to perform authentication and accounting by means of network requests to remote servers.


Auth_RADIUS
This package is a php wrapper around the php radius extension. There are different Classes for the different authentication methods available through RADIUS. If we are using CHAP-MD5 or MS-CHAP authentication, we will also need the Crypt_CHAP package. In addition, if using MS-CHAP authentication, we will need to enable the mhash and mcrypt extension in php.ini. Documentation of the radius extension is available through the PHP manual at http://www.php.net/radius

In previous install link, my sistem has these modules installed
# php -m
[PHP Modules]
Core
date
ereg
gd
libxml
mysql
mysqlnd
pcre
Reflection
session
SPL
standard

I started the installation with the following sequence:

1. Install Auth_Radius a PEAR wrapper classes for the RADIUS PECL.
#/usr/ports/net/pear-Auth_RADIUS
#make
===> Registering installation for pear-1.9.1
===> Returning to build of pear-Auth_RADIUS-1.0.6
===> Configuring for pear-Auth_RADIUS-1.0.6
===> Registering installation for pecl-radius-1.2.5
#make install
----------------------------------------------------------------------
Libraries have been installed in:
/usr/ports/net/pecl-radius/work/radius-1.2.5/modules
****************************************************************************
The following line has been added to your /usr/local/etc/php/extensions.ini
configuration file to automatically load the installed extension:
extension=radius.so
****************************************************************************
===> Returning to build of pear-Auth_RADIUS-1.0.6
===> Generating packing list
===> Generating temporary packing list
===> Checking if net/pear-Auth_RADIUS already installed
===> Installing examples in /usr/local/share/examples/pear/Auth_RADIUS.
install ok: channel://pear.php.net/Auth_RADIUS-1.0.6
===> Registering installation for pear-Auth_RADIUS-1.0.6

# make clean
===> Cleaning for pear-1.9.1 ###PEAR framework for PHP
===> Cleaning for php5-5.3.3_2
===> Cleaning for pecl-radius-1.2.5 ###Radius client library for PHP
===> Cleaning for php5-xml-5.3.3_2
===> Cleaning for pear-Auth_RADIUS-1.0.6 ###PEAR wrapper classes for the RADIUS PECL


2. Install additional package
#/usr/ports/security/pear-Crypt_CHAP
extension=mcrypt.so
extension=hash.so

3. List modules installed
# php -m
[PHP Modules]
Core
date
ereg
gd
hash
libxml
mcrypt
mhash
mysql
mysqlnd
pcre
radius
Reflection
session
SPL
standard
xml

# pear list
Installed packages, channel pear.php.net:
=========================================
Package Version State
Archive_Tar 1.3.7 stable
Auth_RADIUS 1.0.6 stable
Console_Getopt 1.2.3 stable
Crypt_CHAP 1.0.2 stable ### here version 1.0.2
PEAR 1.9.1 stable
Structures_Graph 1.0.3 stable


4.I have to upgrade Crypt_CHAP (replace mhash function to hash function, because I'm on php5.3)
# pear upgrade
downloading Crypt_CHAP-1.5.0.tar ...
Starting to download Crypt_CHAP-1.5.0.tar (Unknown size)
........done: 22,528 bytes
upgrade ok: channel://pear.php.net/Crypt_CHAP-1.5.0
Installed packages, channel pear.php.net:
=========================================
Package Version State
Archive_Tar 1.3.7 stable
Auth_RADIUS 1.0.6 stable
Console_Getopt 1.2.3 stable
Crypt_CHAP 1.5.0 stable
PEAR 1.9.1 stable
Structures_Graph 1.0.3 stable

5. Restart Apache service
#apachectl graceful

6. Start Radius in debug mode



7. Test authentication



8. Use sample number 2 from here and modify arguments as needed, and test it. It works.




Jumat, 08 Oktober 2010

Installation of Mondes' LAB1

Steps to install Mondes' LAB1. This was done remotely via telnet, from 11.50pm to 02.30am.

1. Install Apache web server with prefork MPM (apache-2.0.63_16)
#cd /usr/ports/www/apache20 (released 2008-01-19)
#make install clean
(current Apache is v2.2.16, released 2010-07-25)


2. Install current version of PHP5 (php5-5.3.3_2, released 2010-07-22)
#cd /usr/ports/lang/php5
#make install clean
***************************************************************
Make sure index.php is part of your DirectoryIndex.
You should add the following to your Apache configuration file:
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
***************************************************************
This port has installed the following files which may act as network servers and may therefore pose a remote security risk to the system.
/usr/local/libexec/apache2/libphp5.so
/usr/local/bin/php
/usr/local/bin/php-cgi

AddType application/x-httpd-php .php <<.html>>
AddType application/x-httpd-php-source .phps


3. Install mysql shared extension for php (php5-mysql-5.3.3_2)
#cd /usr/ports/databases/php5-mysql
#make install clean
***************************************************************
The following line has been added to your /usr/local/etc/php/extensions.ini configuration file to automatically load the installed extension:
extension=mysql.so
***************************************************************


4. Install session shared extension for php (php5-session-5.3.3_2)
#cd /usr/ports/www/php5-session
#make install clean
***************************************************************
The following line has been added to your /usr/local/etc/php/extensions.ini
configuration file to automatically load the installed extension:
extension=session.so
***************************************************************


5. Install gd shared extension for php (php5-session-5.3.3_2)
#cd /usr/ports/graphics/php5-gd
#make install clean
****************************************************************************
The following line has been added to your /usr/local/etc/php/extensions.ini
configuration file to automatically load the installed extension:
extension=gd.so
****************************************************************************

6. Install text-based web browser
#cd /usr/local/www/lynx
#make install clean
This port has installed the following files which may act as network
servers and may therefore pose a remote security risk to the system.
/usr/local/bin/lynx


7. Make FreeBSD reread the files in the path so it knows what's there
#rehash


8. Adding PHP5 module to Apache
#cd /usr/local/etc/apache2/
===>modify httpd.conf


9. Create test page
# echo ""  >> /usr/local/www/data/tester.php


10.Test the installation
#apachectl start
#lynx localhost/tester.php

ready for web management (RADIUS and Monitoring).

Minggu, 26 September 2010

Linq to NHibernate

My previous codes show the use of NHibernate and Fluent NHibernate as OR/M with .NET framework. Next, I would refer to Fluent NHibernate and use Linq.

1. Download NHibernate.Linq-2.1.2-GA-Bin to get NHibernate.Linq.dll.
2. Add reference to NHibernate.Linq.dll in this file that we work with, and in the beginning add using NHibernate.Linq;
3. At line 43, add this:

var x = (from p in session.Linq<Personal>() where p.Member== "Y" select p).Take(5);
Console.WriteLine("Output #1:");
foreach (var a in x)
Console.WriteLine("id= {0}, ket= {1}", a.Id, a.Sex);

var r = from p in session.Linq<Personal>()
group p by p.Sex into g
select new { sex = g.Key, count = g.Count() };
Console.WriteLine("Output #2:");
foreach (var a in r)
Console.WriteLine("Sex = {0}, Count= {1}", a.sex, a.count);

4. In this sample, I add a new table and make mapping to database.

public class Personal
{
public virtual string Id { get; private set; }
public virtual string Member { get; set; }
public virtual string Sex { get; set; }
}

public class PersonalMap : ClassMap<Personal>
{
public PersonalMap()
{
Table("employees");
Id(x => x.Id).Column("pk");
Map(x => x.Member, "member");
Map(x => x.Sex, "sex");
}
}

Below the output, and it's time for me to sleep....good morning..

LINQ to MySQL with DbLinq

Language-Integrated Query (LINQ), allows .NET programs to connect to databases. It is an Object-Relational mapping tool, with some similarities to Hibernate or LLBLGen. LINQ is type-safe, queries get compiled into MSIL on the fly, and your C# WHERE clauses are translated into SQL and sent to SQL server for execution. In short, it makes design of data access layers safer and faster.

Today I have work with LINQ to MySQL, and arrived at DbLinq.
DbLinq is the LINQ provider that allows to use common databases with an API close to Linq to SQL. DbLinq is a reimplementation of System.Data.Linq.dll for use with SQL servers. It supports MySQL, Oracle, PostgreSQL, SQLite, Ingres, Firebird, and SQL Server.

This code use DbLinq 0.20.1 (released 2010-04-16).
1. Download and extract DbLinq to c:\DbLinq-0.20.1
2. Copy run_myMetal.bat to runme.bat, and modify it to
DbMetal.exe /conn:"server=localhost;user id=myname;password=a; port=3306; database=mydb" /provider=MySql /code:FerDBLinq.cs /language:C#
4. Execute runme.bat so we get FerDBLinq.cs. Copy the file into your project folder then use Add Existing items from Solution Explorer.

5. Add reference to DbLinq.dll, DbLinq.MySql.dll
6. Open FerDBLing.cs file, add these in the beginning:

using DbLinq.MySql;
using DbLinq.Data.Linq;
using System.Data.Linq.Mapping;
using MySql.Data.MySqlClient;

Here code snippets that follows:

public partial class myDBS: MySqlDataContext
{
#region Extensibility Method Declarations
partial void OnCreated();
#endregion
public myDBS(string conStr) : base(new MySqlConnection(conStr)) { }
public myDBS(MySqlConnection conn): base(conn){}

public DbLinq.Data.Linq.Table<BUkUBeSaR> BUkUBeSaR
{
get { return this.GetTable<BUkUBeSaR>();}
}

5. Creata a function for testing purpose.

private void linqing()
{
using (MySqlConnection conn = new MySqlConnection(GconString))
{
try
{
conn.Open();
myDBS db = new myDBS(conn);

var q = (from p in db.PerSoNaL where p.member=="Y";
Console.WriteLine("Output #1:");
foreach (var a in q)
Console.WriteLine("id= {0}, ket= {1}", a.PK, a.sex);

var r = from p in db.PerSoNaL group p by p.sex into g
select new { sex = g.Key, Count = g.Count() };
Console.WriteLine("Output #2:");
ObjectDumper.Write(r);

var t = db.PerSoNaL.GroupBy(p => p.sex);
var u = t.Select(g => new {g.Key, Count = g.Count()});
Console.WriteLine("Output #3:");
foreach (var a in u)
Console.WriteLine("sex={0}, count={1}", a.Key, a.Count);

int cnt = (from p in db.PerSoNaL group p by p.sex).Count();
Console.WriteLine("Output #4:\nCount={0}", cnt);

var s=db.PerSoNaL.GroupBy(c=> c.sex).ToList().AsQueryable();
Console.WriteLine("Output #5:");
foreach (var a in s)
Console.WriteLine("sex "+a.Key+ ", count=" +a.Count());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

The output:
Dblinq works for me, but I could not resolve about the count(), for Male(L) and Female(P) always return 1. I've read issue 157 and 158, but still locked. Do you have any idea?

Jumat, 24 September 2010

Fluent NHibernate with MySQL

NHibernate is an Object Relational Mapping framework, which (as ORM states) maps between relational data and objects. It defines its mappings in an XML format called HBM, each class has a corresponding HBM XML file that maps it to a particular structure in the database.

Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents (.hbm.xml files), Fluent NHibernate lets you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code. Fluent, XML-less, compile safe, automated, convention-based mappings for NHibernate.

Fluent NHibernate is external to the NHibernate Core, but is fully compatible with NHibernate version 2.1, and is experimentally compatible with NHibernate trunk.

Why replace HBM.XML? While the separation of code and XML is nice, it can lead to several undesirable situations.

  • Due to XML not being evaluated by the compiler, you can rename properties in your classes that aren't updated in your mappings.
  • XML is verbose; NHibernate has gradually reduced the mandatory XML elements, but you still can't escape the verbosity of XML.
  • Repetitive mappings - NHibernate HBM mappings can become quite verbose if you find yourself specifying the same rules over again. For example if you need to ensure all string properties mustn't be nullable and should have a length of 1000, and all ints must have a default value of -1.

To counter these issues Fluent NHibernate does by moving mappings into actual code, so they're compiled along with the rest of your application; rename refactorings will alter your mappings just like they should, and the compiler will fail on any typos. As for the repetition, Fluent NHibernate has a conventional configuration system, where you can specify patterns for overriding naming conventions and many other things; you set how things should be named once, then Fluent NHibernate does the rest.

My post before, shows an example of using NHibernate. Below we modify the previous code to work with Fluent NHibernate.

  1. Download fluentnhibernate-1.1.zip then extract.
  2. Create a console application using Visual Studio and named as FluentNHibernateSample.
  3. Add reference to FluentNHibernate.dll, NHibernate.ByteCode.Castle.dll, NHibernate.dll. In this sample we work with MySQL, so add MySql.Data.dll and remember to set Copy Local property to true.
  4. Here the modified version of my previous code:

using System;
using System.Collections.Generic;
using System.Collections;
using MySql.Data.MySqlClient;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using System.Linq;
using FluentNHibernate.Mapping;

namespace FluentNHibernateSample
{
class Program
{
static void Main(string[] args)
{
FluentConfiguration config = Fluently.Configure()
.Database(MySQLConfiguration.Standard
.ConnectionString(c => c
.Server("localhost")
.Database("mydb")
.Username("myname")
.Password("mypass")));
ISessionFactory factory = config.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<Coba>())
.BuildSessionFactory();

var session = factory.OpenSession();
System.Collections.IList myRows = session.CreateCriteria(typeof(Coba)).List();
foreach (Coba item in myRows)
Console.WriteLine("Id:{0} - Ket:{1}", item.Id, item.Ket);

IQuery query = session.CreateQuery("from Coba order by ket desc");
IList<Coba> dta = query.List<Coba>();
foreach (Coba item in dta)
Console.WriteLine("Id:{0} - Ket:{1}", item.Id, item.Ket);

query = session.CreateQuery("FROM Coba WHERE kode=:kode");
query.SetString("kode", "19");
foreach (Coba item in query.List<Coba>())
Console.WriteLine("\nResult:\nID:{0} with Ket:{1}", item.Id, item.Ket);
session.close();
Console.ReadKey();
}
}
public class Coba
{
public virtual string Id{ get; private set; }
public virtual string Ket {get; set;}
}

public class CobaMap : ClassMap<Coba>
{
public CobaMap()
{
Table("masjob");
Id(x => x.Id).Column("kode");
Map(x => x.Ket, "ket");
}
}
}

  1. Run. We get the same result with my previous code.


The code does not use xml configuration files at all!

Excel Constants Enumeration

When we automate an application such as a Microsoft Office application, the calls to the properties and methods of the Office application's objects must be connected in some way to those objects. The process of connecting property and method calls to the objects that implement those properties and methods is commonly called binding.

Early Binding sets the connections between Excel and the other application early during design time, while Late Binding the connection isn't made until run time.

Early Binding has several advantages, because the Object Model of the other application is known during development, we can make use of Intellisense and the Object Browser to help write code. Late Binding does not allow us to use debugging tools, Intellisense, or Object Browser. The advantage to Late Binding is we do not have to worry about the wrong version of an object library being installed on the user's computer.

While coding for Office automation, I usually record a macro then refer to the commands into mine. We might use some constants, and for Late Binding we have to know the constants value of a constant name.

To get Excel constants enumeration:
1. Open Excel
2. Open Visual Basic Editor, then type the constants name e.g:


Sub main()
MsgBox (xlInsideHorizontal)
MsgBox (xlNone)
End Sub

Another way:
1. Open Excel
2. Open Visual Basic Editor, then press F2
3. Type the constants in the search box e.g: xlNone
4. Click Search button, we get -4142

Each Office program that supports VBA has a set of built-in constants, with numeric values that represent some state or property. These constants are usually prefixed with the initials of the source program. i.e. 'xl' for Excel, 'ol' for Outlook, 'wd' for Word.

Kamis, 23 September 2010

NHibernate MySQL

  1. Download NHibernate.
  2. Create a new C# console application "NHibernateTest", and create a folder "sharelib" that contains library from first step.
  3. Make reference to NHibernate.dll, MySql.Data.dll, NHibernate.ByteCode.Castle.dll
  4. Type this into Program.cs.

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using MySql.Data.MySqlClient;
using NHibernate;
using NHibernate.Cfg;
namespace NHibernateTest
{
class Program
{
static void Main(string[] args)
{
Configuration config = new Configuration();
config.AddAssembly("NHibernateTest");
config.Configure();

ISessionFactory factory = config.BuildSessionFactory();
try
{
ISession session = factory.OpenSession();
IList myRows = session.CreateCriteria(typeof(NHibernateTest.Coba)).List();
foreach (NHibernateTest.Coba item in myRows)
Console.WriteLine("Id:{0} - Ket:{1}", item.Id,item.Ket);

IQuery query = session.CreateQuery("from Coba order by ket desc");
IList<coba> dta = query.List<coba>();
foreach (NHibernateTest.Coba item in dta)
Console.WriteLine("Id:{0} - Ket:{1}",item.Id,item.Ket);

query = session.CreateQuery("FROM Coba WHERE kode=:kode");
query.SetString("kode", "19");
foreach (NHibernateTest.Coba item in query.List<coba>())
Console.WriteLine("\nResult:\nID:{0} with Ket:{1}",item.Id,item.Ket);
session.Close();
}
catch (Exception ex)
{
Console.Out.WriteLine("Error: " + ex.Message.ToString());
}
Console.In.Read();
}
}

public class Coba()
{
public Coba() {}
public virtual string Id { get; private set; }
public virtual string Ket { get; set; }
}
}
  1. Create an XML Mapping File by right-click on the project, add a new item, an named the XML as "NHibernateTest.hbm.xml". Right-click on the file, select "Properties" and change the "Build Action" to "Embedded Resource". Here the contents.

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="NHibernateTest.Coba, NHibernateTest" table="masjob" lazy="false">
<id name="Id" column="kode" type="string">
<generator class="native"></generator>
</id>
<property name="Ket" column="ket" />
</class>
</hibernate-mapping>
  1. Create Configuration File so NHibernate knows the database by right-click on the project, select "New Item...", select "Application configuration File", then type the following to "App.config".

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver
</property>
<property name="connection.connection_string">
Server=localhost;Database=myDB;User ID=myname;Password=mypass;
</property>
<property name="dialect">NHibernate.Dialect.MySQLDialect</property>
<property name="show_sql">false</property>
<property name="proxyfactory.factory_class">
NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
</session-factory>
</hibernate-configuration>
</configuration>
  1. Assume we already have masjob table on myDB with this structure:

CREATE TABLE masjob (
`kode` int(11) NOT NULL AUTO_INCREMENT,
`ket` varchar(20) NOT NULL,
PRIMARY KEY (`kode`));


We sould have this output. Have a try!

Could not create the driver from NHibernate.Driver.MySqlDataDriver

Here a piece of #C code, I use to create session for NHibernate:

1. Configuration config = new Configuration();
2. config.Configure();
3. ISessionFactory factory = config.BuildSessionFactory();

4.......

Line 3 would raise error something like "Could not create the driver from NHibernate.Driver.MySqlDataDriver"

I pointed to Mysql.Data.dll file in References folder on the Solution Exploreror, than change Copy Global property from false to true. The code could work to open a session.

Selasa, 21 September 2010

Vista Batch File and Command Prompt

I have a problem to edit .bat file on Vista, but can run by double-clicking on it.
An error message appears when trying to edit the file through Windows Explorer.

I downloaded .zip file from here, then unzipped. Right-click on batfix_vista.REG file then select Merge will fix batch file association.
Right-click to edit with Notepad and double-click to run, work as expected. Here a list of file associations for Vista.

One more...sometimes, we want to display a command prompt in accordance with the location of the folder from Windows Explorer. For this purpose press the SHIFT key + right-click then select Open Command Window Here.

Minggu, 12 September 2010

A generic error occurred in GDI+ and The process cannot access the file...

I have a database that stores data on a server and use directory as a placeholder for .jpg files. In this application, I store images in folders instead of using BLOB data type, so there is a correspondence between each record with image files, and also there are references to several fields with their corresponding image file.

When viewing the data in the DataGridView, images should be shown in Picture Box, using this function.

private void NextPrevRow()
{
DataRowView drv = (DataRowView)bindSrc0.Current;
if (drv == null) return;
string fname = myGlobVar.UNC + "\\f"+drv["pk"].ToString().Trim()+".jpg";
if (System.IO.File.Exists(fname))
{
try
{
fotobox.Image = System.Drawing.Image.FromFile(fname);
}
catch { }
}
else
fotobox.Image = null;
}

If a user wants to link an image with a record, he chose the image file first and then clicking the save button.
The following function will save the bitmap image that is displayed in the Picture Box as an image file in the directory of the server.

private void SaveImageToFile()
{
DataRowView drv = (DataRowView)bindSrc0.Current;
if (fotobox.Image != null)
{
string fname = myGlobVar.UNC + "\\f" + drv["pk"].ToString().Trim() + ".jpg";
try
{
if (File.Exists(fname))
File.Delete(fname);
fotobox.Image.Save(fname, ImageFormat.Jpeg);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

Make changing of the image, will raise an error The process cannot access the file '\\10.11.12.13\\f128.jpg' because it is being used by another process.
It occurs when use fotobox.Image = System.Drawing.Image.FromFile(fname); line number 10 of NextPrevRow()function, and these commands in SaveImageToFile() function:

if (File.Exists(fname))
File.Delete(fname);
fotobox.Image.Save(fname, ImageFormat.Jpeg);

If I remark commands to delete files, and leave Save command only in SaveImageToFile() function, an error thrown: A generic error occurred in GDI+.

I modify the commands, error messages about file locking does not exist anymore.

private void NextPrevRow()
{
DataRowView drv = (DataRowView)bindSrc0.Current;
if (drv == null) return;
string fname = myGlobVar.UNC + "\\f"+drv["pk"].ToString().Trim()+".jpg";
if (System.IO.File.Exists(fname))
{
try
{
FileStream fs = File.OpenRead(fname);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();

MemoryStream ms = new MemoryStream(data);
Bitmap bmp = new Bitmap(ms);
fotobox.Image = bmp;
ms.Close();
}
catch { }
}
else
fotobox.Image = null;
}


private void SaveImageToFile()
{
DataRowView drv = (DataRowView)bindSrc0.Current;
if (fotobox.Image != null)
{
string fname = myGlobVar.UNC + "\\f" + drv["pk"].ToString().Trim() + ".jpg";
try
{
// if (File.Exists(fname))
// File.Delete(fname);
fotobox.Image.Save(fname, ImageFormat.Jpeg);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

Selasa, 07 September 2010

Could not load file or assembly 'System.Core, Version=3.5.0.0..'

After installing the application on the client, I try to open forms and they are working correctly. But for some other forms, an error message appears

Could not load file or assembly 'System.Core, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089' or one of its dependencies. " The system cannot find the file specified.

I click the details button to find the cause of the error, then check the appropriate source code line number as reported. Although the code works correctly on the development machine, I'm trying to find out why the problem appears on the line, I then realized that I am using LINQ and version of the .NET Framework on the client computer suspected as the cause of the problem.

I finally arrived at here and here. After upgrading to. NET Framework 3.5, the application run correctly.

Just picture it, .NET Framework 3.5 features include the following:

  • Deep integration of Language Integrated Query (LINQ) and data awareness. This new feature will let us write code written in LINQ-enabled languages to filter, enumerate, and create projections of several types of SQL data, collections, XML, and DataSets by using the same syntax.
  • ASP.NET AJAX lets you create more efficient, more interactive, and highly-personalized Web experiences that work across all the most popular browsers.
  • New Web protocol support for building WCF services including AJAX, JSON, REST, POX, RSS, ATOM, and several new WS-* standards.
  • Full tooling support in Visual Studio 2008 for feature sets in Windows Workflow Foundation (WF), Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF) and Windows CardSpace, including the new workflow-enabled services technology.
  • New classes in .NET Framework 3.5 base class library (BCL) that address many common customer requests.

System Requirements:

  • Supported Operating Systems: Windows Server 2003; Windows Server 2008; Windows Vista; Windows XP
  • Processor: 400 MHz Pentium processor or equivalent (Minimum); 1GHz Pentium processor or equivalent (Recommended)
  • RAM:96 MB (Minimum); 256 MB (Recommended)
  • Hard Disk: Up to 500 MB of available space may be required

Specify .NET Framework Target for a Project

We specify a specific .NET Framework target while creating a new project or change it later. For a new project, i.e after a New Project dialog box appear (by clicking Project on the File menu, New Project), we select the .NET Framework version we want from a drop down list.

To change a .NET Framework version:
1. Locate the Project Designer, by right click on a project in the Solution Explorer, then click Properties.

2a. For C#, on the Application tab, locate Target Framework and select .NET Framework version.

2b. For VB, click Compile tab on the Project Designer then click Advanced Compile Options.. from drop down list to choose .NET Framework version.

Selasa, 10 Agustus 2010

Create PDF file using C# and iTextSharp

iText is a library that allows you to generate PDF files on the fly, and it is an ideal library for developers looking to enhance web- and other applications with dynamic PDF document generation and/or manipulation. iText is not an end-user tool. Typically you won't use it on your Desktop as you would use Acrobat or any other PDF application. Rather, you'll build iText into your own applications so that you can automate the PDF creation and manipulation process.

The iText classes are very useful for people who need to generate read-only, platform independent documents containing text, lists, tables and images; or who want to perform specific manipulations on existing PDF documents.

Say we already have a C# project created with Microsoft Visual Studio, and want to generate a PDF file using iTextSharp. Below is my step:

1. Download itextsharp-5.0.2-dll.zip (1.2MB) from http://sourceforge.net/projects/itextsharp/files/
2. Extract the zip file to get itextsharp.dll file.
3. On Visual Studio, Add Reference to that file.
4. Open your source code and put this
using iTextSharp.text;
using iTextSharp.text.pdf;

5. Create a function like this:
private void generatePDF()
{
Document doc = new Document();
string dirPath = AppDomain.CurrentDomain.BaseDirectory + "pdf";
string pdfFile = dirPath + "\\" + "my.pdf";

PdfWriter writer = PdfWriter.GetInstance(doc, new System.IO.FileStream(pdfFile, System.IO.FileMode.Create));
writer.SetEncryption(PdfWriter.STRENGTH128BITS, "readpassw", "editpassw", PdfWriter.AllowCopy PdfWriter.AllowPrinting);

doc.Open();

doc.AddTitle("iTextSharp");
doc.AddSubject("Create Paragraph");
doc.AddCreator("iTextSharp");
doc.AddAuthor("We");
doc.AddTitle("My Title");

string tit = "This document using 128 bits encryption";
doc.Add(new Paragraph(tit, FontFactory.GetFont(FontFactory.HELVETICA, 20, 5,BaseColor.BLUE)));

Paragraph p = new Paragraph(new Chunk("iText is a library that allows you to generate PDF files on the fly", FontFactory.GetFont(FontFactory.HELVETICA, 10)));
p.Add("The most recent version is iText 5.0.3.");
p.Add("iText is an ideal library for developers looking to enhance web-");

p.Add(new Chunk("and other applications with dynamic PDF document generation and/or manipulation."));
p.Add(new Phrase("iText is not an end-user tool."));
p.Add(new Phrase("You'll build iText into your own applications to automate the PDF creation and manipulation process.", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 18)));
doc.Add(p);

doc.NewPage();
p = new Paragraph(new Phrase("This is my second paragraph.", FontFactory.GetFont(FontFactory.TIMES_ITALIC, 11)));
p.Add("In short: the iText classes are very useful for people who need.");
doc.Add(p);
doc.Close();
}

6. Call that function and chek my.pdf file using your PDF reader.

Sabtu, 07 Agustus 2010

Boot on Ring

Seminggu yang lalu, saya berada sekitar 1000 km dari server sebut saja "DearServer". Perjalanan yang mengasyikkan bersama Hari, Suhendra, Teguh. Canda tawa, guyonan dan ide "andai-andai" pun mewarnai perjalanan kami saat melihat indahnya pemandangan, orang, mesin, makanan, bahkan sensor di bandara...bak komentator..dengan rileks dan tanpa beban menyampaikan pandangannya...

Kami beranjak meninggalkan DearServer pukul 05.40 dan tiba di remote area sekitar jam 16. Jam 20 memulai setup komputer, camera, cabling, konfigurasi LAN, tes koneksi internal dan ke internet via RG. Semua lancar dan response aplikasinya baik. Oh ya di DearServer ada rekan Salihin, yang setia menssuport kami, dan di server lokal ada rekan Iwan yang mendampingi. Dari testing aplikasi App2 kami masih menemui kendala. Jam telah menunjukkan hampir pukul 23 dan kami pun istirahat.

Esoknya kami mulai pelatihan internal dan laptop Vaio18 pun digunakan hingga jam 16. Jam 21, PR untuk App2 dilanjutkan. Untuk misi kali ini, ada 2 Aplikasi di DearServer yang harus dijalankan. App1 dan App2.
App1 terbuka untuk diakses via internet, sedangkan App2 khusus untuk intranet. App1 bisa diakses, namun tidak untuk App2. Koneksi VPN digunakan namun gagal koneksi ke App2. Routing dinamik dibuat dan App2 bisa diakses. Naah, sekarang saatnya mengganti dengan routing statis.
Saat membuat routing statis saya membuat IP yang sama (konflik) dalam server island, SSH pun terputus. Jam telah menunjukkan pukul 23, tak mungkin menelpon Salihin untuk datang mereset DearServer. Ide pun muncul andai bisa menelpon petugas untuk melakukan warm/cold boot server, andai ada tambahan NIC, atau andai ring telepon yang membuat Boot On Ring...next time kali yaaa.. Hmmmm...routing statis kan bisa dikerjakan besok pagi...kami melakukan finishing dan kembali pukul 01.

Kicau burung di pagi hari pun terdengar, suasana yang langka saat berada di kotanya DearServer, saat jalan pagi dan melihat pohon dan gunung yang masih tertutup embun...amazing deh...sementara Teguh menelpon Salihin untuk merestart DearServer. Jam 09, routing diberesin, dan semua OK..pada saat yang tepat... Sesuai jadwal, pelatihan eksternal pun dibuka oleh pak Edy dan kami melanjutkan dengan materi dan praktek pelatihan. Hal yang menyenangkan diperoleh dengan tidak adanya gangguan koneksi maupun hambatan pengoperasian aplikasi. Mission completed...dan perjalanan panjang menanti untuk eksekusi real-world.

Rabu, 21 Juli 2010

Outsourcing Inovasi

Artikel Michael J. Stanko, Jonathan D. Bohlmann dan Roger J. Calantone yang ditulis pada The Wall Street Journal November 2009, berjudul “Outsourcing Innovation,” memuat hasil survey mereka terhadap 359 perusahaan untuk mengetahui fator yang mempengaruhi innovative performance. Innovative performance diartikan sebagai the number of patents produced and the number of subsequent patents built on these.

Perusahaan yang berhasil dalam inovasi - innovative performance- menerapkan outsourcing dalam 4 situasi ini:

  1. Saat perusahaan butuh penambahan pengetahuan baru untuk berinovasi, seperti bagaimana bekerja dengan senyawa kimia yang tidak umum untuk membuat lini produksi farmasi yang berbeda.
  2. Pada tahap awal proyek, saat terdapat banyak rintangan teknis yang harus diatasi dan hasilnya jauh dari kepastian.
  3. Saat kekayaan intelektual tidak terlindungi baik di suatu industri. Dalam kasus ini, sejak berbagai ide baru menyebar di banyak perusahaan, maka sulit untuk membedakan produk dengan inovasinya sehingga bisnis menerapkan outsourcing untuk membatasi pengeluaran (spending).
  4. Ketika perusahaan telah berpengalaman dalam berbagai outsourcing. Dalam memilih antara mengerjakan sendiri dan menyerahkan kepada pihak eksternal, perusahaan yang sudah sering menerapkan outsourcing akan menyerahkan pekerjaan kepada pihak eksternal-3 kali lebih sering. Biaya dan manfaat outsourcing lebih pasti dan dapat diatur situasi untuk mencapai hasil yang efektif.

Terlalu banyak menyerahkan pekerjaan kepada pihak eksternal akan berdampak naiknya biaya total jika dibandingkan terlalu banyak melakukannya secara internal. Ketidakmampuan mengontrol pengeluaran kepada vendor, biaya akibat perubahan kontrak, tambahan biaya untuk koordinasi antara upaya internal dan upaya eksternal, atau usaha pertumbuhan secara cepat melalui outsourcing pengembangan produk baru tanpa memperhatikan biaya merupakan faktor penyebab bengkaknya biaya total.

Dalam artikel tersebut, diidentifikasi masalah umum yaitu terlambatnya beralih ke outsourcing dalam pengembangan produk, saat para kontraktor harus belajar lebih banyak tentang pekerjaan yang telah dikembangkan secara internal.

Outsourcing dapat membantu perusahaan dalam memilih berbagai opsi dan mengurangi waktu ke pasar. Sebagai contoh produsen mobil, yang menghadapi berbagai ketidakpastian tentang teknologi bahan bakar alternatif. Dengan outsourcing, mereka dapat melihat beberapa teknologi-jauh melampaui apa yang mungkin mereka mampu lakukan secara internal-dan dapat pergi ke pasar dengan cepat setelah keputusan dibuat.

Dampak outsourcing inovasi terhadap kinerja:

  1. Meskipun tidak selalu lebih murah, outsourcing inovasi sering menghasilkan pengembalian yang lebih tinggi atas investasi dari sumber daya yang dialokasikan.
  2. Perlu balancing jumlah outsourcing. Terlalu banyak outsourcing akan menaikkan biaya jika dibandingkan terlalu banyak pengembangan internal, sedangkan terlalu sedikit outsourcing dapat berakibat kinerja rata-rata atau menurun.
  3. Ada risiko produk menjadi generik/umum, karena dikerjakan pihak eksternal dan mungkin bisa menjadi produk massa.
  4. Ada masalah jika para outsourcer/kontraktor disertakan terlambat dalam pengembangan produk, karena mereka harus melalui kurva pembelajaran yang memakan waktu lama.
  5. Outsourcing memberikan opsi bagi perusahaan untuk masuk ke pasar dengan timing yang baik.

Tidak berlebihan jika diungkapkan dengan outsourcing today for the bright future. O ia, saat menulis saya teringat pada Robert Wolcott penulis buku "Grow From Within", yang mengatakan "Companies don't generally lack good ideas. Rather, they don't have the right approaches to refine, develop, and bring them to market", tampaknya disini barulah empowering today for the bright future. Kombinasinya tentu patut dipilih.

Wisdom quotes: Excellence

"Excellence is a better teacher than mediocrity. The lessons of the ordinary are everywhere. Truly profound and original insights are to be found only in studying the exemplary. " - Warren G Bennis

“It is not enough to do your best, you must know what to do and then do your best. Does experience help? No! Not if we are doing the wrong things".- Deming. 

Good luck in your efforts to make a difference.

Kamis, 01 Juli 2010

Jangan Tunda Besok

Seorang pemuda bernama Luniaz sedang memancing di sungai.
Ia menarik pancingnya, melepas, menariknya lagi... mengikuti gerakan ikan..
(hmmm ia begitu menikmatinya).

Dari arah timur, dua orang berjalan sang PakDe Pitok dan keponakannya Nisura.
Keduanya menghampiri Luniaz dan obrolan pun berlangsung.

PakDe Pitok: Lun, apa kamu ngga kerja?
Luniaz: saya ....
PakDe Pitok: (memotong pembicaraan), coba lihat tuh anak pakDe mu si Nisura dia kan sebaya kamu, dia bekerja dengan semangat

Nisura: Lun, bulan depan saya panen loh, jerih payahku akan kunikmati.
PakDe Pitok: sayang-kan kamu sia-siakan waktu mu. Mari kita berhitung, berapa jam kamu memancing?
Luniaz: sekitar 5 jam-an
PakDe Pitok: Ok...taruhlah 1/3 dari waktu mu sehari untuk tidur, dan 5 jam dari 2/3 waktumu untuk mancing..
Berapa jam waktumu ...

Luniaz: (langsung menyambar) 13 jam totalnya PakDe, sisanya 11 jam.
Nisura: Lun, bulan depan setelah panen..saya mau santai...woww bakalan asik bok
PakDe Pitok: dengar tuh Lun, nanti kalo kamu sudah tua, kamu bisa menikmati hari-hari mu
Luniaz: emangnya gimana contohnya PakDe?

PakDe Pitok: ya...kamu bisa nonton F1, Piala Dunia, bisa jalan kemana-mana, atau bisa mancing di The Rivers of Montana atau Kenai River di Alaska, and spend all your vacation time lying on the deck chair by the pool.

Luniaz: Why to go so much trouble? Cant you see what am i doing?...fishing...yeah I know, Never put till tomorrow , what you can do today.

PakDe Pitok dan Nisura: bertatapan !?!?

Rabu, 30 Juni 2010

Waiting for PostgreSQL 9 stable version

I just read PostgreSQL 9.0 Beta 2 and it's feature on this. Many new feature there, and drive me to use it in future. Things that I am interested in:

Backend section:
1. Column level permissions: allows specification of granular column-level permissions in addition to table level grants
2. GRANT/REVOKE ON ALL TABLES/SEQUENCES/FUNCTIONS: simplifies permission management by allowing mass changes of GRANTS

Functions and triggers section:
1. Column level triggers: adds support for SQL standard column level trigger support, by allowing triggers to only fire if specific columns are mentioned in the UPDATEs SET list
2. WHEN clause for CREATE TRIGGER: adds support for a boolean expression to be checked if a trigger should be fired or not
3. RETURNS TABLE: SQL standard RETURNS TABLE clause for CREATE FUNCTION.

Cryptographic on FreeBSD

I have two Postgresql installed one on Windows (at home) and FreeBSD (at some place out there). I use pgcrypto for encrypting sensitive data. On Windows I have installed the library by executing C:\sistemku\PostgreSQL\9.0\share\contrib\pgcrypto.sql file.

Now it's time for me to send my work to remote server.
I am making a backup secret.db by using pg_dump, then transfer the backup file onto remote server using FTP command. With PuTTY via modem connection, I restored the database. Make some test of web site contents, they looks okay except for crytographic functions. Yeah...the FreeBSD server has no pgcrypto installed.

#find / -name pgcrypto.sql (the file does not exist).


1st attempt: Execute pgcrypto.sql, as you might suspect.., it failed. I have FTPed the file before.
2nd attempt: Type this command using psql:

CREATE OR REPLACE FUNCTION digest(text, text)
RETURNS bytea AS '$libdir/pgcrypto', 'pg_digest'
LANGUAGE C IMMUTABLE STRICT;


Again an error message raised "libdir not found".

3rd attempt: Use port to install pgcrypto with the following steps:
1. Install pgcrypto module
#cd /usr/ports/database/postgresql-contrib
#make config
#make install clean


I could found /usr/local/lib/postgresql/pgcrypto.so and /usr/local/share/postgresql/contrib/pgcrypto.sql.


2. To access library functions, I load stored procedures onto my secret database.
# psql -U binsar -d secredb -f /usr/local/share/postgresql/contrib/pgcrypto.sql


3. Check if cyptographic function loaded.

secretdb=# \df digest
List of functions
Schema Name Type Argument
-------+-------+-------+------------
public digest bytea bytea, text
public digest bytea text, text



4. It works, and get my coffee.

Jumat, 28 Mei 2010

Indikator

Indikator adalah acuan untuk mengetahui kenormalan dalam suatu sistem. Dengan indikator kita dapat mengetahui dimana kita berada, kemana kita bergerak, seberapa jauh pencapaian/kinerja atau seberapa jauh kita dari posisi acuan. Indikator merupakan ukuran, referensi atau indeks yang menjadi detektor dalam mengenali suatu hasil proses, yang pada gilirannya dapat memberikan petunjuk mengenai apa yang harus dibenahi.

Contoh indikator dapat ditemui dalam hasil pemeriksaan darah yang berisi angka penunjuk tentang jumlah trombosit, hematoktrit, dsb. Disertai dengan informasi dari pasien atau jika perlu dengan tambahan indikator lain, para Diagnoser dapat menegakkan diagnosa. Saat berjalan di kawasan pabrik, dan melihat kepulan asap yang hitam pekat, para engineer bisa menduga what happen there, atau saat mengendarai mobil, kita dapat mengetahui apakah kecepatan saat ini sesuai dengan Max. Speed, jika tidak maka prrriiiit...kena tilang.

Perjalanan Menuju Kota Tujuan
Pada tahun 1988, saya naik bis dari Jember ke Jakarta. Berangkat jam 4 sore dan tiba di Pulogadung pukul 10 pagi keesokan harinya. Perlu waktu 22 jam dengan biaya sekitar 100 ribu. Saat naik pesawat, dari Jakarta ke Medan diperlukan waktu sekitar 2 jam. Tarifnya pun tergantung pada airlines yang digunakan, jika diratakan sekitar 1,5 juta. Naik Ferry ke Tomok, Samosir perlu waktu 1 jam, dan dari sini ke kampung saya di Sideak merupakan perjalanan yang indah dengan viewnya Tao Toba na uli.

Dalam "perjalanan" ini sang Sopir mengantar penumpangnya sampai di tempat tujuan.
Apa yang ada dalam benak keluarga jika dalam 25 jam, belum tiba di Jakarta? Berbagai kontak telepon dilakukan untuk mengetahui kabar.

Apa yang ada dalam benak penumpang pesawat, saat melihat jam tangan dan ternyata sudah 2 jam 30 menit dan Anda belum landing? Dari balik mikropon sang Stewardess/Pilot menyampaikan bahwa ban pesawat tidak terbuka dan berupaya menenangkan penumpang. Penumpang tegang panik, serta merta berbagai doa dipanjatkan kepadaNya.

Indikator sederhana untuk sampai di tempat tujuan adalah Keselamatan. Disisi lain faktor Waktu dan Biaya menjadi interest factors saat pembicaraan memasuki area efektifitas dan efisiensi.

Perjalanan Menuju Penyelesaian Studi
Saat belajar ukuran keberhasilan siswa tercermin dalam Rapor atau KHS. IP yang diperoleh merupakan indikator kepuasan atas hasil studi mahasiswa. Mungkin saja seseorang dengan IP rendah -dapat berhasil dalam kehidupannya- jika dibandingkan IP yang diraihnya, namun IP 3 adalah tiket bagi para pencari kerja untuk lolos persyaratan administrasi pada semua jenis lowongan pekerjaan. Bagaimana dengan lama Studi? Ya beberapa organisasi memiliki kriteria seleksi yang lebih ketat.

Dalam "perjalanan" ini, sang Mahasiswa menjadi Manager bagi dirinya sendiri. Dengan resources yang ada padanya Ia mengorganisir dan mengarahkannya untuk mencapai tujuan yang didambakan saat di kelas 3 SMA. Bagaimana jika setelah 5 tahun, sang Mahasiswa belum selesai studi? Para stakeholders akan bertanya-tanya.

Ayah: Mas, kapan lulus?
Mhs: Sebentar lagi Ayah, saya susah ketemu dosen pembimbing Skripsi. Kuliah sekarang susah, banyak yg harus dipelajari. Doakan Ayah supaya saya cepat lulus.
(Ferry: kalo alasan kayak gini...hehehe pembaca pasti dapat membuat interpretasi logis sendiri.)

Ayah: Mas, kapan lulus?
Mhs: Semester kemarin saya ngulang untuk mata kuliah Ekonometrika, ingin buat IP 3, dan semester depan saya ambil Skripsi. Lulusnya 9 bulan lagi setelah skripsi selesai. Doakan Ayah supaya saya cepat lulus.
(Ferry: yaa...cukup logis, rupanya sang Siswa ingin IP 3).

Indikator sederhana untuk lulus S1, yaitu Lama Studi dan IP. Biaya studi mungkin menjadi interest factors dalam studi penelitian kelulusan.

Perjalanan Menuju Kemenangan Pertandingan
Sekitar 2 minggu lalu saya menonton pertandingan Pro Liga Volly antara Samator dan BNI. Pertandingan yang seru dan menarik ditunjukkan oleh kedua tim. Saya turut tegang, mungkin juga para pihak yang secara emosional terikat dalam keluarga besar maupun fans, apalagi Organ Tim yang selama ini bekerja keras untuk masuk final.

Dengan skor sebagai indikatornya, Pelatih dan Manajer Tim mengubah strategi dan taktik bertanding, dan dengan catatan pada recording log pemain, mereka mengganti dan mengistirahatkan pemain, memberi semangat, mengarahkan semua sumber daya untuk mencapai tujuan "to be a winner". BNI akhirnya tak terbendung oleh Samator sang juara bertahan.

Setelah kedua Tim kembali ke markas mereka, apa yang dilakukan? Yes, mengapresiasi perjuangan berat dan tentu Evaluasi untuk perbaikan berikutnya. Indikator keberhasilan adalah Win atau Loss. Bagi para Tim interest factors mungkin berupa Skor, kesalahan/ keberhasilan individu pemain, kekuatan lawan.

Perjalanan Pencapaian Visi
Dalam operasional sektor private maupun sektor publik terdapat indikator pencapaian/kinerja. Dari sisi manajemen Keuangan, Operasional, Pemasaran, SDM, dan Strategi (waah saya baru sadar nih sama dengan jumlahnya Pilihan Konsentrasi/Penjurusan saat kuliah) akan diukur dan kemudian dievaluasi. Caranya pun beragam dengan melibatkan Sejawat Satu Level, oleh atasan Satu Level di atas, oleh bawahan Satu Level di bawah, bahkan dengan Customer maupun Ownernya.

Indikatornya tertuang misalnya dalam KPI, KGI, Strategic Objectives, Standar Pelayanan Minimal. Misalnya dalam bidang kesehatan kita, mengetahui visi tentang "Indonesia Sehat 2010". Disana tertuang detail kriterianya. Dalam bidang ekonomi makro ada studi indikatornya dan bidang perbankan.

Ukuran keberhasilan Sopir adalah No Accident dan penumpang tiba di Terminal tujuan, bagi Pelatih adalah kemenangan, dan bagi Siswa adalah kelulusan. Indikator ini begitu jelas dan mudah diinderai.

Bagaimana dengan ukuran di sektor private dan publik? Beberapa diantaranya Growth, Profit,
Sustainability...silahkan baca Laporan dan Juknisnya.

Inti Indikator adalah measurable dan observable.

Selasa, 18 Mei 2010

Export PostgreSQL table into CSV file

1. Change directory to PostgreSQL binary folder or just type this command if the search path is already listed in your environment paths.

C:\pgsql83\bin>psql -dmydb -Uferry

mydb# COPY customer TO 'C:/myfolder/allcust.csv' DELIMITER ';';
COPY 5076

mydb# COPY (SELECT * FROM customer WHERE city ='PNK') TO E'C:\\myfolder\cityPNK.csv' DELIMITER ';' CSV;
COPY 502

mydb# \q

See: Import from CSV files into PostgreSQL Table

Importing a CSV file into PostgreSQL table

1. Export your data into CSV format. Remember the field delimiter you specify here (I prefer the semicolon) and you must pay attention or change it later if the import process fails. Also uncheck the option for first line as a header so that the CSV file contains only data.

2. If not exists, create a table in PostgreSQL with the data type that can accommodate the data to be imported.

3. Change directory to PostgreSQL binary folder or just type this command if the search path is already listed in your environment paths.

C:\pgsql83\bin>psql -dmydb -Uferry
mydb# COPY dest_table FROM 'C:/myfolder/myfile.csv' USING DELIMITERS ';';
COPY 10537

mydb# COPY another_dest_table FROM 'C:/myfolder/myfile22.csv' USING DELIMITERS ';';
COPY 300024

mydb# \q

See: Export from PostgreSQL to CSV files

Sabtu, 15 Mei 2010

My list show only one record after doing edit-close form repeatedly

I was coding a form with a datagridview for single table. All Insert, Update, and Delete operations work well and satisfy me. But I saw a strange behaviour, when I did these:

1. Open the form, Edit some data, then click Save button..(data updated successfully!)
2. Close the form.
3. Do step 1-2 repeatedly.

After n times opening-editing-closing the form, the datagridview only show one record???
My list show only one record after doing edit-close form repeatedly.

public partial class frmCoa : mybasefrm.frmMainGrdView
{
private MySqlDataAdapter gda;
private DataTable gdt;
private DBOPS.SqlHelper;

private void frmCoa_Load(object sender, EventArgs e)
{
gHelper = new DBOPS.SqlHelper();
gda = gHelper.getDataAdapter("SELECT * FROM akun");
MySqlCommandBuilder gcmdBldr = new MySqlCommandBuilder(gda);
gdt = new DataTable();
gda.Fill(gdt);
bindSrc0.DataSource = gdt;
bindNav0.BindingSource = bindSrc0;
dgv.DataSource = bindSrc0;
...do binding
}

private void btnSave_Click(object sender, EventArgs e)
{
try
{
Validate();
bindSrc0.EndEdit();
gda.Update(gdt);
startingEdit(false);
base.buttonNormal();
}
catch (System.Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
return;
}
dgv.Enabled = true;
}
}


.

The form has a Query button, then without closing the application, I did some query to display all or some data, all query work as expected.

Don't know why this happened, and my guess is related to connection and data adapter (Fill method). I disable pooling connection in my connection string, and this seems quite resolve my problem. Any idea?

Selasa, 11 Mei 2010

Backup and restore all database between MySQL instances

I have two instances of MySQL, one using 5.0.27 and the other 5.5.3. My requirement is to transfer all database to a new one. I try to backup all database and restore using My SQL Administration Tools. All database successfully restored (imported) to the new instance, but got problem with privilege that reports Column count of mysql.proc is wrong. Expected 20, found 16. The table is probably corrupted.

Then I look at the backup script but could not found command to create/insert user privilege on mysql database. Probably I missed something, and glad to hear from you. I switch the way, and try following steps:

1. Do backup:
shell5027>mysqldump -uroot -ppass --all-database > C:\temp\sqldataku.sql

Then opened the backup script and found commands to create-insert users privileges on mysql database, something like these:

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `mysql` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `mysql`;
DROP TABLE IF EXISTS `db`;
CREATE TABLE `db` ( .... )...;
INSERT INTO `db` VALUES ('%','cms','fercms','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y'),....);

INSERT INTO `user` VALUES ('localhost','root','*7775476747C6AD73358FA54DAED7828A72014B4E','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','',0,0,0,0),('%','fercms','*778F407DE7C65307389FA34AAED7828A72014B4E','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','N','','','','',0,0,0,0), ...);

mysql.user table contains user list (with passwords) and their global privileges, mysql.db handles users' database-level privileges.

2. Do restore:
shell553>mysql -uroot -ppass < C:\temp\sqldataku.sql

3. Do flush privilege:
shell553>mysql -uroot -ppass
mysql> flush privileges;
mysql>\q

Test the database using myprogram or tools but come with error message: Column count of mysql.proc is wrong. Expected 20, found 16. The table is probably corrupted;

4. Do upgrade, by run this command:
shell553>mysql_upgrade -uroot -ppass --tmpdir=C:\temp\

Looking for 'mysql.exe' as: shell553\mysql.exe
Looking for 'mysqlcheck.exe' as: shell553\mysqlcheck.exe
Running 'mysqlcheck' with connection arguments: "--port=3306"
drupal64.access OK
drupal64.actions OK
fkm.phpbb_acl_groups OK
fkm.phpbb_acl_options OK
Running 'mysql_fix_privilege_tables'...
ERROR 1547 (HY000) at line 167: Column count of mysql.proc is wrong. Expected 20, found 16. The table is probably corrupted
ERROR 1547 (HY000) at line 168: Column count of mysql.proc is wrong. Expected 20, found 16. The table is probably corrupted
ERROR 1547 (HY000) at line 181: Column count of mysql.proc is wrong. Expected 20, found 16. The table is probably corrupted
WARNING: NULL values of the 'character_set_client' column ('mysql.proc' table) have been updated with a default value (cp850). Please verify if necessary.
WARNING: NULL values of the 'collation_connection' column ('mysql.proc' table) have been updated with a default value (cp850_general_ci). Please verify if necessary.
WARNING: NULL values of the 'db_collation' column ('mysql.proc' table) have been updated with default values. Please verify if necessary.
FATAL ERROR: Upgrade failed

Once again I run the command:
shell553>mysql_upgrade -uroot -ppass --tmpdir=C:\temp\
...
...
Running 'mysql_fix_privilege_tables'...
OK

I did the command again, and reported that "This installation of MySQL is already upgraded to 5.5.3-m3, use --force if you still need to run mysql_upgrade".

If these solve my requirement above (I have to see in future), than I suspect that first try using MySQL Administration Tools should work as well.

Senin, 10 Mei 2010

SELECT command denied for table 'proc'

By using MySQL Administrator Tool or phpMyAdmin, we could administer users. For example create Esterina as a new user then grant all available privilege to her. One of the privilige granted was run by this command.

GRANT CREATE ROUTINE ON mydb.* TO esterina@ 'localhost';

The CREATE ROUTINE privilege is needed to create stored routines (procedures and functions).

On her desk, she open TOAD, create some table then create a procedure with this command:

DROP PROCEDURE IF EXISTS mydb.'tester';
CREATE PROCEDURE mydb.'tester'(IN stat INT)
BEGIN
set @STATUS=stat;
END;

The procedure created successfully, but she could not see the procedure on TOAD GUI. She will receive an error message:

MySQL Database Error
SELECT command denied to user esterina@ 'localhost'
for table 'proc';

For her to be able to see her procedure, she must contact her boss, then with super user privilege the adminstrator run this:

GRANT SELECT ON mysql.proc TO esterina@ 'localhost';

Esterina back to her workbench, with tons of plan!

Minggu, 09 Mei 2010

Does SQLite support foreign keys?

Short Answer:
FOREIGN KEY constraints are parsed but are not enforced. However, the equivalent constraint enforcement can be achieved using triggers.

A. Foreign Key (FK)
FK is a referential constraint between two tables. A FK is a field(s) that reference to the primary key of another table. The purpose of the FK is to ensure referential integrity of the data. The values in one row of the referencing columns must occur in a single row in the referenced table. Thus, a row in the referencing table cannot contain values that don't exist in the referenced table (except potentially NULL).

This way references can be made to link information together and it is an essential part of database normalization. Multiple rows in the referencing table may refer to the same row in the referenced table. Most of the time, it reflects the one (master table, or referenced table) to many (child table, or referencing table) relationship.

FK is defined in DDL (Data Definition Language), so we do not code in our application. Once we define FK constraints, they must remain true while inputting/modifying/deleting data in the database. Constraints are used to enforce table rules and prevent data dependent deletion (enforce database integrity).


B. Enforce Foreign Key Constraint using PRAGMA
The PRAGMA statement is a SQL extension specific to SQLite and used to modify the operation of the SQLite library or to query the SQLite library for internal (non-table) data. The foreign_keys pragma controls the enforcement of foreign key constraints in all of the attached databases. If set to off, foreign key constraints are ignored. The default value is off.

For many years SQLite would parse foreign key constraints, but was unable to enforce them. When native support for foreign key constraints was finally added to the SQLite core, enforcement was left off by default to avoid any backwards compatibility issues.

This default value may change in future releases. To avoid problems, it is recommended that an application explicitly set the pragma one way or the other. This pragma cannot be set when there is an active transaction in progress.

1. Parent table: We define Primary Key
CREATE TABLE parentorder (
jmid VARCHAR(16) NOT NULL PRIMARY KEY,
jmdate DATE NOT NULL,
jmsupp VARCHAR(6) NOT NULL);


2. Child table: We define a reference to primary key above
CREATE TABLE childorder (
jm2id VARCHAR(16) NOT NULL CONSTRAINT fk_childorder_id REFERENCES parentorder(jmid),
jm2no VARCHAR(3) NOT NULL,
jm2itemid VARCHAR(6) NOT NULL,
jm2qty INTEGER NOT NULL,
PRIMARY KEY (jm2id,jm2no));

Test them in SQLite
sqlite>select sqlite_version();
3.6.23.1
sqlite> insert into parentorder values ('A1','2010-05-08','SUP1');
sqlite> insert into childorder values ('A1','P','CODE1', 10.5);
sqlite> insert into childorder values ('A1','V','CODE2', 11);

here we try with unexisting key in the primary key of parentorder table.
sqlite> insert into childorder values ('A2','X','CODE3', 12);

We see, FK constraint does not work, because the data A2 successfully inserted! It should raise an error for A2 is not exist in parent table.

Let's continue...with the PRAGMA statement
sqlite> PRAGMA foreign_keys;
0

Here we enforce the foreign key constraint to ON by using PRAGMA statement
sqlite> PRAGMA foreign_keys=1;
sqlite> update childorder set jm2id='A3' WHERE jm2id='A2';
Error: foreign key constraint failed


Look! We could not change A2 to A3, it means the FK constraint works!

sqlite> update childorder set jm2id='A1' WHERE jm2id='A2';
sqlite> select * from childorder;
A1 P CODE1 10.5
A1 V CODE2 11
A1 X CODE3 12


sqlite> select * from parentorder;
A1 2010-05-08 SUP1

sqlite> update childorder set jm2id='A3' WHERE jm2id='A1';
Error: foreign key constraint failed

C. Using Pragma in Program
using C#:
conn = new SQLiteConnection(connString);
conn.Open();
const string sqlString = "PRAGMA foreign_keys = ON;";
SQLiteCommand command = new SQLiteCommand(sqlString, conn); command.ExecuteNonQuery();


D. Trigger
Maintain FK constraints in above scenario might be not simple as it should be, such as enforce FK constraint each time we use database or when using application through connection string, or set the pragma in SQLite command line. For these reason, below we implemet triggers for FK constraints. See more.

-- Foreign Key Preventing insert
CREATE TRIGGER fki_childorder_jm2id_parentorder_jmid
BEFORE INSERT ON [childorder]
FOR EACH ROW
BEGIN
SELECT RAISE(ROLLBACK, 'insert on table "childorder" violates foreign key constraint "fki_childorder_jm2id_parentorder_jmid"')
WHERE (SELECT jmid FROM parentorder WHERE jmid = NEW.jm2id) IS NULL;
END;

-- Foreign key preventing update
CREATE TRIGGER
fku_childorder_jm2id_parentorder_jmid
BEFORE UPDATE ON [childorder] FOR EACH ROW
BEGIN
SELECT RAISE(ROLLBACK, 'update on table "childorder" violates foreign key constraint "fku_childorder_jm2id_parentorder_jmid"')
WHERE
(SELECT jmid FROM parentorder WHERE jmid = NEW.jm2id) IS NULL;
END;

-- Foreign key preventing delete
CREATE TRIGGER fkd_childorder_jm2id_parentorder_jmid
BEFORE DELETE ON parentorder
FOR EACH ROW
BEGIN
SELECT RAISE(ROLLBACK, 'delete on table "parentorder" violates foreign key constraint "fkd_childorder_jm2id_parentorder_jmid"')
WHERE
(SELECT jm2id FROM childorder WHERE jm2id = OLD.jmid) IS NOT NULL;
END;

E. Testing Trigger Code
sqllite>.exit
C:\sqllite3>sqlite tesdb
SQLite version 3.6.23.1

sqlite> copy-paste fki_childorder_jm2id_parentorder_jmid trigger above!
sqlite> insert into childorder values ('A1ERR','P','CODE1', 10.5);
Error: insert on table "childorder" violates foreign key constraint "fki_childorder_jm2id_parentorder_jmid"

sqlite> do the same for fku_childorder_jm2id_parentorder_jmid!
sqlite> update childorder set jm2id='TESTING';
Error: update on table "childorder" violates foreign key constraint "fku_childorder_jm2id_parentorder_jmid"

sqlite> do the same for fkd_childorder_jm2id_parentorder_jmid!
sqlite> delete from parentorder;Error: delete on table "parentorder" violates foreign key constraint "fkd_childorder_jm2id_parentorder_jmid"

--This pragma returns one row for each foreign key that references a column in the argument table.
sqlite> pragma foreign_key_list('childorder');
0 0 parentorder jm2id jmid NO ACTION NO ACTION NONE


F. Utility
1. Use this utility to generate triggers to enforce foreign key constraints with sqlite, operates on database schema and understands most CREATE TABLE syntax. Win32 and linux x86 binaries included, public domain source code.

2. The triggers code above is generated using this web tool. You could try by copy-paste the two Create Table statement above (B.1 and B.2) then click Submit.


G. Trigger vs Constraint
Constraint is a rule define in DDL statement (Foreign Key, Primary Key, etc).
Trigger is a rule define using DML statement.
Both are useful in special situation.

Using triggers we could define complex processing logic, and also support all of the functionality of constraints; however, DML triggers are not always the best method for a given feature.

Entity integrity should always be enforced at the lowest level by indexes that are part of PRIMARY KEY and UNIQUE constraints or are created independently of constraints. Domain integrity should be enforced through CHECK constraints, and referential integrity (RI) should be enforced through FOREIGN KEY constraints, assuming their features meet the functional needs of the application. DML triggers are most useful when the features supported by constraints cannot meet the functional needs of the application.

Each RDBMS has their way for implementation of constraints and triggers, and we also know that there is SQL standards to meet. For constraints and triggers,  I keep these guidance:
-FK constraints can validate a column value only with an exact match to a value in another column, unless the REFERENCES clause defines a cascading referential action.
-Constraints can communicate about errors only through standardized system error messages.
-DML triggers can cascade changes through related tables in the database; however, these changes can be executed more efficiently through cascading referential integrity constraints.
-DML triggers can disallow or roll back changes that violate referential integrity, thereby canceling the attempted data modification. Such a trigger might go into effect when you change a foreign key and the new value does not match its primary key. However, FOREIGN KEY constraints are usually used for this purpose.
-If constraints exist on the trigger table, they are checked after the INSTEAD OF trigger execution but prior to the AFTER trigger execution. If the constraints are violated, the INSTEAD OF trigger actions are rolled back and the AFTER trigger is not executed.

Wish that in the next officials release of SQLite, the foreign keys constraints come with default on.

Jumat, 07 Mei 2010

SQLite: ROWID and VACUUM

A. ROWID
Every row of every SQLite table has a 64-bit signed integer key that is unique within the same table. This integer is called "rowid". The rowid is the actual key used in the B-Tree that implements an SQLite table. Because rows are stored in rowid order, a rowid is a candidate for a primary key, as it can uniquely identify a record within a table...

Below we see how it works:

1. WITHOUT Primary Key Keyword
sqlite>CREATE TABLE t1 (name TEXT);
sqlite>insert into t1 values ('a');
sqlite>insert into t1 values ('b');
sqlite>insert into t1 values ('c');
sqlite>insert into t1 values ('d');
sqlite>select rowid, name from t1;
rowid name
1 a
2 b
3 c
4 d

sqlite>delete from t1 where name='a';
sqlite>delete from t1 where rowid=3;
sqlite>select rowid, name from t1;
rowid name
2 b
4 d
sqlite>vacuum;
sqlte>select _rowid_, name from t1;

rowid name
1 b
2 d

2. WITH Primary Key Keyword
CREATE TABLE t2 (pk INTEGER PRIMARY KEY, name TEXT);

insert into t2(name) values ('a');
insert into t2(name) values ('b');
insert into t2(name) values ('c');
insert into t2(name) values ('d');

select rowid, pk, name from t2;
pk pk_1 name
1 1 a
2 2 b
3 3 c
4 4 d

delete from t2 where name='a';
delete from t2 where rowid=3;
select oid, pk, name from t2;
pk pk_1 name
2 2 b
4 4 d

sqllite>vacuum;
select oid, pk, name from t2;
pk pk_1 name
2 2 b
4 4 d

B. OBSERVED
- As we saw, the ROWID in the second sample will be retain static!
- So, don't forget to include INTEGER PRIMARY KEY in your Create Table statement.
- Rowid is integer key with amount of 9223372036854775807. Is it enough for you?.
- The rowid value can be accessed using one of the special names "ROWID", "OID", or "_ROWID_".
- If a column is declared to be an INTEGER PRIMARY KEY, then that column is not a "real" database column but instead becomes an alias for the rowid. Unlike normal SQLite columns, the rowid must be a non-NULL integer value.
- The VACUUM command may change the ROWIDs of entries in tables that do not have an explicit INTEGER PRIMARY KEY.

C. VACUUM
When an object (table, record, index, trigger, or view) is dropped from the database, it leaves behind empty space. This empty space will be reused the next time new information is added to the database. But in the meantime, the database file might be larger than strictly necessary. Also, frequent inserts, updates, and deletes can cause the information in the database to become fragmented - scrattered out all across the database file rather than clustered together in one place.

The VACUUM command cleans the main database by copying its contents to a temporary database file and reloading the original database file from the copy. This eliminates free pages, aligns table data to be contiguous, and otherwise cleans up the database file structure.

Sabtu, 01 Mei 2010

Unlock DataGridView properties in Inherited Form

Form inheritance improve our coding time. But I'm facing a problem while inherit a form that contain DataGridView control. I could not modify the DataGridView properties. Eventhough change the modifier property to protected or public. The DataGridView control still locked in designer.

Here a brief step to work with:
1. I add a new class file for example FerDataGrdView.cs in my library objects (mylib.dll).
2. Type this code:
using System.Windows.Forms;
using System.ComponentModel;
namespace Ferryptk
{
[Designer(typeof( System.Windows.Forms.Design.ControlDesigner))]
public class FerDataGrdView : DataGridView { }
}

3. Build library (mylib.dll).
4. Add reference to mylib.dll
5. Drag the control (FerDataGrdView) in ancestor form.
6. Do form inheritance.
7. Now, I could modify the properties of DataGridView control.

O.. happy day..

Selasa, 27 April 2010

SQLite is so simple

SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. It means a simplicity. Simplicity in a database engine can be either a strength or a weakness, depending on what you are trying to do.

A. Appropriate Uses
The primary design goal of SQLite is to be simple:
- Simple to administer
- Simple to operate
- Simple to embed in a larger program
- Simple to maintain and customize

So use SQLite in situations where simplicity of administration, implementation, and maintenance are more important than the countless complex features that enterprise database engines provide. SQLite is small, fast and reliable. Reliability is a consequence of simplicity. With less complication, there is less to go wrong.

B. Situations Where SQLite Works Well
1. Application File Format
SQLite has been used with great success as the on-disk file format for desktop applications such as financial analysis tools, CAD packages, record keeping programs, and so forth. The traditional File/Open operation does an sqlite3_open() and executes a BEGIN TRANSACTION to get exclusive access to the content. The use of transactions guarantees that updates to the application file are atomic, consistent, isolated, and durable (ACID).

2. Embedded devices and applications
SQLite is a good choice for devices or services that must work unattended and without human support. SQLite is a good fit for use in cellphones, PDAs, set-top boxes, and/or appliances. It also works well as an embedded database in downloadable consumer applications.

3. Websites
SQLite usually will work great as the database engine for low to medium traffic websites (which is to say, 99.9% of all websites). The amount of web traffic that SQLite can handle depends, of course, on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite.

4. Replacement for ad hoc disk files
Many programs use fopen(), fread(), and fwrite() to create and manage files of data in home-grown formats. SQLite works particularly well as a replacement for these ad hoc data files.

5. Internal or temporary databases
For programs that have a lot of data that must be sifted and sorted in diverse ways, it is often easier and quicker to load the data into an in-memory SQLite database and use queries with joins and ORDER BY clauses to extract the data in the form and order needed rather than to try to code the same operations manually. Using an SQL database internally in this way also gives the program greater flexibility since new columns and indices can be added without having to recode every query.

6. Command-line dataset analysis tool
Experienced SQL users can employ the command-line sqlite program to analyze miscellaneous datasets. Raw data can be imported from CSV files, then that data can be sliced and diced to generate a myriad of summary reports. Possible uses include website log analysis, sports statistics analysis, compilation of programming metrics, and analysis of experimental results.

You can also do the same thing with an enterprise client/server database, of course. The advantages to using SQLite in this situation are that SQLite is much easier to set up and the resulting database is a single file that you can store on a floppy disk or flash-memory stick or email to a colleague.

7. Stand-in for an enterprise database during demos or testing
If you are writing a client application for an enterprise database engine, it makes sense to use a generic database backend that allows you to connect to many different kinds of SQL database engines. It makes even better sense to go ahead and include SQLite in the mix of supported databases and to statically link the SQLite engine in with the client. That way the client program can be used standalone with an SQLite data file for testing or for demonstrations.

8. Database Pedagogy
Because it is simple to setup and use (installation is trivial: just copy the sqlite or sqlite.exe executable to the target machine and run it) SQLite makes a good database engine for use in teaching SQL. Students can easily create as many databases as they like and can email databases to the instructor for comments or grading.

11. Experimental SQL language extensions
The simple, modular design of SQLite makes it a good platform for prototyping new, experimental database language features or ideas.

C. Situations Where Another RDBMS May Work Better
1. Client/Server Applications

If you have many client programs accessing a common database over a network, you should consider using a client/server database engine instead of SQLite. A good rule of thumb is that you should avoid using SQLite in situations where the same database will be accessed simultaneously from many computers over a network filesystem.

2. High-volume Websites
SQLite will normally work fine as the database backend to a website. But if you website is so busy that you are thinking of splitting the database component off onto a separate machine, then you should definitely consider using an enterprise-class client/server database engine instead of SQLite.

3. Very large datasets
With the default page size of 1024 bytes, an SQLite database is limited in size to 2 tebibytes (241 bytes). And even if it could handle larger databases, SQLite stores the entire database in a single disk file and many filesystems limit the maximum size of files to something less than this. So if you are contemplating databases of this magnitude, you would do well to consider using a client/server database engine that spreads its content across multiple disk files, and perhaps across multiple volumes.

4. High Concurrency
SQLite uses reader/writer locks on the entire database file. That means if any process is reading from any part of the database, all other processes are prevented from writing any other part of the database. Similarly, if any one process is writing to the database, all other processes are prevented from reading any other part of the database. For many situations, this is not a problem. Each application does its database work quickly and moves on, and no lock lasts for more than a few dozen milliseconds. But there are some applications that require more concurrency, and those applications may need to seek a different solution.

D. Want to explore?
1. Installation
Download Precompiled Windows Binaries:
1. Download http://www.sqlite.org/sqlite-3_6_23_1.zip (contains: sqllite3.exe)
2. and this http://www.sqlite.org/sqlitedll-3_6_23_1.zip (This is a DLL of the SQLite library)
3. Extract all the file and put in one directory (ex: C:/sqlite3)

C:\sqlite3>dir
Volume in drive C has no label.
Volume Serial Number is 9863-4221
Directory of C:\sqlite3
2010-04-27 00:13 .
2010-04-27 00:13 ..
2010-03-29 16:02 3.809 sqlite3.def
2010-03-29 16:02 520.234 sqlite3.dll
2010-03-29 16:02 528.522 sqlite3.exe
3 File(s) 1.052.565 bytes
2 Dir(s) 84.336.992.256 bytes free

The only external dependency is MSVCRT.DLL.

2. Create Database
A standalone program called sqlite3 is provided which can be used to create a database, define tables within it, insert and change rows, run queries and manage an SQLite database file. This program is a single executable file on the host machine. It also serves as an example for writing applications that use the SQLite library.


C:\sqlite3>sqlite3 pontianak.db3
SQLite version 3.6.23.1
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .exit

SQLite will create a new one, if the database does not exist.

3. Create Table
If you are not exit in the previous step, just do

sqlite> create table create table mytab (pk integer primary key, nametext not null);
sqlite> .table (this a sqllite command line to display tables, for other commands just type .help
mytab
sqlite>

or if you have exitted, type this:

C:\sqlite3>sqlite3 pontianak.db3 "create table mytab (pk integer primary key, nametext not null);


4. Insert Data
C:\sqlite3>sqlite3 pontianak.db3 "insert into mytab values (100, 'My Name');"
C:\sqlite3>sqlite3 pontianak.db3 "insert into mytab values (200, 'Your Name');"
or

sqlite>insert into mytab values (300, 'Tova Naruto');


5. Display Data
C:\sqlite3>sqlite3 pontianak.db3 "select * from mytab ;"
or

sqlite>select * from mytab;
100My Name
200Your Name
300Tova Naruto


E. GUI for Data Administration
Yes, you are absolutely right...for productivity reason we use GUI for data administration. You can find some in Management Tools , and I use SQLite Administration.

As stated above, if we want to move our database into another folder, computer, other device or mail it, just copy and paste pontianak.db3 database into destination.

At all...it's so simple and now it's time for me to do my job.
Happy coding and for detail see this.