Halaman

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.