Friday, September 26, 2008

.NET Framework Common Language Runtime

1. Common Language Runtime (CLR)

Common Language Runtime (CLR) is a run-time environment provided by the .NET Framework , which runs the code and provides services that make the development process easier. CLR is a rich set of features for cross-language development and deployment. CLR supports both Object Oriented Languages as well as procedural languages. CLR provides security, garbage collection, cross language exception handling, cross language inheritance and so on.

Responsibilities:
1. Garbage Collection (GC) : CLR automatically manages memory in .NET framework. When objects are no longer in use Garbage Collection (GC) automatically releases those memories, which provides efficient memory management.
2. Code Access Security (CAS) : CAS determines whether a piece of code is allowed to run or not and what are the resources that it can use while running. CAS grants rights to program based upon security configuration of machine.
3. Code Verification : This ensures proper code execution and type safety while the code runs. It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.
4. Microsoft Intermediate Language (MSIL) : CLR uses JIT compiler to compile the Intermediate Language code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL code.

2. Microsoft Intermediate Language (MSIL)

Microsoft Intermediate Language is a platform independent language that gets compiled into platform dependent executable file or Dynamic Link Library. It is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Before code can be run, MSIL must be converted to CPU-specific code, by a just-in-time (JIT) compiler. It means .NET compiler can generate code written using any of the CLR languages and finally convert it to the required machine code(native code) depending on the target machine.
3. Just-in-time (JIT) Compiler
A Just-In-Time (JIT) compiler is used to translate the MSIL code into native code during execution time. Before you can run MSIL, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler. Because the common language runtime supplies a JIT compiler for each supported CPU architecture, developers can write a set of MSIL that can be JIT-compiled and run on computers with different architectures.
Each method for which MSIL has been generated is JIT-compiled when it is called for the first time, and then run. The next time the method is run, the existing JIT-compiled native code is run.
JIT compilation takes into account the fact that some code might never get called during execution. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as needed during execution and stores the resulting native code so that it is
accessible for subsequent calls.

As part of compiling MSIL to native code, code must pass a verification process, that examines MSIL and metadata to find out whether the code is type safe.
4. Metadata
When a compiler produces MSIL, it also produces metadata. Metadata describes the types in your code, including the definition of each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at execution time. The MSIL and metadata are contained in a portable executable (PE) file. The presence of metadata in the file along with the MSIL enables your code to describe itself. The runtime locates and extracts the metadata from the file as needed during execution. Every type and member defined and referenced in a module or assembly is described within metadata. When code is executed, the runtime loads metadata into memory and references it to discover information about code's classes, members, inheritance, and so on.
Metadata provides the following major benefits :
Self-describing files : Common language runtime modules and assemblies are self-describing. A module's metadata contains everything needed to interact with another module. Runtime modules and assemblies do not even require registration with the operating system.
Language interoperability and easier component-based design : Metadata provides all the information required about compiled code for you to inherit a class from a PE file written in a different language. You can create an instance of any class written in any managed language.
Attributes : The .NET Framework allows you to declare specific kinds of metadata, called attributes, in your compiled file. Attributes can be found throughout the .NET Framework and are used to control in more detail how your program behaves at run time.
5. Managed code
Managed code is code that has its execution managed by the runtime. Code that you develop with a language compiler that targets the runtime is called managed code. During execution, managed code receives services such as garbage collection, security, interoperability with unmanaged code, cross-language debugging support, and enhanced deployment and versioning support. Managed code provides information (i.e., metadata) to allow the CLR to locate methods encoded in assembly modules, store and retrieve security information, handle exceptions, and walk the program stack.
Managed code can access both managed data and unmanaged data. Managed data can only be accessed by managed code. CLR automatically handles object layout and manages references to objects, releasing them when they are no longer being used. Objects whose lifetimes are managed in this way are called managed data. Using Garbage collection, CLR allocate and release memory and eliminates some other common programming errors.
6. Unmanaged Code
Code that runs outside the runtime is called unmanaged code. Code that is created without regard for the conventions and requirements of the common language runtime. Unmanaged code executes in the common language runtime environment with minimal services (for example, no garbage collection, limited debugging, and so on). COM components, ActiveX interfaces, and Win32 API functions are examples of unmanaged code.
7. Native code
Native code is computer programming code that is compiled to run with a particular processor and its set of instructions. If the same program is run on a computer with a different processor, software can be provided so that the computer emulates the original processor. In this case, the original program runs in "emulation mode" on the new processor and almost certainly more slowly than in native mode on the original processor. Native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler. Microsoft's .NET compilers for its Visual Basic, C#, and JavaScript languages produce MSIL that can be compiled into native code before execution by a just-in-time compiler for faster performance.
8. Common Type System (CTS)
The common type system defines how types are declared, used, and managed in the runtime, and is also an important part of the runtime's support for cross-language integration. CTS is a standard that specifies how Type definitions and specific values of Types are represented in computer memory. CTS describes how types are defined and how they behave in .NET Framework. The common type system performs the following functions:
  • To establishe a framework that helps enable cross-language integration, type safety, and high performance code execution.
  • To provide an object-oriented model that supports the complete implementation of many programming languages.
  • To define rules that languages must follow, which helps ensure that objects written in different languages can interact with each other.
