Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, November 12, 2009

Difference between const and readonly

The readonly keyword is different from the const keyword.

A const field can only be initialized at the time of declaration. It specifies that the value of the field or the local variable cannot be modified.
A readonly field or variable can be initialized either at the declaration or in a constructor in the same class. Therefore, readonly variable or fields can have different values depending on the constructor used. A static readonly field can be set at run time, so it can have a different value for different executions of the program. However, the value of a const field is set to a compile time constant.

A const field is a compile-time constant.
A readonly field is a runtime constant.

using System;

public class Test
{
public const int rows = 10; // Initialize a const field
public const int seats = rows + 25;
public const double size = 5.0, width = 72.5, height = 44.45;

public readonly int x = 30; // Initialize a readonly field
public readonly int y;

public Test()
{
y = 100; // Initialize a readonly instance field
}

public Test(int a, int b)
{
x = a;
y = b;
}
}

Thursday, September 25, 2008

Localizing column header text of datagridview using XML file

When I faced a problem involving Grid view control localization, I had come out with the code displayed here which solved the issues properly. I will like to present it here for fellow programmers. As far as the code is concerned, I can guarantee that this works.

Situation : When I was working for a MNC client project, it involves localization for all forms. For example, in a windows form named 'Employee', contains a datagridview named 'grdEmployee' with columns 'Employee ID', 'Employee Name', 'Company', 'Phone' and 'Email'.
My problem was with the Current UICulture. I need to change my current culture to 'ja'(Japanese). When I switch to Japanese culture display column header text of the grid view to the corresponding Japanese characters of the English headers.


I am using an XML file named 'GridLayout.xml' in the application base directory. Content of the XML file is shown below:

GridLayout.xml

< ?xml version="1.0" encoding="utf-8"?>
< datagridview>
< grid name="grdEmployee">
< columns language="en">
< headertext0>Employee ID< /headertext0>
< headertext1>Employee Name< /headertext1>
< headertext2>Company< /headertext2>
< headertext3>Phone< /headertext3>
< headertext4>Email< /headertext4>
< /columns>
< columns language="ja">
< headertext0>社員ID< /headertext0>
< headertext1>社員名< /headertext1>
< headertext2>会社< /headertext2>
< headertext3>電話番号< /headertext3>
< headertext4>メールアドレス< /headertext4>
< /columns>
< /grid>
< /datagridview>

The code I have wriiten in code window of the form 'Employee.cs' is as :

Employee.cs

// Import section
using System;
using System.Collections.Generic;
using System.ComponentModel;using System.Data;
using System.Drawing;using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Threading;
using System.Xml;

// Private variable used
private string culture;

// constructor
public Employee()
{
// Getting the current culture intended to be used from the App.Config file
culture = Service.GetAppSetting("Language", "ja");
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
InitializeComponent();
}

// Form load event
private void Employee_Load(object sender, EventArgs e)
{
// Calling the method used to localize the datagridview
LocalizeGridHeader();
}

// Method used to localize datagridview Column Headers
private void LocalizeGridHeader()
{
// calling method wriiten in class 'Service' to get XML node defined for 'grdEmployee'
XmlNode xmlNode = Service.GetXmlGridLayout("grdEmployee");
if (xmlNode == null) return;
foreach (DataGridViewColumn dc in grdEmployee.Columns)
{
dc.HeaderText = xmlNode.ChildNodes.Item(dc.Index).InnerText; // xmlNode["HeaderText0"].InnerText;
}
}

Also I have used a class named 'Service' to write the common method used in my application.The code in the class 'Service.cs' is as :

Service.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;
using System.IO;

// Method to get configuration values from the application configuration file 'App.config'
public static string GetAppSetting(string key, string defaultValue)
{
string AppSetValue = defaultValue;
if (ConfigurationManager.AppSettings[key] != null)
{
try
{
AppSetValue = ConfigurationManager.AppSettings[key];
}
catch
{
}
}
return AppSetValue;
}

// To get an XML node list from the 'GridLayout.xml' for the grid name passed in base directory
public static XmlNode GetXmlGridLayout(string gridName)
{
string language = Service.GetAppSetting("Language", "ja");
string filePath = AppDomain.CurrentDomain.BaseDirectory + "
\\GridLayout.xml";
XmlDocument xmlDoc = new XmlDocument();
XmlReader xr = XmlReader.Create(new StreamReader(filePath, Encoding.Default));
xmlDoc.Load(xr);
XmlNodeList nodeList;
nodeList = xmlDoc.SelectNodes("/DataGridView/Grid[@name='"+ gridName + "']/Columns
[@language='" + language + "']");
return nodeList.Item(0);
}

In this solution , a part of the Configuration file 'App.config' looks like:

App.config

< ?xml version="1.0" encoding="utf-8" ?>
< configuration>>
< system.windows.forms jitdebugging="true">
< appSettings>
< add key="Language" value="ja">
< !--< add key="Language" value="en">-->
< /appSettings>
< /configuration>

Monday, September 22, 2008

Excel Error "COMExceoption was unhandled" Old format or invalid type library.

When I try to open an Excel Workbook (C# and Excel 2003) using the following statement an error occurs.
oBooks.Open(path, 0, true, 5,"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,0,true);


Error is :

COMException was unhandled
Old format or invalid type library. (Exception from HRESULT: 0x80028018(TYPE_E_INVDATAREAD))


Solution
This is actually an error caused by the Excel. This occurs when you try to automate excel. In your machine the excel installed is english version and the current locale is set to some other language, in my case it was Japanese. The solution is to set the current culture of the thread to english "en-US" before calling this method. After calling this set culture back to culture you need.

Sample
public static void OpenExcelFile()

{
Excel.Application oExcel;
Excel.Workbooks oBooks;
Excel.Workbook oBook;
Excel.Sheets oSheets;
Excel.Worksheet oSheet;
Excel.Range oCells;
Object objMissing = System.Reflection.Missing.Value;
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");oExcel = new Excel.Application();
oBooks = oExcel.Workbooks;
string path = @"c:\test.xls";
//string path = "c:\\test.xls";
//Excel 2000
//oBooks.Open(path, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing,
objMissing, objMissing, objMissing, objMissing, objMissing, objMissing);
//Excel 2003
oBooks.Open(path, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0,
true);
oExcel.Visible = true;
oBook = oBooks.get_Item(1);
oSheets = oBook.Worksheets;
oSheet = (Excel.Worksheet)oSheets.get_Item(1);
oSheet.Activate();System.Threading.Thread.CurrentThread.CurrentCulture = CurrentCI;
}