Friday, June 27, 2008

What is the difference between VB.NET and C# ?

Well this is the most debatable issue in .NET community and people treat these languages like religion. It’s a subjective matter which language is best. Some like VB.NET’s natural style and some like professional and terse C# syntaxes. Both use the same framework and speed is also very much equivalents.
But still let’s list down some major differences between them
:-Advantages VB.NET :-Has support for optional parameters which makes COM interoperability much easy. With Option Strict off late binding is supported. Legacy VB functionalities can be used by using Microsoft.VisualBasic namespace. Has the WITH construct which is not in C#. The VB.NET part of Visual Studio .NET compiles your code in the background. While this is considered an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger. Advantages of C# XML documentation is generated from source code but this is now been incorporated in Whidbey. Operator overloading which is not in current VB.NET but is been introduced in Whidbey. Use of this statement makes unmanaged resource disposal simple. Access to Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies).
This is the major difference that you can access unmanaged code in C# and not in VB.NET.

What is concept of Boxing and Unboxing ?

Boxing permits any value type to be implicitly converted to type object or to any interface type implemented by value type. Boxing is a process in which object instances are created and copy values in to that instance. Unboxing is vice versa of boxing operation where the value is copied from the instance in to appropriate storage location. Below is sample code of boxing and unboxing where integer data type is converted in to object and then vice versa.

Dim x As IntegerDim y As Object x = 10‘ boxing process y = x‘ unboxing process x = y

What are Value types and Reference types ?

Value types directly contain their data which are either allocated on the stack or allocated in-line in a structure. 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. 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. All types are derived from the System.Object base type.

What are different types of JIT ?

JIT compiler is a part of the runtime execution environment. In Microsoft .NET there are three types of JIT compilers

1)Pre-JIT :- Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.

2)Econo-JIT :- Econo-JIT compiles only those methods that are called at runtime. However, these compiled methods are removed when they are not required.

3)Normal-JIT :- Normal-JIT compiles only those methods that are called at runtime. These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache issued for execution.

What is reflection?

All .NET assemblies have metadata information stored about the types defined in modules. This metadata information can be accessed by mechanism called as “Reflection”. System. Reflection can be used to browse through the metadata information. Using reflection you can also dynamically invoke methods using System.Type.Invokemember.

Can we force garbage collector to run ?

System.GC.Collect() forces garbage collector to run. This is not recommended but can be used if situations arises.

What is garbage collection?

Garbage collection is a CLR feature which automatically manages memory.
Programmers usually forget to release the objects while coding ..... Laziness (Remember in VB6 where one of the good practices is to set object to nothing).
CLR automatically releases objects when they are no longer inuse and refernced.
CLR runs on non-deterministic to see the unused objects and cleans them. One side effect of this non-deterministic feature is that we cannot assume an object is destroyed when it goes out of the scope of a function. we should avoid using destructors because before GCdestroys the object it first executes destructor in that case it will have to wait for code to release the umanaged resource. resultin in additional delays in GC.
So its recommended to implement IDisposable interface and write cleanup code in Dispose method and call GC.SuppressFinalizemethod so instructing GC not to call your constructor.

What is Delay signing ?

During development process you will need strong name keys to be exposed to developer which is not a good practice from security aspect point of view. In such situations you can assign the key later on and during development you can use delay signing
Following is process to delay sign an assembly:

