.NET Questions and Solutions

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries for January, 2011

INFO: Microsoft Application Blocks for .NET – Exception Management Application Block Overview

Symptoms
This article describes the Microsoft Application Blocks for .NET topic “Exception Management Application Block Overview.”
The Exception Management Application Block provides a simple, extensible framework for handling exceptions. Without affecting your application code, you can do the following: Log exception information to the event log by using only one line of application code.Extend the application block by creating your own components that log exception details to other data sources or notify operators.You can use the Exception Management Application Block as a building block in your .NET Framework-based application.
Resolution
“Exception Management Application Block Overview” contains the following sections: Introduction
The Exception Management Application Block is an exception management framework that you can use as a building block in your own .NET Framework-based application. If you use this block, you reduce the quantity of custom error handling code that you must create, test, and maintain. You may also make your application more robust and easier to debug.
The Exception Management Application Block helps you to do the following: Manage exceptions in an efficient and consistent way.Isolate exception management code from business logic code.Handle and log exceptions by using minimal custom code.What Does the Exception Management Application Block Include?
The Exception Management Application Block is made up of three Microsoft Visual Studio .NET projects, full source code, and comprehensive documentation.Downloading and Installing the Exception Management Application Block
A Microsoft Windows Installer file that contains the Exception Management Application Block projects, source code, and comprehensive documentation is available.
The install process creates a Microsoft Application Blocks for .NET menu on your Programs menu. An Exception Management menu appears on the Microsoft Application Blocks for .NET menu. The Exception Management menu includes options to start the documentation and to start the Exception Management Application Block Visual Studio .NET solution.Using the Exception Management Application Block
This section discusses how to use the basic features of the Exception Management Application Block. For additional information about these topics, and other related topics, see the documentation that is included with the Exception Management Application Block download.
The topics that this section discusses include: Publishing ExceptionsReferencing the Exception Management Application BlockConfiguring the Exception Manager Application Block
You control the behavior of the Exception Management Application Block by using the following standard .NET Framework-based XML application configuration files: Web.config (for an ASP.NET application)Appname.exe.config (for a Windows-based application)You can also apply configuration settings at the computer level by using the Machine.config file.Extending the Exception Management Application Block
You may be satisfied with the functionality of the default publisher. The default publisher writes exception details to the Windows event log. However, you may want to develop your own custom publishers to log exception details to alternative locations or to notify operators (possibly through Microsoft Windows Management Instrumentation [WMI]), that an exception has occurred. This section discusses how to extend the functionality of the Exception Management Application Block.Internal Design
This section discusses the main elements of the Exception Management Application Block. The main elements of the Exception Management Application Block are as follows: The BaseApplicationException classThe ExceptionManagerSectionHandler classThe ExceptionManager classThe ExceptionManagerInstaller classThe DefaultPublisher classThe IExceptionPublisher interfaceThe IExceptionXmlPublisher interface

How to use structured exception handling in Visual C# .NET and in Visual C# 2005 or Visual C# 2008

Symptoms
This article describes how to use structured exception handling in Microsoft Visual C# .NET, in Microsoft Visual C# 2005, or in Microsoft Visual C# 2008.

RequirementsThe following list outlines the recommended hardware, software, network infrastructure, and service packs that you need: Visual C# .NET or later versions of Visual C#
This article assumes that you are familiar with the following topics: Visual C# .NET or later versions of Visual C#Microsoft Visual Studio .NETor or later versions of Visual Studio
Structured Exception HandlingVisual C# .NET offers structured exception handling that provides a powerful and a more readable way to handle errors. Structured exception handling enables you to nest error handlers inside other error handlers that are in the same procedure. Structured exception handling uses a block syntax that is similar to the If…Else…End If statement. This makes Visual C# .NET code or code in later versionsof Visual C# more readable and easier to maintain. You can handle exceptions in Visual C# .NET or in later versions Visual C# by using a combination of exception handling statements:trycatchfinallythrow The basic syntax of structured error handling is as follows:

