Halaman

Jumat, 24 September 2010

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.