First obtain your string name keys using SN.EXE. Annotate the source code for the assembly with two custom attributes from System.Reflection: AssemblyKeyFileAttribute, which passes the name of the file containing the public key as a parameter to its constructor. AssemblyDelaySignAttribute, which indicates that delay signing, is being used by passing true as a parameter to its constructor. For example as shown below:[Visual Basic] [C#] [assembly:AssemblyKeyFileAttribute("myKey.snk")] [assembly:AssemblyDelaySignAttribute(true)]The compiler inserts the public key into the assembly manifest and reserves space in the PE file forthe full strong name signature. The real public key must be stored while the assembly is built so that other assemblies that reference this assembly can obtain the key to store in their own assemblyreference. Because the assembly does not have a valid strong name signature, the verification ofthat signature must be turned off. You can do this by using the –r option with the Strong Name tool. The following example turns off verification for an assembly called myAssembly.dll.Sn –r myAssembly.dll80vJust before shipping, you submit the assembly to your organization's signing authority for the actual strong name signing using the –R option with the Strong Name tool. The following example signs an assembly called myAssembly.dll with a strong name usingthe sgKey.snk key pair.

Sn -R myAssembly.dll sgKey.snk

What is concept of strong names (Twist :- How do we generate strong names or what is the process of generating strong names , What is use of SN.EXE , How do we apply strong names to assembly ?

Strong name is similar to GUID(It is supposed to be unique in space and time) in COM components. Strong Name is only needed when we need to deploy assembly in GAC. Strong Names helps GAC to differentiate between two versions. Strong names use public key cryptography (PKC) to ensure that no one can spoof it. PKC use public key and private key concept. Following are the step to generate a strong name and sign a assembly :-

Go to “Visual Studio Command Prompt”. See below figure “Visual studio Command Prompt”. Note the samples are compiled in 2005 but 2003 users do not have to worry about it. Same type of command prompt will be seen in2003 also.

After you are in command prompt type sn.exe -k “c:\test.snk”.

After generation of the file you can view the SNK file in a simple notepad.

After the SNK file is generated it’s time to sign the project with this SNK file

Click on project -- properties and the browse the SNK file to the respective folder and compile the project.

Click on Use a key file to sign the assembly with strong name. and that’s it.

What is GAC (Twist :- What are situations when you register .NET assembly in GAC ?) ?

GAC (Global Assembly Cache) is used where shared .NET assembly reside. GAC is used in the following situations :-

· If the application has to be shared among several application.

· If the assembly has some special security requirements like only administrator scan remove the assembly. If the assembly is private then a simple delete of assembly the assembly file will remove the assembly. Note :- Registering .NET assembly in GAC can lead to the old problem of DLL hell, where COM version was stored in central registry. So GAC should be used when absolutely necessary.

what is Manifest? what is strongname?

An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE (Portable Executable) file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE (Portable Executable) file that contains only assembly manifest information.

The following table shows the information contained in the assembly manifest. The first four items — the assembly name, version number, culture, and strong name information — make up the assembly's identity.

Assembly name: A text string specifying the assembly's name.

Version number: A major and minor version number, and a revision and build number. The common language runtime uses these numbers to enforce version policy.

Culture: Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information. (An assembly with culture information is automatically assumed to be a satellite assembly.)

Strong name information: The public key from the publisher if the assembly has been given a strong name.

List of all files in the assembly: A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest.

Type reference information: Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.

Information on referenced assemblies: A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.

If you want to view a Assembly how to you go about it (Twist : What is ILDASM ?) ?

When it comes to understanding of internals nothing can beat ILDASM. ILDASM basically converts the whole exe or dll in to IL code.
To run ILDASM you have to go to "C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin".
Note: this applies if you had v1.1 you have to probably change it depending on the type of framework version you have.
If you run IDASM.EXE from the path you will be popped with the IDASM exe program as shown in figure ILDASM. Click on file and browse to the respective directory for the DLL whose assembly you want to view. After you select the DLL you will be popped with a tree view details of the DLL as shown in figure ILDASM.
On double clicking on manifest you will be able to view details of assembly, internal IL code etc.

What is Difference between NameSpace and Assembly?

This is one of the important question asked in most of the .NET technical interviews,

A namespace is a logical naming scheme for types in which a simple type name, such as MyType, is preceded with a dot-separated hierarchical name. Such a naming scheme is completely under control of the developers. For example, types MyCompany.FileAccess.A and MyCompany.FileAccess.B might be logically expected to have functionality related to file access. The .NET Framework uses a hierarchical naming scheme for grouping types into logical categories of related functionality, such as the ASP.NET application framework, or remoting functionality. Design tools can make use of namespaces to make it easier for developers to browse and reference types in their code.

The concept of a namespace is not related to that of an assembly. A single assembly may contain many types whose hierarchical names have different namespace roots, and a logical namespace root may span multiple assemblies. In the .NET Framework, a namespace is a logical design-time naming convention, whereas an assembly establishes the name scope for types at run time.

Namespace: It is a Collection of names wherein each name is Unique.

They form the logical boundary for a Group of classes.

Namespace must be specified in Project-Properties.

Assembly: It is an Output Unit. It is a unit of Deployment & a unit of versioning. Assemblies contain MSIL code.

Assemblies are Self-Describing. [e.g. metadata,manifest]

An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within their implementation unit, or by code outside that unit.

What is NameSpace?

Namespace is a group of classes, structures, interfaces, enumerations, and delegates, organized in a logical hierarchy by function, that enable you to access the core functionality you need in your applications.

Namespaces are the way that .NET avoids name clashes between classes. A namespace is no more than a grouping of data types, but it has the effect that the names of all data types within a namespace automatically get prefixed with the name of the namespace. It is also possible to nest namespaces within each other.

Or in general we can sya that a namespace uniquely identifies a set of names so that there is no ambiguity when objects having different origins but the same names are mixed together.

What are different types of Assembly?

There are 3 types of Assemblies

1) Private :- Used by only one application and stored in its own folder

2) Public :- Used by more than one application and store in GAC (Global Assembly Cache)