try{// Code that is expected to raise an exception.}catch(Exception e){// Code that can handle an error.}finally{// Code to do any final cleanup.}You can include any valid Visual C# code in the try block, or you can include another try block or another hierarchy of try blocks. When an exception occurs at any point, the common language runtime looks for the nearest try block that encloses this code and does not run any additional lines of code. The control is then passed to a matching catch block, if one exists, and to the associated finally block. You can also specify multiple catch statements so that each catch block handles a specific error.

Catch an ExceptionIn Microsoft Visual Studio.NET, click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET.
In Microsoft Visual Studio 2005, click Start, point to Programs, point toMicrosoft Visual Studio 2005, and then click Microsoft Visual Studio 2005.
In Microsoft Visual Studio 2008, click Start, point to Programs, point toMicrosoft Visual Studio 2008, and then click Microsoft Visual Studio 2008..On the File menu, point to New, and then click Project.In the New Project dialog box, follow these steps: Under Project Types, click Visual C# Projects.
Note In Visual Studio 2005 or in Visual Studio 2008, click Visual C# under Project Types.Under Templates, click Console Application.In the Name box, type MyConsoleApp.In the Location box, type C:\, and then click OK.Add the following code in the Main() function:

int a = 0; int b = 10; int c = 0; try { a = b / c; } catch (Exception e) { Console.WriteLine(“A run-time error occurred.”); } finally { Console.ReadLine(); }To run the application, click Start on the Debug menu. The code tries to divide a number by 0. This operation is not valid and causes a divide-by-zero error. However, the catch block catches this error, and the Console window displays the following error message:

A run-time error occurredClose the Console window.
Catch Multiple ExceptionsThis section demonstrates how to use multiple catch statements to handle different errors. Open the Console Application project that you created in the “Catch an Exception” section of this article. Replace the existing code in the Main() function with the following code:

int a = 2147483647; int b = 0; int c = 0; try { a = checked(a + 1); } catch (DivideByZeroException e) { Console.WriteLine(“Error: Divide by Zero”, e.Message); } catch (OverflowException e) { Console.WriteLine(“Error: Overflow”, e.Message); } finally { Console.ReadLine(); }This code includes two catch blocks:One catch block catches the previous divide-by-zero error.One catch block catches the new overflow error.To run the application, click Start on the Debug menu. The Console window displays the following error message:

Error: OverflowClose the Console window.Because you cannot always anticipate every error that may occur, you can add a catch block for all exceptions that you cannot anticipate. For example, add the following code before the finally statement to catch any errors that you cannot anticipate andto display the appropriate error message:

catch (Exception e) { Console.WriteLine(“Error: “, e.Message); }On the File menu, click Close Solution.
Throw an ExceptionStructured exception handling uses the catch statement to catch an exception. With structured exception handling, you can also throw an exception. For example, you may find it useful to throw an exception when you perform data validation inside a Property Set procedure, because you may want to throw an error if a business rule is violated. In Microsoft Visual Studio.NET, click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET.
In Microsoft Visual Studio 2005, click Start, point to Programs, point toMicrosoft Visual Studio 2005, and then click Microsoft Visual Studio 2005.
In Microsoft Visual Studio 2008, click Start, point to Programs, point toMicrosoft Visual Studio 2008, and then click Microsoft Visual Studio 2008..On the File menu, point to New, and then click Project.In the New Project dialog box, follow these steps: Under Project Types, click Visual C# Projects.
Note In Visual Studio 2005 or in Visual Studio 2008, click Visual C# under Project Types.Under Templates, click Console Application.In the Name box, type MyNewConsoleApp.In the Location box, type C:\, and then click OK.On the Project menu, click Add Class.In the Add New Item dialog box, type clsPerson.cs in the Name box, and then click Open.
Note In Visual Studio 2005 or in Visual Studio 2008, click Add.Add the following code in the clsPerson class:

public clsPerson() { } private int mintAge; public int Value; public int Age { get { Age = mintAge; return Age; } set { if(Value > 0) mintAge = Value; else throw new ArgumentException(“Age cannot be negative.”); } }This code creates an Age property. Because a person cannot have a negative age, an error is raised if the user of the class tries to set the Age property to a number that is less than 0. In the Main() function of Class1.cs, add the following code:

clsPerson p = new clsPerson(); try { p.Age = -1; } catch (Exception e) { Console.WriteLine(e.Message); } finally { Console.ReadLine(); }To run the application, click Start on the Debug menu. The Console window displays the following error message:

Age cannot be negativeClose the Console window.
Complete Code ListingCatch an Exception

using System;namespace MyConsoleApp{ class Class1 { [STAThread]static void Main(string[] args) { int a = 0; int b = 0; int c = 0; try { a = b / c; } catch (Exception e) { Console.WriteLine(“A run-time error occurred.”); } finally { Console.ReadLine(); } }}}Catch Multiple Exceptions

using System;namespace MyConsoleApp{ class Class1 { [STAThread] static void Main(string[] args) { int a = 2147483647; try { a = checked(a + 1); } catch (DivideByZeroException e) { Console.WriteLine(“Error: Divide by Zero”, e.Message); } catch (OverflowException e) { Console.WriteLine(“Error: Overflow”, e.Message); } catch (Exception e) { Console.WriteLine(“Error: “, e.Message); } finally { Console.ReadLine(); } } }}Throw an Exception

using System;namespace MyNewConsoleApp{ class Class1 { [STAThread] static void Main(string[] args) { clsPerson p = new clsPerson(); try { p.Age = -1; } catch (Exception e) { Console.WriteLine(e.Message); } finally { Console.ReadLine(); } } }public class clsPerson { public clsPerson() { } private int mintAge; public int Value; public int Age { get { Age = mintAge; return Age; } set { if(Value > 0) mintAge = Value; else throw new ArgumentException(“Age cannot be negative.”); } } }}

How to troubleshoot a memory leak or an out-of-memory exception in the BizTalk Server process

Symptoms
Memory leaks are a common issue. You may have to try several steps to find the specific cause of a memory leak or an out-of-memory (OOM) exception in Microsoft BizTalk Server. This article discusses important things to consider when you are evaluating memory usage and possible memory-related issues. These considerations include the following:
Physical RAM
Large message processing
Use of the /3GB switch
Use of custom components
Which version of the Microsoft .NET Framework the system is running
The number of processors
Resolution
This article describes how to troubleshoot a memory leak or an out-of-memory exception in the BizTalk Server process of Microsoft BizTalk Server.

How to enable SQL Server connectivity on Windows XP Service Pack 2

Symptoms
This article describes how to enable SQL Server connectivity on Windows XP Service Pack 2.
By default, Windows Firewall is enabled on computers that are running Microsoft Windows XP Service Pack 2. Windows Firewall closes ports such as 445 that are used for file and printer sharing to prevent Internet computers from connecting to file and print shares on your computer or to other resources. When SQL Server is configured to listen for incoming client connections by using named pipes over a NetBIOS session, SQL Server communicates over TCP ports and these ports must be open. SQL Server clients that are trying to connect to SQL Server will be not be able to connect until SQL Server is set as an exception in Windows Firewall. To set SQL Server as an exception in Windows Firewall, use the steps that are listed in the “More Information” section.
Resolution
Create an exception for each instance of SQL Server The following method will open User Datagram Protocol (UDP) port 1434 in addition to the Transmission Control Protocol (TCP) port. If you want to open these ports manually, see the following article in the Microsoft Knowledge Base:
841252?(http://support.microsoft.com/kb/841252/) How to manually enable TCP/IP on Windows XP Service Pack 2 for SQL Server 2000
Note If you are running multiple instances of SQL Server, you will have to create an exception for each instance. Click Start, and then click Run. In the Run dialog box, type Firewall.cpl, and then click OK.In the Windows Firewall dialog box, click Add a Program on the Exceptions tab.In the Add Program dialog box, you can select an instance of SQL Server or you can click the Browse button to locate the instance of SQL Server that you want to add to the exception list. The default installation locations for SQL Server are listed in the following table.

Collapse this tableExpand this table
VersionFile pathSQL Server 7.0 Mssql\Binn\Sqlservr.exeSQL Server 2000 Default InstanceProgram Files\Microsoft SQL Server\Mssql\Binn\Sqlservr.exeSQL Server 2000 Named InstanceProgram Files\Microsoft SQL Server\Mssql$instancename\Binn\Sqlservr.exeSQL Server 2005 Default InstanceProgram Files\Microsoft SQL Server\MSSQL.x\MSSQL\Binn\sqlservr.exeSQL Server 2005 Named InstanceProgram Files\Microsoft SQL Server\MSSQL.x\MSSQL\Binn\sqlservr.exe
Note Each SQL Server 2005 instance is made up of a distinct set of services with specific settings for collations and other options. The directory structure, registry structure, and service names all reflect the specific instance ID of the SQL Server instance that is created during SQL Server 2005 Setup. x is the instance ID of the SQL Server instance that is created during SQL Server 2005 Setup.Select the name of the instance, and then click OK.Under Programs and Services, select the check box that is next to the name you selected in step 6, and then click OK. How to use Multiprotocol Remote Procedure Call (RPC)If you are using Multiprotocol, you must perform the steps in the “Create an exception for each instance of SQL Server” section as well as open the correct TCP ports on Windows Firewall.How to run RPC over TCPWarning Serious problems might occur if you modify the registry incorrectly by using Registry Editor or by using another method. These problems might require that you reinstall your operating system. Microsoft cannot guarantee that these problems can be solved. Modify the registry at your own risk.
To run RPC over TCP, follow these steps:Enable port 135 on Windows Firewall. To do this, follow these steps: Click Start, and then click Run.In the Run dialog box, type Firewall.cpl, and then click OK.On the Exceptions tab, click Add Port. In the Port number box, type 135, and then click the TCP button.In the Name box, type a name for the port such as MULTI, and then click OK.On the Exceptions tab, you will see the new service. To enable the port, click to select the check box next to your new service, and then click OK.Modify the \\HKLM\SOFTWARE\Policies\Microsoft\Windows NT\RPC registry key.
Note If you have just installed SQL Server, this registry key does not exist. You will have to create the key and set the value. To do this, follow these steps: Click Start, and then click Run.In the Run dialog box, type Regedit, and then click OK. This will start Registry Editor.Locate the \\HKLM\SOFTWARE\Policies\Microsoft\Windows NT\RPC Registry key.Set the RestrictRemoteClients key to 0. Quit Registry EditorRestart the computer that is running SQL Server.How to use RPC over Named PipesIf you are running RPC over Named Pipes, you must open port 445 on Windows Firewall. To do this, follow these steps: Click Start, and then click Run.In the Run dialog box, type Firewall.cpl, and then click OK.On the Exceptions tab, click Add Port. In the Port number box, type 445, and then click the TCP button.In the Name box, type a name for the port such as MULTI, and then click OK.On the Exceptions tab, you will see the new service. To enable the port, click to select the check box next to your new service, and then click OK.

How the Windows Firewall exception settings in the Group Policy administrative template work together with the Windows Firewall Control Panel program in Windows Vista

Symptoms
This article describes how the Windows Firewall exception settings in the Group Policy administrative template work together with the Windows Firewall Control Panel program in Windows Vista.
Resolution
Group Policy settingsYou can configure the Windows Firewall settings in the Group Policy administrative template and then apply the settings to a Windows Vista-based computer. The settings that you use to configure exceptions appear on the Exceptions tab in the Windows Firewall Control Panel program. When you enable a setting in the Group Policy administrative template, the setting generates an enabled firewall rule that has the “Allow” action. When you disable a setting, this action generates an enabled firewall rule that has the “Block” action.
Windows Firewall Control Panel program settingsIf you enable or disable an exception by using the settings in Group Policy, the check box for the exception entry is selected in the Windows Firewall Control Panel program. A selected check box indicates only that some action has been taken in that exception. The selection does not indicate what specific action is configured in the exception. The selected check box could indicate any of the following settings:Windows Firewall: Allow inbound file and printer sharing exception Windows Firewall: Allow inbound remote administration exception Windows Firewall: Allow inbound Remote Desktop exception Windows Firewall: Allow inbound UPnP framework exceptions Windows Firewall: Allow ICMP exceptions
Full exception settingsTo view the full exception settings, use the “Windows Firewall with Advanced Security” snap-in. This snap-in is available in the Administrative Tools folder.

FIX: You receive exception error messages when you use the StreamWriter.Flush () method or the StreamWriter.Close () method to access a file on a disk that has insufficient space in .NET Framework 1.1

Symptoms
On a computer that is running Microsoft .NET Framework 1.1, when you use the StreamWriter.Flush() method or the StreamWriter.Close() method to access a file on a disk that has insufficient space, you receive the following exception error message:

System.IO.IOException: There is not enough space on the disk.After you free up space on the disk and then try to access the file again, you receive the following exception error message:

System.IO.IOException: The process cannot access the file “C:\outputTest.txt” because it is being used by another process.
Resolution
This problem occurs if the common language runtime (CLR) does not close the file handle after you receive the first exception error message. If the file handle does not close, you cannot access the file regardless of how much space is on the disk.