Saturday, November 29, 2008

The type initializer threw an exception

Can not see the Form in the Designer. "The type initializer threw an exception." error
I got a problem recently when one of the forms I created could not be opened in Designer. Error message was as brief as "The type initializer for "..." threw an exception.". I found a good advice from Microsoft Developer Support guy Keith Fink how to debug the problem here.
Here is the advice:
Usually this means that your constructor of a particular type is throwing an exception. One way to debug this is to use aseparate instance of Devenv.exe and attach to the instance where yourproject is open, and then open the inherited form that causes the problem.

In the instance of Devenv.exe that you are using to debug with, followthese steps.

1. Start Devenv.exe.2. Select Tools->Debug Processes.3. Select the other instance of Devenv (where your project is loaded), andclick Attach.4. Make sure to select Common Language Runtime, and uncheck Nativedebugging, and click OK.5. Click Close.6. Select Debug->Exceptions.7. Expand Common Language Runtime Exceptions->System.8. Select the System.TypeInitializationException.9. Under the "When the exception is thrown" section, select the "Break intothe debugger" option, and click OK.10. Switch over to the other instance of Devenv, and open the form so thatthe exception is thrown. When that happens the first instance of Devenvshould break on the line of code where the exception is thrown.

One more hint - in the Form code DesignMode property is useful (it'll tell you if your Form is loaded in designer).
Note that the DesignMode property should not be checked from within the constructor or from any code that the constructor calls. A constructor is called before a control is sited, and it's the site that determines whether or not a control is in design mode. DesignMode will also be false in the constructor. I personally like to put it into Form_Load event (Form_FormClosing if you want to do something like logging on form close).
Example:
...
if(!this.DesignMode)
{
// chek authentication or something else
}

And finally a good article about
Design-time integration of controls.

10 Articles you should Read

10 .Dot net articels you should READ
Multi-Lingual Language Translations for ASP.NET
Here are a few free (paid for by me) language translations of common software terms for use in your multi-lingual ASP.NET application. This is particularly helpful if you want to create a list of available languages in Spanish, German, Chinese, etc... The language translation spreadsheet has generic term translations for Spanish, English, German, Italian, French, Chinese-Simple, and Japanese. The language name translations also includes Dutch, Korean, and Russian.
Dependency Injection using Spring.NET
Spring.NET is one of the popular open source framework ported from Java platform. It offers lot of functionality and in this article I will discuss about Dependency Injection and how it is supported in Spring.NET
Obfuscation and Packaging of .NET Applications via Compressed Embedded Assemblies
Shows a technique for embedding all the assemblies for an application as compressed, embedded resources into a single stub loader executable, extracting, decompressing and loading into the AppDomain at startup.
WPF & PowerShell - Part 7 (Sharing Hosts)
Well here we are at the end of a week of WPF. We've learned how to create basic, simple user interactive interfaces. We've seen a brief glimmer of the golden UI layer that is WPF, and have seen how we can use PowerShell to add easy interactivity to XAML. You've seen tricks to help you work your way through .NET code, and help you unwrap the mysteries of WPF. We've seen how we can use PowerShell's list processing technology allows for simple binding to WPF's controls, and how WPF applets can help you present a simple front ends to PowerShell functionality. We've gotten a very brief taste of what the pipeline can bring to User interfaces, and we've showed you how to make controls that run in the background so you can build your control in PowerShell and still use PowerShell.
Patterns in Practice - The Open Closed Principle
This is the first installment of a new MSDN® Magazine column on software design fundamentals. My marching orders are to discuss design patterns and principles in a manner that isn't bound to a specific tool or lifecycle methodology. In other words, my plan is to talk about the bedrock knowledge that can lead you to better designs in any technology or project.I'd like to start with a discussion of the Open Closed Principle and other related ideas popularized by Robert C. Martin in his book, Agile Software Development, Principles, Patterns, and Practices. Don't be turned off by the word "agile" in the title, because this is all about striving for good software designs.
How to Find Memory Leaks With CLRProfiler
We all know managed code can have memory leaks. You can find a good example here: A .NET memory leak you did not think about. Microsoft provides us with the CLR Profiler, an open source tool for analyzing the behavior of your managed application, which you can download here. It contains very good documentation about the different functions of the tool, however I still find it a bit hard to start with, so here is a simple step-by-step example of how to use it.
Animation in-depth with Silverlight 2.0 Beta - Part Four
In this example I'll show you how animations can be performed using a VideoBrush. This is one of the examples that attracts the users attention by completing the animation at the right time. The video will be clipped and rotated during the animation.
IronRuby on Rails. Microsoft makes it happen.
Now... No more doubts about Open Source Support by Microsoft. The first ever Open Source Project comes live now.
Mr. John Lam, the person behind IronRuby has provided more information on his blog here...
http://www.iunknown.com/2008/05/ironruby-and-rails.html Here are the Highlights of his blog.
Optimization Tips: Using HTTP Compression
I know it has been a few weeks since the last installment in this series, and with TechEd on the horizon it'll probably be a couple 'til the next, but as long as there is some time in between let's explore another area of performance optimization with the RadControls for ASP.NET AJAX. This week, we're going to take a look at HTTP compression and how this simple technique can deliver a valuable performance boost to your website.
ASP.NET Memory: Thou shalt not store UI objects in cache or session scope
Surprisingly the issue I wrote about in "the eventhandlers that made the memory baloon" (Jan 2006) is something that still happens very frequently, I reference it in cases at least a few times a month. Just this last week I had different variations of it crop up in different cases so in this post I will show a different variation, what to look out for and how to identify it.

Using enum in .net

Using a Enum in C#.net
Code Sample
// declaring a enum
enum Operations
{
add,sub,mul,div
};


public void mymethod()
{
// creating object of enum
Operations op ;

// assinging value to enum
op = Operations.add ;

// using it to compare
if(op== Operations.add)
{
// do somethng.. addition
}

}

Friday, November 28, 2008

Dataset vs Business Entities

Introduction
This days creating a layered architectured applications is common and widely used. A distributed application always need to send data from one layer to another. If you are an .Net developer and you've come to a cross roads of sorts in development over which object model to go with. thier are multiple options available but the formal and first question we need to ask ourselves is what are we going to do with our data. the best two options available are using dataset or create business entities which will hold data. using dataset also gives as option of selecting a untyped dataset or typed dataset.
Before selecting a data tier component following are the point which we must keep in mind
  • 1) use of application(internal or external)
  • 2) deadline of the application
  • 3) development efforts(resources required)
  • 4) Architectural design of application
  • 5) how future changes will be implmented