3) Satellite :- It is used during localization and Globalization

What is Assembly ?

An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly. Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions.

What Is Managed Code?

Managed code is code written in one of over twenty high-level programming languages that are available for use with the Microsoft .NET Framework, including C#, J#, Microsoft Visual Basic .NET, Microsoft JScript .NET, and C++. All of these languages share a unified set of class libraries and can be encoded into an Intermediate Language (IL). A runtime-aware compiler compiles the IL into native executable code within a managed execution environment that ensures type safety, array bound and index checking, exception handling, and garbage collection.

By using managed code and compiling in this managed execution environment, you can avoid many typical programming mistakes that lead to security holes and unstable applications. Also, many unproductive programming tasks are automatically taken care of, such as type safety checking, memory management, and destruction of unneeded objects. You can therefore focus on the business logic of your applications and write them using fewer lines of code. The result is shorter development time and more secure and stable applications.

What is the CTS?What is CLS(Common Language Specification)?

CTS = Common Type System. This is the full range of types that the .NET runtime understands. Not all .NET languages support all the types in the CTS.

CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected to support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program written in any language. This interop is very fine-grained - for example a VB.NET class can inherit from a C# class.

what is CLR

The Common Language Runtime (CLR) is the virtual machine component of Microsoft's .NET initiative. It is Microsoft's implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. The CLR runs a form of bytecode called the Common Intermediate Language (CIL, previously known as MSIL -- Microsoft Intermediate Language).

Developers using the CLR write code in a language such as C# or VB.Net. At compile time, a .NET compiler converts such code into CIL code. At runtime, the CLR's just-in-time compiler (JIT compiler) converts the CIL code into code native to the operating system. Alternatively, the CIL code can be compiled to native code in a separate step prior to runtime. This speeds up all later runs of the software as the CIL-to-native compilation is no longer necessary.

Although some other implementations of the Common Language Infrastructure run on non-Windows operating systems, Microsoft's implementation runs only on Microsoft Windows operating systems.

The virtual machine aspect of the CLR allows programmers to ignore many details of the specific CPU that will execute the program. The CLR also provides other important services, including the following:

Memory management

Thread management

Exception handling

Garbage collection

Security

Wednesday, June 25, 2008

What is IL

IL or MSIL

IL is a intermediate language, which is created when you compile the .net program. This is also a object oriented language. This makes cross language inheritance easier.

or in other words we can say it’s a language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler. The common language runtime includes a JIT compiler for converting MSIL to native code.

Where is version information stored of a assembly ?

All versioning of assemblies that use the common language runtime is done at the assembly level. The specific version of an assembly and the versions of dependent assemblies are recorded in the assembly's manifest. The default version policy for the runtime is that applications run only with the versions they were built and tested with, unless overridden by explicit version policy in configuration files (the application configuration file, the publisher policy file, and the computer's administrator configuration file).

The runtime performs several steps to resolve an assembly binding request:

1. Checks the original assembly reference to determine the version of the assembly to be bound.

2. Checks for all applicable configuration files to apply version policy.

3. Determines the correct assembly from the original assembly reference and any redirection specified in the configuration files, and determines the version that should be bound to the calling assembly.

4. Checks the global assembly cache, codebases specified in configuration files, and then checks the application’s directory and subdirectories

Version Information
Each assembly has two distinct ways of expressing version information:

The assembly's version number, which, together with the assembly name and culture information, is part of the assembly's identity. This number is used by the runtime to enforce version policy and plays a key part in the type resolution process at run time.

An informational version, which is a string that represents additional version information included for informational purposes only. Assembly manifest stored this information.

Tuesday, June 24, 2008

Methods to generate random number in SQL Server

There are many methods to generate random number in SQL Server.


--Method 1 : Generate Random Numbers (Int) between Range
-- Create the variables for the random number generation
DECLARE @Random INT
DECLARE @Upper INT
DECLARE @Lower INT
-- This will create a random number between 1 and 999
SET @Lower = 1 -- The lowest random number
SET @Upper = 999 -- The highest random number
SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
SELECT @Random

--Method 2 : Generate Random Float Numbers
SELECT RAND( (DATEPART(mm, GETDATE()) * 100000 )+ (DATEPART(ss, GETDATE()) * 1000 )+ DATEPART(ms, GETDATE()) )