The common type system supports two general categories of types:
Value types : Value types directly contain their data, and instances of value types are either
allocated on the stack or allocated inline in a structure. Value types can be built-in, user-defined, or enumerations.
Assigning one value type variable to another copies the contained value. It is not possible to derive a new type from a value type. It is not possible for a value type to contain the null value.Each value type has an implicit default constructor that initializes the default value of that type.
Reference types : Reference types store a reference to the value's memory address, and are
allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates.
Assignment of reference type variables, copies a reference to the object but not the object itself.
Variables that are value types each have their own copy of the data, and therefore operations on one variable do not affect other variables. Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same object referred to by another variable.
9. Common Language Specification
The Common Language Specification (CLS) is a basic set of language features common to many programming languages and defines rules for how those features are used. It defines the mininum requirements of types that must be supported by any .NET language.
To fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with. For this reason, the Common Language Specification (CLS), has been defined. The Common Type System defines a set of rules compilers must follow for types so that objects of types written in different languages can interact. The CLS rules define a subset of the common type system.
The CLS helps enhance and ensure language interoperability. Language interoperability is the ability of code to interact with code that is written using a different programming language. The common language runtime provides the necessary foundation for language interoperability by specifying and enforcing a common type system and by providing metadata. The CLS also establishes requirements for CLS compliance. Components that adhere to the CLS rules and use only the features included in the CLS are said to be CLS-compliant components.
The common language runtime provides built-in support for language interoperability. However, this support does not guarantee that code you write can be used by developers using another programming language. To ensure that you can develop managed code that can be fully used by developers using any programming language, a set of language features and rules for using them, called the Common Language Specification (CLS), has been defined. Components that follow these rules and expose only CLS features are considered CLS-compliant.
10. Type safety
Type-safe code accesses only the memory locations it is authorized to access. For example, type-safe code cannot read values from another object's private fields. Type-safe code is code that accesses types only in well-defined, allowable ways.
JIT compilation performs an optional verification process that examines metadata and MSIL to determine whether the code is type-safe. Code that is proven during verification to be type-safe is called verifiably type-safe code. This process is skipped if the code has permission to bypass verification.
Type safety plays a crucial role in assembly isolation and security enforcement. When code is type safe, the common language runtime can completely isolate assemblies from each other. This isolation helps ensure that assemblies cannot adversely affect each other and it increases application reliability.

Dynamically number or rank rows in SQL Server using SELECT statement

By using a SELECT statement we can dynamically number or rank rows. This method is the only possible solution and which is faster than the procedural solution. Row numbering or ranking is a typical procedural issue. Typical solutions are based on loops, cursors and temporary tables. But this technique is based on an auto join. The chosen relationship is typically "is greater than.". Count how many times each element of a particular set of data fulfills the relationship "is greater than" when the set is compared to itself.

In SQL Server 2000

SELECT SerialNo = count(*), A.FirstName FROM Employee A, Employee B
WHERE A.FirstName >= B.FirstName
GROUP BY A.FirstName
ORDER BY SerialNo

Result :SerialNo FirstName
1 Abhilash
2 Aby
3 Admin
4 Anand
5 Aneesh
6 Arun
7 Justin
8 Neethu
9 Roshin
10 Suresh