thier may be many other scenarios which must be taken on consideration. let us see what this option are and how are they achieved.

Dataset

DataSet are not particularly optimized when you serialize them with either XmlSerializer or Formatters runtime serialization, at least until the release of .NET Framework 2.0...
By default XmlSerialization of DataSets is a little bit fat J, because of its Schema, Data and DiffGram representation. To tell the true we can refine XmlSerialization of DataSet implementing IXmlSerializable interface in custom DataSet or typed DataSet.
On the other side re-implementing IXmlSerialization is not always trivial and sometime it’s simply too expensive if compared to the goal we’d like to achieve.
In order to use a DataSet inside the presentation layer, we need to have knowledge about data structures (i.e. tables, columns and rows hosted by the DataSet), so we don’t have real abstraction from the data layer.
Anyway a DataSet makes easier to develop data binding code not only in ASP.NET but above all in Windows Forms apps.
From a Web Service point of view a DataSet fights with SOA, with WS-I BP1 and with any other kind of SOAP node that’s not .NET based.

Typed DataSet

the diffrence here in typed dataset is that we define the structure of the data at design time which gives us a more abstract way of representing data. Typed dataset is type safe and provides us compile time error rather than runtime.

Advantages of using typed dataset

· The readability of our code increases.
· It gives compile time error for datatype mismatch.
· With Visual Studio 2005 you will get the intellisense support for tables and columns.

Business entities

Creating a business entities requires more effort and development time, but it has less overhead in terms of memory and performance. Custom entities are slim and effiecent way of passing data. the over head here is to create custom classes and implementing serialization mechanism. Relation of the data also must be implemented seperately. A future change also need to be take care as all the business entities class should be changed.

When new requirement must be handled,

Fastest Development Time :- Typed Dataset

Requires Custom Programming for filter and sort :- Business Entity

Requires Re-deploying Client To Add New Column :- Typed Dataset,Business Entity

Requires Re-deploying Service To Add New Column :- Dataset,Typed Dataset,Business Entity

Heaviest Payload: - Dataset

Conclusion