--Method 3 : Random Numbers Quick Scripts

-- random float from 0 up to 20 - [0, 20]
SELECT 20*RAND()
-- random float from 10 up to 30 - [10, 30]
SELECT 10 + (30-10)*RAND()
--random integer BETWEEN 0 AND 20 - [0, 20]
SELECT CONVERT(INT, (20+1)*RAND())
--random integer BETWEEN 10 AND 30 - [10, 30]
SELECT 10 + CONVERT(INT, (30-10+1)*RAND())

--Method 4 : Random Numbers (Float, Int) Tables Based with Time

DECLARE @t TABLE( randnum float )
DECLARE @cnt INT
SET @cnt = 0
WHILE @cnt <=10000
BEGIN
SET @cnt = @cnt + 1
INSERT INTO @tSELECT RAND( (DATEPART(mm, GETDATE()) * 100000 )+ (DATEPART(ss, GETDATE()) * 1000 )+ DATEPART(ms, GETDATE()) )
END

SELECT randnum, COUNT(*)FROM @t GROUP BY randnum

--Method 5 : Random number on a per row basis
--The distribution is pretty good however there are the occasional peaks.
--If you want to change the range of values just change the 1000 to the maximum
--value you want. Use this as the source of a report server report and chart the
--results to see the distribution

SELECT randomNumber, COUNT(1) countOfRandomNumber FROM (SELECT ABS(CAST(NEWID() AS binary(6)) %1000) + 1 randomNumberFROM sysobjects) sample GROUP BY randomNumber ORDER BY randomNumber

How to select records randomely from the SQL Server table.

There are many times when we need to select some records randomely from the SQL Server table.

For that purpose there are many ways that can be utilized for the same. they're especially effective when you wish to add dynamism to a site. For instance, you could randomly select a product to present as Today's Featured Product, or QA could generate a random call list to gauge customer satisfaction levels.

But the snag is that SQL doesn't permit the selection of random rows. then howe to do that ?
But you don't need to worry becaues the good news is that there's a simple trick to getting this functionality to work in SQL.

The solution is based on the uniqueidentifier data type. Unique identifiers, popularily known as Guaranteed Unique Identifiers (GUIDs), look something like this:

4C34AA46-2A5A-4F8C-897F-02354728C7B0

SQL Server uses GUIDs in many contexts, perhaps most notably in replication. You can use them when normal incrementing identity columns won't provide a sufficient range of keys. To do this, you create a column of type uniqueidentifier whose default value is NewID(), something like this:

CREATE TABLE MyNewTable
(
PK uniqueidentifier NOT NULL DEFAULT NewID(),
AnotherColumn varchar(50) NOT NULL,
. . .

This function is just the ticket to solve our random rows problem. We can simply call NewID() as a virtual column in our query, like this:

Select top , NEWID() AS RANDOM from TABLE order by RANDOM

you can now get the number of records selected randomly.

and that's what we want .

so cheers ....

Tuesday, June 10, 2008

How do we can format money or decimal with commas?

Sometimes we want to have our money fields properly formatted with commas like this: 12,345,678.9999

For the same purpose we can use the CONVERT function and give a value between 0 and 2 to the style and the format will be displayed based on that style selection

Here is an example:

DECLARE @value MONEYSELECT @v = 12345678.6666
SELECT CONVERT(VARCHAR,@value ,0) --12345678.67 value is Rounded but no formatting is done
SELECT CONVERT(VARCHAR,@value ,1) --12,345,678.67 Formatted with commas
SELECT CONVERT(VARCHAR,@value ,2) --12345678.6666 No formatting

Now If we have a decimal field it doesn't work with the convert function. The work around in this case is to convert it to money and then follow the above method.

For example:

DECLARE @TargetValue DECIMAL (36,10)
SELECT @TargetValue = 12345678.6666
SELECT CONVERT(VARCHAR,CONVERT(MONEY,@TargetValue ),1) --12,345,678.67 Formatted with commas

how to remove time component from a datetime value

What if I want to remove the time component from a datetime value ?

That is to say I want 2008-04-18 00:00:00.000 intead of 2008-04-18 13:46:57.983

Now since values with the datetime data type are stored internally by the SQL Server 2005 Database Engine as two 4-byte integers. The first 4 bytes store the number of days before or after the base date: January 1, 1900. The base date is the system reference date. The other 4 bytes store the time of day represented as the number of 1/300-second units after midnight.
reference : http://msdn2.microsoft.com/en-us/library/ms187819.aspx

so the simplest way of doing this I found is :

SELECT CONVERT(DATETIME,CONVERT(INT,datetimevalue))