In the above sample, 'FirstName' column of 'Employee' table is selected with a dynamic number. Here the relationship used is 'greater than or equal to'. The technique is counting the number of times the 'FirstName' of 'A' is greater than or equal to the 'FirstName' in 'B'. If duplicte exist in 'FirstName' use relationship 'A.FirstName + A.LastName >= B.FirstName + B.LastName'

 
In SQL Server 2005
Use ranking functions that are provided as a new feature in SQL Server 2005. Ranking functions return a ranking value for each row in a partition. Depending on the Rank function used, some rows might receive the same value as other rows.
Transact-SQL provides the following ranking functions:

  • RANK
  • DENSE_RANK
  • ROW_NUMBER
  • NTILE

SELECT RANK() OVER (ORDER BY A.Firstname) AS SerialNo, A.Firstname FROM Employee A ORDER BY SerialNo

SELECT DENSE_RANK() OVER (ORDER BY A.Firstname) AS SerialNo, A.Firstname FROM Employee A ORDER BY SerialNo

 

SELECT ROW_NUMBER() OVER (ORDER BY A.Firstname) AS SerialNo, A.Firstname FROM Employee A ORDER BY SerialNo

SELECT NTILE(10) OVER (ORDER BY A.Firstname) AS SerialNo, A.Firstname FROM Users A ORDER BY SerialNo

Here Argument to NTITLE is a positive integer constant that specifies the number of buckets into which each partition must be divided.

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;
}

Monday, September 15, 2008

Difference between Web.Config and Machine.Config

The .NET Framework uses on .config files to define configuration options. The .config files are text-based XML files.

Machine.configSystem-wide configuration settings for the .NET Framework are defined in the Machine.config file. The default settings that are contained in the Machine.config file can be modified to affect the behavior of .NET applications on the whole system. Configuration done in machine.config file is affected on any application that runs on a particular machine(local machine ). Usually, this file is not altered. The default path of the Machine.config file is
%SystemRoot%\Microsoft.NET\Framework\% VersionNumber%\CONFIG\
folder.

Web.configWhen we want to change the ASP.NET configuration settings for a single application then we create a Web.config file in the root folder of the application. This Web.config file will override the settings in the Machine.config file. An Asp .net application has one web.config file which keeps the configurations required for the corresponding application.

Monday, September 08, 2008

Change password for Login in SQL Server

Use system stored procedure 'sp_password' to change password. This procedure is used to add or modify a password for a Microsoft Sql Server login. Take a new query window and execute this procedure.Syntax :
sp_password 'Old Password','new password','login name'

Sample :
1. If login is currently with a blank password you can add a password for it. Adding a password for login 'sa'.
sp_password NULL,'Sql2005','sa'2. If login is having a password already then you can change password. Changing password for login 'sa'.
sp_password 'Sql2005','amthlk','sa'
Errors
Possible errors you can see when you try to change password are :-
1. Password validation failed. The password does not meet policy requirements because it is not complex enough.2. Password validation failed. The password does not meet policy requirements because it is too short.
When you create a SQL Server login, the server will validate the password against the password policy of the local machine. To view or modify the password policy on your lacal machine, take 'Administrative Tools' in 'Control Panel'. You can see 'Local Security Policy' in 'Administrative Tools'. Open this by clicking. You can see 'Password Policy' under 'Account Policy'.
Changing password policy or using a password that meet the password policy will clear error.


You can Use CHECK_POLICY option to disable password policy validation.
Use ALTER LOGIN to configure policy application.

The following SQL statement will change password of login to a new password without knowing old password. It requires ALTER ANY LOGIN permission to execute.

ALTER LOGIN sa WITH PASSWORD = 'sql2005', CHECK_POLICY = OFF

Changing login password from old password to new one.
ALTER LOGIN sa WITH PASSWORD = 'amthlk' OLD_PASSWORD = 'sql2005';

Friday, September 05, 2008

To retrieve data stored in varbinary data type column

Varbinary data type can store Variable-length binary data with maximum size of 8,000 bytes. The storage size is the actual length of the data entered + 2 bytes. Column of this type can be used to store data such as images, sounds, video, Office documents, compressed data and other non-alphanumeric data.

Sample:To get password stored in SQL server table.
Table 'Users' have a field 'Password' with data type 'varbinary(50)'.
Run the following query to get password from the 'Password' field of the table 'Users' .

SELECT UserID, FirstName, LoginName, Convert(nvarchar(50),Password) FROM Users