The best approach a developer can take when it comes to Datasets vs the entity argument is take a holistic approach at the problem that he or she is trying to be solve. Don't forget to take into account future changes and how much maintenance may be required. Use common sense and match the best solution to the problem. I hope this helps and is now officially clear as mud.

Strong Naming Assembly


Any code you have that uses this assembly, will need to be recompiled with a reference to the new assembly with the newer version.
Strong named assemblies can only reference other strong named assemblies.
If your product includes many assemblies (.NET DLL’s) and you want to ship only one of them as a hotfix, you will not be able to because your other assemblies will still refer to old version of the DLL. So either restrict to the same old version or use the .Net Framework configuration tool to forward the old version to the new version.
If you have classes that need to be serialized, the engine includes type information in the serialized data, that way it can be reconstituted later. If you the AssemblyFormat property is not set correctly, you could end up with a situation here you have stored some data, upgraded your application (maybe because of a bug fix), and then error when you try to load your serialized database (even though nothing in that particular class has changed).
Unless your assemblies need to be placed in the GAC, or run as COM+ component, or some other special case,strong-naming them probably is not necessary.
A strong name consists of the assembly’s identity—its simple text name, version number, and culture information (if provided)—plus a public key and a digital signature. It is generated from an assembly file using the corresponding private key. (The assembly file contains the assembly manifest, which contains the names and hashes of all the files that make up the assembly.)

Security Note: A strong-named assembly can only use types from other strong-named assemblies. Otherwise, the security is already compromised.
It’s pretty easy using Visual Studio .net 2005 IDE, but we will also talk about alternatives later.
Go to “Property Pages” of your project from the Solution Explorer.
Select the “Signing” Tab from the list of tabs on the left.
Select the check-box “Sign the Assembly”.
Select “New…” from “Choose a strong name key file” drop-down list.
Just finish the dialog by providing strong name key filename(new) and password(optional).
There you go!!
Alright, other alternatives are also mentioned here.
First of all, we need a cryptographic key pair to sign an assembly with a strong name.
This public and private cryptographic key pair is used during compilation to create a strong-named assembly. Microsoft has provided Strong Name Tool (sn.exe) to create this key pair in a file with “.snk” extension.
Open the command prompt and type the following command,
sn -k //e.g. sn -k mySgnKey.snk will create a keypair file named mySgnKey.snk
Delay Signing an Assembly:
If you intend to delay sign an assembly and you control the whole key pair (which is unlikely outside test scenarios), you can use the following commands to generate a key pair and then extract the public key from it into a separate file.
First Command: sn -k mySgnKey.snk
Second Command: sn -p mySgnKey.snk publicSgnKey.snk
Sign an Assembly with a Strong Name using Assembly Linker
al /out: /keyfile:
In this command, assembly name is the name of the assembly to sign with a strong name, module name is the name of the code module used to create the assembly, and file name is the name of the container or file that contains the key pair.
al /out:MyAssembly.dll Project.Module /keyfile:mySgnKey.snk
Signing an Assembly with a Strong Name using Assembly Attributes
C# usage: [assembly:AssemblyKeyFileAttribute(@"sgKey.snk")]
VB usage:
Note: When signing an assembly with a strong name, the Assembly Linker (Al.exe) looks for the key file relative to the current directory and to the output directory. When using command-line compilers, you can simply copy the key to the current directory containing your code modules.
How To Reference This Strongly Named Assembly
/reference:
In this command, compiler command is the compiler command for the language you are using, and assembly name is the name of the strong-named assembly being referenced. You can also use other compiler options, such as the /t:library option for creating a library assembly.
The following example creates an assembly called myAssembly.dll that references a strong-named assembly called myLibAssembly.dll from a code module called myAssembly.cs.
csc /t:library MyAssembly.cs /reference:MyProjectAssembly.dll
How To Make a Run-time Reference to this Strongly Named Assembly
We need to use the name of the assembly in following manner…
, , ,
C#usage: Assembly.Load(”myAssemby,Version=1.0.0.1,Culture=neutral,PublicKeyToken=7b53aa32d4fc18b1″);
VB usage: Assembly.Load(”myAssemby,Version=1.0.0.1,Culture=neutral,PublicKeyToken=7b53aa32d4fc18b1″)


Wednesday, November 26, 2008

Calling a JavaScript function from ASP.NET

Calling a JavaScript funtion from ASP.NET
Requirement :
Calling a javascript function which return strings and binding it to textbox of asp.net page
For e.g . You have a javascript function say
MyJavaScript() whichs return string, on click of button you need to call javascript function and
bind the returned value to textbox.

Code Snippet
function MyJavaScript()
{
return 'Text from JavaScript';
}

asp:TextBox ID="mytxtBox" runat="server"

asp:btn ID="myButton" runat="server"
Text="Click to Get Value"
OnClientClick ="document।getElementById('mytxtBox').value= MyJavaScript()"
/asp:btn
Output

Monday, November 24, 2008

Animating a Windows Form

Requirment

To animate a windows form while displaying it to user , just like a powerpoint slides effects.

Solution

To get such powerpoint slides effect can be achieved using Win32 API . the only problem here is that its unmanged code.

Note : sample code below is in C#

1) Add a reference to you class file
using System.Runtime.InteropServices;

2) import user32 dll with following syntax
[DllImport("User32.dll")]
static extern bool AnimateWindow(System.IntPtr handle, int time, int value);

3) call AnimateWindow function at windows form load event


Arguments
1) Handler(this. handle) of form(to be animated)
2) time(in milliseconds) to specify how much time animation will take (faster or slower)
3) values(in hexadecimal ) which specify how the form will be displayed (left to right, right to left, top to bottom, bottom to top or center etc..)


The last values are or'd together and can be any of the following:

&O1 = Animate the window from left to right. This flag can be used with roll or slid eanimation It is ignored when used with the &H10 flag.

&H2 = Animate the window from right to left. This flag can be used with roll or slide animation. It is ignored when used with the &H10 flag.

&H4 = Animate the window from top to bottom. This flag can be used with roll or slide animation. It is ignored when used with the &H10flag.

&H8 = Animate the window from bottom to top. This flag can be used with roll or slide animation. It is ignored when used with the &H10flag.

&H10 = Makes the window appear to collapse inward if the &H10000 flagis used or expand outward if the &H10000 flag is not used.

&H10000 = Hides the window. By default, the window is shown.&H20000 = Activates the window. Do not use this flag with &H10000.

&H40000 = Uses slide animation. By default, roll animation is used. This flag is ignored when used with the &H10 flag.

&H80000 = Uses a fade effect. This flag can be used only if hwnd is a top-level window.

Reference site for .NET

Some useful and important forums reference sites

ASP.NET forums
www.forums.asp.net

VB Forums
www.vbdotnetforums.com/
www.a1vbcode.com/vbforums/

C#.NET forums
www.c-sharpcorner.com/
www.mastercsharp.com
www.csharphelp.com/
www.csharp-source.net/
www.developerfusion.com/

Sunday, November 23, 2008

.NET Framework

Microsoft has introduced .NET with the intention of bridging the gap in interoperability between applications. It is designed to make significant improvements in code-reuse, code-specialization, resource management, multi-
language development, security, deployment and administration.
Components of .NET Framework
.Net Framework base classes
.Net class library that works with any .net language such as VB.NET or C#. This class library is built on the object oriented nature of the runtime. It provides classes that can e used in code to accomplish common programming tasks.
Common Language Runtime (CLR)
The CLR is the most essential component of the .NET framework. As like java having its on runtime environment (JRE – java runtime environment), .Net having its own as CLR. Runtime environment basically provides path with which the program can be executed.

The CLR runtime provides functionalities, Such as:

Exception handling
Security
Debugging & Version support to any
language that supports it.

Features provided by CLR:
Automatic memory management
Standard type system
Language
interoperability
Platform independence
Security management
Type safety

Managed Code

The code that is developed with a language compiler that targets the CLR is called Managed Code

Unmanaged Code

The code that is developed without considering the convention and requirements of the CLR is called Unmanaged Code. Unmanaged code runs and executes in CLR with minimal services.For example: Unmanaged code may run with limited debugging and without garbage collection process.
Class LoaderClass loader loads the code in the memory.

Garbage Collection

The automatic memory management scheme employed by the .net framework is called Garbage Collection. The garbage collector continuously traces the out of scope objects in the background and identifies objects that no longer have references.Because the garbage collector is always running, you do not have to explicitly destroy the objects, it will automatically cleaned when you are finished working with them.You can also force the garbage collector to run using System.GC.Collect() method.