Showing posts with label DOTNET. Show all posts
Showing posts with label DOTNET. Show all posts

What's New in the .NET Framework 4 ?

0 comments
This topic contains information about key features and improvements in the .NET Framework version 4. This topic does not provide comprehensive information about all new features and is subject to change.

The .NET Framework 4 introduces an improved security model. For more information, see Security Changes in the .NET Framework 4.

Other new features and improvements in the .NET Framework 4 are described in the following sections:

    *      Application Compatibility and Deployment
  

     *  Core New Features and Improvements
   

    *   Managed Extensibility Framework
  

      *  Parallel Computing
  

    *   Networking
  

     *  Web
   

     *  Client
   

     *  Data
   

     *  Windows Communication Foundation
 

       *  Windows Workflow Foundation

See New Types and Members in the .NET Framework 4 for lists of new namespaces, new types, and new members added to existing types.
Application Compatibility and Deployment

The .NET Framework 4 is highly compatible with applications that are built with earlier .NET Framework versions, except for some changes that were made to improve security, standards compliance, correctness, reliability, and performance.

The .NET Framework 4 does not automatically use its version of the common language runtime to run applications that are built with earlier versions of the .NET Framework. To run older applications with .NET Framework 4, you must compile your application with the target .NET Framework version specified in the properties for your project in Visual Studio, or you can specify the supported runtime with the <supportedRuntime> Element in an application configuration file.

If your application or component does not work after .NET Framework 4 is installed, please submit a bug on the Microsoft Connect Web site. You can test compatibility as described in the .NET Framework 4 Application Compatibility topic and learn about new features by using the Visual Studio 2010 and .NET Framework 4 Walkthroughs.

For guidance about migrating to the .NET Framework 4, see Migration Guide to the .NET Framework 4 and Version Compatibility in the .NET Framework

The following sections describe deployment improvements.
Client Profile

The .NET Framework 4 Client Profile supports more platforms than in previous versions and provides a fast deployment experience for your applications. Several new project templates now target the Client Profile by default. For more information, see .NET Framework Client Profile.
In-Process Side-by-Side Execution

This feature enables an application to load and start multiple versions of the .NET Framework in the same process. For example, you can run applications that load add-ins (or components) that are based on the .NET Framework 2.0 SP1 and add-ins that are based on the .NET Framework 4 in the same process. Older components continue to use the older .NET Framework version, and new components use the new .NET Framework version. For more information, see In-Process Side-by-Side Execution.


Core New Features and Improvements

The following sections describe new features and improvements provided by the common language runtime and the base class libraries.
Diagnostics and Performance

Earlier versions of the .NET Framework provided no way to determine whether a particular application domain was affecting other application domains, because the operating system APIs and tools, such as the Windows Task Manager, were precise only to the process level. Starting with the .NET Framework 4, you can get processor usage and memory usage estimates per application domain.

You can monitor CPU and memory usage of individual application domains. Application domain resource monitoring is available through the managed and native hosting APIs and event tracing for Windows (ETW). When this feature has been enabled, it collects statistics on all application domains in the process for the life of the process. See the new AppDomain.MonitoringIsEnabled property.

You can now access the ETW events for diagnostic purposes to improve performance. For more information, see CLR ETW Events and Controlling .NET Framework Logging. Also see Performance Counters and In-Process Side-By-Side Applications.

The System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute attribute enables managed code to handle exceptions that indicate corrupted process state.
Globalization

The .NET Framework 4 provides new neutral and specific cultures, updated property values, improvements in string handling, and other improvements. For more information, see What's New in Globalization and Localization.
Garbage Collection

The .NET Framework 4 provides background garbage collection. This feature replaces concurrent garbage collection in previous versions and provides better performance. For more information, see Fundamentals of Garbage Collection.
Code Contracts

Code contracts let you specify contractual information that is not represented by a method's or type's signature alone. The new System.Diagnostics.Contracts namespace contains classes that provide a language-neutral way to express coding assumptions in the form of preconditions, postconditions, and object invariants. The contracts improve testing with run-time checking, enable static contract verification, and support documentation generation. For more information, see Code Contracts.
Design-Time-Only Interop Assemblies

You no longer have to ship primary interop assemblies (PIAs) to deploy applications that interoperate with COM objects. In the .NET Framework 4, compilers can embed type information from interop assemblies, selecting only the types that an application (for example, an add-in) actually uses. Type safety is ensured by the common language runtime. See Using COM Types in Managed Code and Walkthrough: Embedding Type Information from Microsoft Office Assemblies (C# and Visual Basic).
Dynamic Language Runtime

The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework.

The expression trees are extended with new types that represent control flow, for example, System.Linq.Expressions.LoopExpression and System.Linq.Expressions.TryExpression. These new types are used by the dynamic language runtime (DLR) and not used by LINQ.

In addition, several new classes that support the .NET Framework infrastructure are added to the System.Runtime.CompilerServices namespace. For more information, see Dynamic Language Runtime Overview.
Covariance and Contravariance

Several generic interfaces and delegates now support covariance and contravariance. For more information, see Covariance and Contravariance in Generics.
BigInteger and Complex Numbers

The new System.Numerics.BigInteger structure is an arbitrary-precision integer data type that supports all the standard integer operations, including bit manipulation. It can be used from any .NET Framework language. In addition, some of the new .NET Framework languages (such as F# and IronPython) have built-in support for this structure.

The new System.Numerics.Complex structure represents a complex number that supports arithmetic and trigonometric operations with complex numbers.
Tuples

The .NET Framework 4 provides the System.Tuple class for creating tuple objects that contain structured data. It also provides generic tuple classes to support tuples that have from one to eight components (that is, singletons through octuples). To support tuple objects that have nine or more components, there is a generic tuple class with seven type parameters and an eighth parameter of any tuple type.
File System Enumeration Improvements

New file enumeration methods improve the performance of applications that access large file directories or that iterate through the lines in large files. For more information, see How to: Enumerate Directories and Files.
Memory-Mapped Files

The .NET Framework now supports memory-mapped files. You can use memory-mapped files to edit very large files and to create shared memory for interprocess communication.
64-Bit Operating Systems and Processes

You can identify 64-bit operating systems and processes with the Environment.Is64BitOperatingSystem and Environment.Is64BitProcess properties.

You can specify a 32-bit or 64-bit view of the registry with the Microsoft.Win32.RegistryView enumeration when you open base keys.
Other New Features

The following list describes additional new capabilities, improvements, and conveniences. Several of these are based on customer suggestions.

    *

      To support culture-sensitive formatting, the System.TimeSpan structure includes new overloads of the ToString, Parse, and TryParse methods, as well as new ParseExact and TryParseExact methods.
    *

      The new String.IsNullOrWhiteSpace method indicates whether a string is null, empty, or consists only of white-space characters. New overloads have been added to the String.Concat and String.Join methods that concatenate members of System.Collections.Generic.IEnumerable(Of T) collections.
    *

      The String.Concat method lets you concatenate each element in an enumerable collection without first converting the elements to strings.
    *

      Two new convenience methods are available: StringBuilder.Clear and Stopwatch.Restart.
    *

      The new Enum.HasFlag method determines whether one or more bit fields or flags are set in an enumeration value. The Enum.TryParse method returns a Boolean value that indicates whether a string or integer value could be successfully parsed.
    *

      The System.Environment.SpecialFolder enumeration contains several new folders.
    *

      You can now easily copy one stream into another with the CopyTo method in classes that inherit from the System.IO.Stream class.
    *

      New Path.Combine method overloads enable you to combine file paths.
    *

      The new System.IObservable(Of T) and System.IObserver(Of T) interfaces provide a generalized mechanism for push-based notifications.
    *

      The System.IntPtr and System.UIntPtr classes now include support for the addition and subtraction operators.
    *

      You can now enable lazy initialization for any custom type by wrapping the type inside a System.Lazy(Of T) class.
    *

      The new System.Collections.Generic.SortedSet(Of T) class provides a self-balancing tree that maintains data in sorted order after insertions, deletions, and searches. This class implements the new System.Collections.Generic.ISet(Of T) interface.
    *

      The compression algorithms for the System.IO.Compression.DeflateStream and System.IO.Compression.GZipStream classes have improved so that data that is already compressed is no longer inflated. Also, the 4-gigabyte size restriction for compressing streams has been removed.
    *

      The new Monitor.Enter(Object, Boolean) method overload takes a Boolean reference and atomically sets it to true only if the monitor is successfully entered.
    *

      You can use the Thread.Yield method to have the calling thread yield execution to another thread that is ready to run on the current processor.
    *

      The System.Guid structure now contains the TryParse and TryParseExact methods.
    *

      The new Microsoft.Win32.RegistryOptions enumeration lets you specify a volatile registry key that does not persist after the computer restarts.
    *

      Registry keys are no longer restricted to a maximum length of 255 characters.


Managed Extensibility Framework

The Managed Extensibility Framework (MEF) is a new library in the .NET Framework 4 that helps you build extensible and composable applications. MEF enables you to specify points where an application can be extended, to expose services to offer to other extensible applications and to create parts for consumption by extensible applications. It also enables easy discoverability of available parts based on metadata, without the need to load the assemblies for the parts. For more information, see Managed Extensibility Framework Overview and Managed Extensibility Framework. For a list of the MEF types, see the System.ComponentModel.Composition namespace.

Parallel Computing

The .NET Framework 4 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The new System.Threading.Tasks namespace and other related types support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax. For more information, see Parallel Programming in the .NET Framework.

Networking

Networking improvements include the following:

    *

      Security improvements for Windows authentication in several classes, including System.Net.HttpWebRequest, System.Net.HttpListener, System.Net.Mail.SmtpClient, System.Net.Security.SslStream, and System.Net.Security.NegotiateStream. Extended protection is available for applications on Windows 7 and Windows Server 2008 R2. For more information, see Integrated Windows Authentication with Extended Protection.
    *

      Support for Network Address Translation (NAT) traversal using IPv6 and Teredo. For more information, see NAT Traversal using IPv6 and Teredo.
    *

      New networking performance counters that provide information about HttpWebRequest objects. For more information, see Networking Performance Counters.
    *

      In the System.Net.HttpWebRequest class, support for using large byte range headers (64-bit ranges) with new overloads for the AddRange method. New properties on the System.Net.HttpWebRequest class allow an application to set many HTTP headers. You can use the Host property to set the Host header value in an HTTP request that is independent from the request URI.
    *

      Secure Sockets Layer (SSL) support for the System.Net.Mail.SmtpClient and related classes.
    *

      Improved support for mail headers in the System.Net.Mail.MailMessage class.
    *

      Support for a null cipher for use in encryption. You can specify the encryption policy by using the System.Net.ServicePointManager class and the EncryptionPolicy property. Constructors for the System.Net.Security.SslStream class now take a System.Net.Security.EncryptionPolicy class as a parameter.
    *

      Credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication in the System.Net.NetworkCredential class. To improve security, passwords may now be treated as System.Security.SecureString instances rather than System.String instances.
    *

      Ability to specify how a URI with percent-encoded values is converted and normalized in the System.Uri and System.Net.HttpListener classes. For more information, see the System.Net.Configuration.HttpListenerElement, System.Configuration.SchemeSettingElement, System.Configuration.SchemeSettingElementCollection, and System.Configuration.UriSection classes.

Web

ASP.NET version 4 introduces new features in the following areas:

    *

      Core services, including a new API that lets you extend caching, support for compression for session-state data, and a new application preload manager (autostart feature).
    *

      Web Forms, including more integrated support for ASP.NET routing, enhanced support for Web standards, updated browser support, new features for data controls, and new features for view state management.
    *

      Web Forms controls, including a new Chart control.
    *

      MVC, including new helper methods for views, support for partitioned MVC applications, and asynchronous controllers.
    *

      Dynamic Data, including support for existing Web applications, support for many-to-many relationships and inheritance, new field templates and attributes, and enhanced data filtering.
    *

      Microsoft Ajax, including additional support for client-based Ajax applications in the Microsoft Ajax Library.
    *

      Visual Web Developer, including improved IntelliSense for JScript, new auto-complete snippets for HTML and ASP.NET markup, and enhanced CSS compatibility.
    *

      Deployment, including new tools for automating typical deployment tasks.
    *

      Multi-targeting, including better filtering for features that are not available in the target version of the .NET Framework.

For more information about these features, see What's New in ASP.NET 4 and Visual Web Developer.


Client

Windows Presentation Foundation (WPF) version 4 contains changes and improvements in the following areas:

    *

      New controls, including Calendar, DataGrid, and DatePicker.
    *

      VisualStateManager supports changing states of controls.
    *

      Touch and Manipulation enables you to create applications that receive input from multiple touches simultaneously on Windows 7.
    *

      Graphics and animation supports layout rounding, Pixel Shader version 3.0, cached composition, and easing functions.
    *

      Text has improved text rendering and supports customizing the caret color and selection color in text boxes.
    *

      Binding is supported on the Command property of an InputBinding, dynamic objects, and the Text property.
    *

      XAML browser applications (XBAPs) support communication with the Web page and support full-trust deployment.
    *

      New types in the System.Windows.Shell namespace enable you to communicate with the Windows 7 taskbar and pass data to the Windows shell.
    *

      The WPF and Silverlight Designer in Visual Studio 2010 has various designer improvements to help create WPF or Silverlight applications.

For more information, see What's New in WPF Version 4.

Data
ADO.NET

ADO.NET provides new features for the Entity Framework, including persistence-ignorant objects, functions in LINQ queries, and customized object layer code generation. For more information, see What's New in ADO.NET.
Dynamic Data

For ASP.NET 4, Dynamic Data has been enhanced to give you even more power for quickly building data-driven Web sites. This includes the following:

    *

      Automatic validation that is based on constraints that are defined in the data model.
    *

      The ability to easily change the markup that is generated for fields in the GridView and DetailsView controls by using field templates that are part of a Dynamic Data project.

For more information, see What's New in ASP.NET 4 and Visual Web Developer.
WCF Data Services

ADO.NET Data Service has been renamed to WCF Data Services, and has the following new features

    *

      Data binding.
    *

      Counting entities in an entity set.
    *

      Server-driven paging.
    *

      Query projections.
    *

      Custom data service providers.
    *

      Streaming of binary resources.

For more information, see What's New in WCF Data Services.


Windows Communication Foundation

Windows Communication Foundation (WCF) provides the following improvements:

    *

      Configuration-based activation: Removes the requirement for having an .svc file.
    *

      System.Web.Routing integration: Gives you more control over your service's URL by allowing the use of extensionless URLs.
    *

      Multiple IIS site bindings support: Allows you to have multiple base addresses with the same protocol on the same Web site.
    *

      Routing Service: Allows you to route messages based on content.
    *

      Support for WS-Discovery: Allows you to create and search for discoverable services.
    *

      Standard endpoints: Predefined endpoints that allow you to specify only certain properties.
    *

      Workflow services: Integrates WCF and WF by providing activities to send and receive messages, the ability to correlate messages based on content, and a workflow service host.
    *

      WCF REST features:
          o

            Web HTTP caching: Allows caching of Web HTTP service responses.
          o

            Web HTTP formats support: Allows you to dynamically determine the best format for a service operation to respond in.
          o

            Web HTTP services help page: Provides an automatic help page for Web HTTP services, similar to the WCF service help page.
          o

            Web HTTP error handling: Allows Web HTTP Services to return error information in the same format as the operation.
          o

            Web HTTP cross-domain JavaScript support: Allows use of JSON Padding (JSONP).
    *

      Simplified configuration: Reduces the amount of configuration a service requires

For more information, see What's New in Windows Communication Foundation.


Windows Workflow Foundation

Windows Workflow Foundation (WF) provides improvements in the following areas:

    *

      Improved workflow activity model: The Activity class provides the base abstraction of workflow behavior.
    *

      Rich composite activity options: Workflows benefit from new flow-control activities that model traditional flow-control structures, such as Flowchart, TryCatch, and Switch(Of T).
    *

      Expanded built-in activity library: New features of the activity library include new flow-control activities, activities for manipulating member data, and activities for controlling transactions.
    *

      Explicit activity data model: New options for storing or moving data include variable and directional arguments.
    *

      Enhanced hosting, persistence, and tracking options: Hosting enhancements include more options for running workflows, explicit persistence using the Persistactivity, persisting without unloading, preventing persistence by using no-persist zones, using ambient transactions from the host, recording tracking information to the event log, and resuming pending workflows by using a Bookmark object.
    *

      Easier ability to extend the WF Designer: The new WF Designer is built on Windows Presentation Foundation (WPF) and provides an easier model to use when rehosting the WF Designer outside of Visual Studio.

For more information, see What's New in Windows Workflow Foundation.

Custom Error Handling in ASP.NET

0 comments
Introduction
Structured exception handling is a fundamental part of the CLR and provides .Net programmers a great way of managing errors. In addition to CLR exception system, ASP.Net also provides ways of handling errors.

When a runtime or design-time error occurs in an application, ASP.Net shows a default error page that gives a brief description of the error along with the line number on which the error occurred. A developer would wish to view this default error page, during the testing of the application since the description helps him in rectifying the error. But he would never want a user trying to access his application, to view this error page. The user would be least bothered to know about the error. Instead of showing the default error page, it would be more sensible to show a customized error page that would let the user send notification of the error to the administrator.
Explanation
Consider an example of an ASP.Net application that generates an error intentionally to show how ASP.Net detects it and shows the default error page. The below given webform contains a label and a button server control. In the eventhandler for the button click event, the user will be redirected to another webform "Trial.aspx". Since the page being redirected to, is missing ASP.Net will show the default error page indicating it is a runtime error.

Unlike classic ASP, ASP.Net separates the code for the business logic from the content (i.e HTML and interface logic). The sample application has two files named "webform1.aspx" containing the content and "webform1.aspx.vb" containing the code.
WebForm1.aspx
<%@ Page Language="vb" AutoEventWireup="false"
Codebehind="WebForm1.aspx.vb" Inherits="ErrorSample.WebForm1"%>
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN">
<
HTML
><HEAD><title></title><meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"><meta name="CODE_LANGUAGE" content="Visual Basic 7.0"><meta name="vs_defaultClientScript" content="JavaScript"><meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"></HEAD><body MS_POSITIONING="GridLayout"><form id="Form1" method="post" runat="server"><asp:Label id="Message" style="Z-INDEX: 101; LEFT: 34px;
POSITION: absolute; TOP: 46px"
runat="server"></asp:Label
><asp:Button id="ErrorButton" style="Z-INDEX: 102; LEFT: 268px;
POSITION: absolute; TOP: 41px"
runat="server" Text
="Generate
Error"></
asp:Button
></form></body>
</
HTML
>
WebForm1.aspx.vb
Public Class
WebForm1Inherits System.Web.UI.PageProtected WithEvents Message As System.Web.UI.WebControls.LabelProtected WithEvents ErrorButton As System.Web.UI.WebControls.ButtonPrivate Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles
MyBase.Load
Message.Text = "This sample page generates an Error..."
End
SubPublic Sub ErrorButton_Click(ByVal sender As Object, ByVal e AsSystem.EventArgs)Handles ErrorButton.Click
Response.Redirect("Trial.aspx")
End
Sub
End
Class
Now if you try to run the above web form by viewing it on the browser, you will get the below shown web page:



Now if you click on the button labeled "Generate Error", you will get the below shown default ASP.Net error page.


Customizing Error PageTo customize the default error page, one will have to change the default configuration settings of the application.

There are three error modes in which an ASP.Net application can work:

  1. Off Mode
  2. On Mode
  3. RemoteOnly Mode
The Error mode attribute determines whether or not an ASP.Net error message is displayed. By default, the mode value is set to "RemoteOnly".
  • Off ModeWhen the error attribute is set to "Off", ASP.Net uses its default error page for both local and remote users in case of an error.
  • On ModeIn case of "On" Mode, ASP.Net uses user-defined custom error page instead of its default error page for both local and remote users. If a custom error page is not specified, ASP.Net shows the error page describing how to enable remote viewing of errors.
  • RemoteOnlyASP.Net error page is shown only to local users. Remote requests will first check the configuration settings for the custom error page or finally show an IIS error.
Configuration File
Customization of error page can be implemented by adding a value for an attribute "defaultRedirect" in the <customErrors> tag of the configuration file "web.config". This file determines configuration settings for the underlying application.

  • Off ModeIn this scenario, set the mode attribute value to "Off" as shown below:
    Web.Config File
    <?xml version="1.0" encoding="utf-8"
    ?>
    <
    configuration
    ><system.web><customErrors mode="Off" /></system.web>
    </
    configuration
    >
    When the sample ASP.Net web page is viewed in the browser from the remote machine, one gets the below shown default error page.



    The above example thus shows that, whether it is local or remote access, ASP.Net error page is shown.
    On Mode
    In this scenario, set the mode attribute value to "On" as shown below:

    Web.Config File
    <?xml version="1.0" encoding="utf-8"
    ?>
    <
    configuration
    ><system.web><customErrors defaultRedirect="error.htm" mode="On" /></system.web>
    </
    configuration
    >
    As shown in the configuration file, the "defaultRedirect" attribute has been set to a user-defined page "error.htm". The user-defined error page can be an ASP.Net web page, classic ASP page or a simple HTML page.

    For example, the contents of the user-defined error page "error.htm" can be given as follows:
    Error.htm
    <HTML
    >
    <
    BODY
    ><b>We are very sorry for the inconvenience caused to you...<br></b>
    </
    BODY
    >
    </
    HTML
    >
    When the sample ASP.Net web page is viewed in the browser from the remote/local machine, one gets the below shown custom error page.


  • RemoteOnly Mode
    In this scenario, set the mode attribute value to "RemoteOnly" as shown below:
    Web.Config File<?xml version="1.0" encoding="utf-8" ?>configuration><system.web><customErrors defaultRedirect="error.htm" mode="RemoteOnly" /></system.web>
    </
    configuration
    >

    Since the "defaultRedirect" attribute has been set, if the page is requested from a remote machine page is redirected to "error.htm" and if the page is requested from the local machine the default error page is shown.
Notification of Error to the Administrator
In a practical web application, customization of error pages is not the only requirement. The error, if encountered, should be reported to the administrator so that it can be rectified thus enabling subsequent requests to work properly without any error.

Notification of the error can be sent to the administrator in one of the following two ways:

  1. Error can be registered as a log entry in the Windows Event Log on the administrator's machine.
  2. An Email can be sent to the administrator with a suitable error message.
  • Writing to the Event Log
    In ASP.Net, error can be handled programmatically by writing appropriate code in the page-level error event, for errors on an individual page or in the application-level error event for handling errors that may occur in any page of the application.
    Therefore, code for writing in the Event Log should be written in either of the events, depending on the requirement of the application. To illustrate this example, I have written the code in the application-level event with the error mode set to "RemoteOnly" and the "defaultRedirect" attribute to "error.htm". The application-level error event should be included in the global file "global.asax" within the same application folder.
    The contents of the global file can be given as follows:
    Writing Log Entry in the Event Log
    Imports System.WebImports System.Web.SessionStateImports System.DiagnosticsPublic Class GlobalInherits System.Web.HttpApplicationSub Application_Error(ByVal sender As Object, ByVal e As EventArgs)Dim ErrorDescription As String = Server.GetLastError.ToString'Creation of event log if it does not exist Dim EventLogName As String = "ErrorSample"If (Not EventLog.SourceExists(EventLogName)) ThenEventLog.CreateEventSource(EventLogName, EventLogName)End If' Inserting into event logDim Log As New EventLog
    Log.Source = EventLogName
    Log.WriteEntry(ErrorDescription, EventLogEntryType.Error)
    End Sub
    End
    Class
    Event Log support is provided in .Net through the namespace "System.Diagnostics". So, for the above code to work, it is very essential to add a reference to the above-mentioned namespace in the project. In the event handler for application-level error, a log named "ErrorSample" is created if it does not exist in the Event Log. If it already exists, the error entry is added to the existing list of events. After viewing the page on the browser from a remote machine, the event will get listed in the Event Log on the administrator's machine as shown below:


    Description of the error can be viewed by selecting the appropriate event and double clicking it. Another form pops up as shown below:


  • Sending an Email to the Administrator
    To illustrate this example, I have written the code for sending an Email to the administrator in the application-level error event. The contents of the global file can be given as follows:
    Sending Email To the Administrator
    Imports System.WebImports System.Web.SessionStateImports System.Web.MailPublic Class GlobalInherits System.Web.HttpApplicationSub Application_Error(ByVal sender As Object, ByVal e As EventArgs)Dim mail As New MailMessageDim ErrorMessage = "The error description is as follows : "
    & Server.GetLastError.ToStringmail.To = administrator@domain.com
    mail.Subject = "Error in the Site"
    mail.Priority = MailPriority.High
    mail.BodyFormat = MailFormat.Text
    mail.Body = ErrorMessage
    SmtpMail.Send(mail)
    End Sub
    End
    Class
    In the above code, SMTP service is being used to send the mail across. SMTP mail service support is provided in .Net through the namespace "System.Web.Mail". So, for the above code to work, it is very essential to add a reference to the above-mentioned namespace in the project.

Explain about strong name in .NET.

0 comments
They are the assemblies which can be uniquely identified by attaching the strong name to the dll name. It gives a unique name to each assembly of various versions. This allows solving the DLL hell problem.

Creating an Assembly with a Strong Name

   1. Use the Strong Name tool (Sn.exe) that comes with the .NET Framework Software Development Kit (SDK) to generate a cryptographic key pair.

      The following command uses the Strong Name tool to generate a new key pair and store it in a file called TestKey.snk:

      sn -k Testkey.snk
                             

   2. Add the proper custom attribute to your source for the compiler to emit the assembly with a strong name. Which attribute you use depends on whether the key pair that is used for the signing is contained in a file or in a key container within the Cryptographic Service Provider (CSP). For keys that are stored in a file, use the System.Reflection.AssemblyKeyFileAttribute attribute. For keys that are stored in the CSP, use the System.Reflection.AssemblyKeyNameAttribute attribute.

      The following code uses AssemblyKeyFileAttribute to specify the name of the file that contains the key pair.

      NOTE: In Microsoft Visual Basic, the assembly level attributes must appear as the first statements in the file.Visual Basic .NET Code

      Imports System
      Imports System.Reflection

      <assembly:AssemblyKeyFileAttribute("TestKey.snk")>
                         

      C# Code

      using System;
      using System.Reflection;

      [assembly:AssemblyKeyFileAttribute("TestKey.snk")]
                         
.........................................................................................................................................

A strong name is a reliable .NET assembly identifier,
comprised of the assembly’s simple text name, version
number, culture, public key and a digital signature. The
latter two are generated with the strong name (sn) tool,
while the remainder is part of the assemblies manifest …
usually specified in the AssemblyInfo source file.

........................................................................................................................


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.

In particular, strong names satisfy the following requirements:

Strong names guarantee name uniqueness by relying on unique
key pairs. No one can generate the same assembly name that
you can, because an assembly generated with one private key
has a different name than an assembly generated with another
private key.

Strong names protect the version lineage of an assembly. A
strong name can ensure that no one can produce a subsequent
version of your assembly. Users can be sure that a version
of the assembly they are loading comes from the same
publisher that created the version the application was built
with.

Strong names provide a strong integrity check. Passing the
.NET Framework security checks guarantees that the contents
of the assembly have not been changed since it was built.
Note, however, that strong names in and of themselves do not
imply a level of trust like that provided, for example, by a
digital signature and supporting certificate.

................................................................................................................................................................


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 (the file that contains the assembly manifest, which in turn contains the names and hashes of all the files that make up the assembly), using the corresponding private key. Microsoft® Visual Studio® .NET and other development tools provided in the .NET Framework SDK can assign strong names to an assembly. Assemblies with the same strong name are expected to be identical.

You can ensure that a name is globally unique by signing an assembly with a strong name. In particular, strong names satisfy the following requirements:

    * Strong names guarantee name uniqueness by relying on unique key pairs. No one can generate the same assembly name that you can, because an assembly generated with one private key has a different name than an assembly generated with another private key.
    * Strong names protect the version lineage of an assembly. A strong name can ensure that no one can produce a subsequent version of your assembly. Users can be sure that a version of the assembly they are loading comes from the same publisher that created the version the application was built with.
    * Strong names provide a strong integrity check. Passing the .NET Framework security checks guarantees that the contents of the assembly have not been changed since it was built. Note, however, that strong names in and of themselves do not imply a level of trust like that provided, for example, by a digital signature and supporting certificate.

When you reference a strong-named assembly, you expect to get certain benefits, such as versioning and naming protection. If the strong-named assembly then references an assembly with a simple name, which does not have these benefits, you lose the benefits you would derive from using a strong-named assembly and revert to DLL conflicts. Therefore, strong-named assemblies can only reference other strong-named assemblies.

difference between Server.Transfer and Response.Redirect

0 comments
Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist accros the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive.
Response.Dedirect() :client know the physical loation (page name and query string as well). Context.Items loses the persisitance when nevigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they’re difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems.
As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.
......................................................................................................................................
Response.Redirect simply sends a message down to the browser, telling it to move to another page. So, you may run code like:
Response.Redirect("WebForm2.aspx")
or
Response.Redirect("http://www.karlmoore.com/")
to send the user to another page.
Server.Transfer is similar in that it sends the user to another page with a statement such as Server.Transfer("WebForm2.aspx"). However, the statement has a number of distinct advantages and disadvantages.
Firstly, transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.
But watch out: because the "transfer" process can work on only those sites running on the server, you can't use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.
Secondly, Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.
That's not all: The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.
For example, if your WebForm1.aspx has a TextBox control called TextBox1 and you transferred to WebForm2.aspx with the preserveForm parameter set to True, you'd be able to retrieve the value of the original page TextBox control by referencing Request.Form("TextBox1").
This technique is great for wizard-style input forms split over multiple pages. But there's another thing you'll want to watch out for when using the preserveForm parameter. ASP.NET has a bug whereby, in certain situations, an error will occur when attempting to transfer the form and query string values. You'll find this documented at http://support.microsoft.com/default.aspx?id=kb;en-us;Q316920.
The unofficial solution is to set the enableViewStateMac property to True on the page you'll be transferring to, then set it back to False. This records that you want a definitive False value for this property and resolves the bug.
So, in brief: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and, with a little bug-bashing, allows you to transfer the query string and form variables.
Top Tip: Don't confuse Server.Transfer with Server.Execute, which executes the page and returns the results. It was useful in the past, but, with ASP.NET, it's been replaced with fresher methods of development. Ignore it.

.........................................................................................................................................

A common misconception is the difference between Server.Transfer and Response.Redirect in ASP.NET applications. Redirect and Transfer both cause a new page to be processed, but the interaction between the client (web browser) and server (ASP.NET) is different in each situation.
Redirect: A redirect is just a suggestion – it’s like saying to the client “Hey, you might want to look at this”. All you tell the client is the new URL to look at, and if they comply, they do a second request for the new URL.
If you want to pass state from the source page to the new page, you have to pass it either on the URL (such as a database key, or message string), or you can store it in the Session object (caveat: there may be more than one browser window, and they’ll all use the same session object).
e.g. Redirect to the new.aspx page, passing an ID on the query string. "true" stops processing the current page:

Difference between Web.Config and Machine.Config File

0 comments

Machine.Config:-
1) This is automatically installed when you install Visual Studio. Net.
2) This is also called machine level configuration file.
3)Only one machine.config file exists on a server.
4) This file is at the highest level in the configuration hierarchy.
Web.Config:-
1) This is automatically created when you create an ASP.Net web application project.
2) This is also called application level configuration file.
3)This file inherits setting from the machine.config
.........................................................................................................................................
1)Machine.config is used to store machine level settings
Web.config is used to store per application based settings
2)We can have more than one web.config files but only one
machine.config
3)Web.config overrides the machine.config file.
If we store different values on both for a single key, the
application will get the value from the web.config file
.........................................................................................................................................
The MACHINE.config file contains default and machnine-specific values for all supported setting.
Machine setting are normally controlled by the system admin and app should never be given write access to it.
An application can override most default values stored in the machine.config file by creating one or more web.config files.
At min an app creates a WEB config file in its root folder. The web.config file is a subset of machine.config written according to the same XML achema.

.........................................................................................................................................
Machine.Config:-
1) This is automatically installed when you install .Net Framework.
2)Only one machine.config file can exist on a server.
3) This file is at the highest level in the configuration hierarchy.
4)Its like a common repository for standard items and its over ridden by web.config file.
3)With out the Machine.Config file Application can not be executed.
Web.Config:-
1) This is automatically created when you create an ASP.Net web application project.
2)This file inherits the settings from the machine.config
3)With out the Web.Config file Application can still be executed.

 

difference between autopostback and ispostback?

0 comments
Autopostback - Property of the control
IsPostback - Property of the Page class
Autopostback - get and set property to control postback on changes made for control.
for e.g.
this.ListBox1.AutoPostBack = true;
whenever user will select item, the page will get post back.
IsPostback - get property of the Page class, to check if page is post back i.e. if it is true then page has already executed Init function of the page else it is first time the page has requested to be executed.

what is “AutoPostBack” feature

0 comments
If we want the control to automatically postback in case of any event , we will need to
check this attribute as true.
Example
on a ComboBox change we need to send the event
immediately to the server side then set the “AutoPostBack” attribute to true.
..................................................................................................................................
If we want the control to automatically post back in case of any event, we will need to check this attribute as true. Example on a Combo Box change we need to send the event immediately to the server side then set the “AutoPostBack” attribute to true.

.......................................................................................................................................

For understanding AutoPostBack, we need to know , what a
PostBack
Then, what is AutoPostBack, Autopostback is the mechanism,
by which the page will be posted
Back to the server automatically based on some events in the
web controls. In some of the web controls, the property
called auto post back, which if set to true, will send the
request to the server when an event happens in the control
For example.
Dropdown Box (Combo box) web control has the property
autopostback, if we set the property to true, when ever user
selects a different value in the combo box, and event will
be fired in the server. i.e. a request will be send to the
server.
Why we need to send a request to the server in this case?
Consider this scenario where the web page is used for
entering the user information. The page contains two combo
box controls State and Town. When user selects the state,
the appropriate towns should be filled in the town combo box
which is loaded from the database. For achieving this
requirement, we can set the autopostback property of state
combo box to true. If we do that we can handle the event in
the server side and write code to populate the town combo
box with the values from the database.
This is how we use the autopostback property. I will give
another example for the autopostback usage with another
control which will give much better understanding.
Consider a login page, which contains text fields User ID,
User Name and Password fields. User name text box will not
be editable. So the requirement will be like this, when user
enters the user id and clicks tab, his name should be
displayed in the User Name text field. For achieving this we
have to make autopostback property of the user id textfield
to true and handle the event in the server side, In the
event handler, we have to write code to fetch the user name
from the database for the user id ,which we will be getting
from the user id text box.
How it is happening?
Whenever we set autopostback attribute to true in any of the
controls, the .net framework will automatically insert few
code in to the HTML generated to implement this functionality.
These are the additional items that the framework will
inject to the HTML source for implementing autopostback event.
a. A Java script method with name __doPostBack (eventtarget,
eventargument)
b. Two Hidden variables with name __EVENTTARGET and
__EVENTARGUMENT
c. OnChange JavaScript event to the control

We will discuss one by one of these new entries.

a. __EVENTTARGET and __EVENTARGUMENT
These two controls are added to the HTML source, when ever
any autopostback attribute is set to true for any of the web
control.
The __EVENTTARGET hidden variable will tell the server
,which control actually does the server side event firing so
that the framework can fire the server side event for that
control.
The __ EVENTARGUMENT variable is used to provide additional
event information if needed by the application, which can be
accessed in the server.
b. __doPostBack (eventtarget, eventargument)
Why the framework is inserting this method to the HTML
source, and what it really does.  This method is inserted to
the HTML source to implement the autopostback functionality.
This method will submit the form, when ever called. The two
parameters in this method i.e. eventtarget and eventargument
do the actual work of selecting the control to fire the event.
Eventtarget will contain the name of the control which
initiates the post back event, and event arguments will
contain the additional parameters needed for the event.
(Refer to the previous block).
This method will set the value of the __EVENTTARGET hidden
variable with the eventtarget parameter and __ EVENTARGUMENT
value with the eventargument parameter.
The next activity is to submit the form, so that in the
server side, the framework will check for the name of the
control in the __EVENTTARGET hidden variable and will fire
the appropriate event.
c. OnChange event.
This event is added by the framework to any of the control
where autopostback is set to true, this method will fire the
client side OnChange event and calls the __doPostBack event
with the name of the control where the OnChange event is
happened.
For e.g. If we set autopostback = true to a textfield with
id myTextField, then the HTML for the test field will look
like this.

name="myTextField" OnChange="__doPostBack(' myTextField
','')" id=" myTextField
So whenever the OnChange event in client occurs, the
doPostBack method will be called with the name of the
Textfield as the first parameter.
This name will be set to the __EVENTARGUMENT hidden variable
by the __doPostBack JavaScript method and the form will be
submitted. In the server side the __EVENTARGUMENT hidden
variable will be checked and will take the textfield name
and the server side event for the same will be fired.
IsPostBack –
When we discuss about autopostback, we should have an
understanding of the IsPostBack property of Page class.
IsPostBack property is used by the Page to determine whether
the page is posted back from the client. If IsPostBack
property is false, then the page is loading for the first
time, and if false, then the request is because of some
event generated by web controls.
IsPostBack is used when we want to load some information
when the page loads, for e.g. if we want to load some
information from the database and show in the data grid in a
page for the first time, then we can load and bind the grid
in the page_load when IsPostBack property is false.

Enum in .NET

0 comments
enum
The enum keyword is used when you require a enumeration. A enumeration is a distinct type that consists of a set of named constants called the enumetor list. Every enumeration type has an underlying type which can be all integral times except that of a char type.
Declaration syntax:
[attributes] [modifiers] enum identifier [:base-type] {enumerator-list};

Where:
    * attributes (optional) - this is additional declarative information, look under index A for more information
    * modifiers (optional) - permissible modifiers include: new, public, protected, internal and private ( the 4 access modifiers)
    * base-type (optional) - underlying type for the storage allocated for each enumerator, any integral type except char (default is int)
    * enumerator-list - the enumerators identifiers which are seperated by commas (optionally including a value assignment)
Key Points:
The default underlying type of the elements in the enumeration is int as previously mentioned. The first enumerator begins at 0 by default and each enumerator following is increased by 1. Explicit casts are required to convert from enum type to an integral type.
........................................................................................................................................
    * Understand what an enum is
    * Be able to create new enum types
    * Learn how to use enums
    * Gain familiarity with System.Enum type methods
Enums Defined
Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. In the C# tradition, they are strongly typed, meaning that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. Along the same lines, integral types and enums are not implicitly interchangable. All assignments between different enum types and integral types require an explicit cast.
Enums lend themselves to more maintainable code because they are symbolic, allowing you to work with integral values, but using a meaningful name to do so. For example, what type of code would you rather work with - a set of values named North, South, East, and West or the set of integers 0, 1, 2, and 3 that mapped to the same values, respectively? Enums make working with strongly typed constants via symbolic names easy.
Enums are value types, which means they contain their own value, can't inherit or be inherited from, and assignment copies the value of one enum to another. You will see in this lesson and elsewhere that enums are used and referred to with both lower case, enum, and upper case, Enum. The relationship between the two is that the C# type, enum, inherits the Base Class Library (BCL) type, Enum. Use the C# type, enum, to define new enums and use the BCL type, Enum, to implement static enum methods.
Creating an Enum
The .NET Framework Class Library contains many enums and examples of how they are used. For example, every time you put an icon on a MessageBox, you use the MessageBoxIcon enum. For a list of available enums in the .NET Framework Class Library, look at the documentation for the Enum class and click on the Derived Classes link.
Whenever there are situations where you are using a set of related numbers in a program, consider replacing those numbers with enums. It will make a program more readable and type safe. Listing 17-1 contains an enum definition and code that uses that enum in a switch statement. Instead of using the numbers 0, 1, and 2 in the switch statement, the code is more meaningful through the use of the Volume enum.
Listing 17-1. Creating and Using an Enum: EnumSwitch.cs
using System;
// declares the enum
public enum Volume
{
   Low,
   Medium,
   High
}
// demonstrates how to use the enum
class EnumSwitch
{
   static void Main()
   {
      // create and initialize
      // instance of enum type
      Volume myVolume = Volume.Medium;
      // make decision based
      // on enum value
      switch (myVolume)
      {
         case Volume.Low:
            Console.WriteLine("The volume has been turned Down.");
            break;
         case Volume.Medium:
            Console.WriteLine("The volume is in the middle.");
            break;
         case Volume.High:
            Console.WriteLine("The volume has been turned up.");
            break;
      }
      Console.ReadLine();
   }
}
Listing 17-1 contains a definition for an enum. Notice that it is declared with the enum keyword, has a type identifier (Volume), and contains a comma separated list of values enclosed within curly braces.
This enum is of type Volume and we use it to declare the myVolume variable in the Main method. Since an enum is a value type, we can assign a value (Volume.Medium) to it directly, similar to the simple types such as int or double. Once the myVolume variable is declared and initialized, it is used in the switch statement.Each of the case statements represent a unique member of the Volume enum.
Any time a member of the Volume enum is used, it is fully qualified with the "Volume" identifier to guarantee type safety. For example, if there were a Meat enum in scope, then Meat.Medium would definitely have different semantics than Volume.Medium. With both enums in scope, it would be ambiguous to just use the Medium identifier without type qualification. Using the type identifier ensures such mistakes are not made.
Using Enums
An enum is typically specified as shown in Listing 17-1, but may be customized by changing its base type and member values. By default, the underlying type of an enum is int. This default may be changed by specifying a specific base when declaring the enum. You would specify a different base if the enum was used extensively and there was an opportunity for space savings by selecting a smaller type. Another reason may be if you wanted the underlying type of the enum to correspond to another type in your program and you wanted to explicitly cast between the two without loss of precision. Valid base types include byte, sbyte, short, ushort, int, uint, long, and ulong.
Another modification you can make to an enum is to set the value of any enum member. By default, the first member of an enum takes the value of zero. If this value doesn't make sense for your enum, you can change it to one or some other number. Additionally, you can change any of the members of an enum to any value that is valid for its base type. Unassigned enum members have a value that is one more than their predecessor. Listing 17-2 shows how to modify the base type and member values of an enum.
Listing 17-2. Setting the Enum Base and Initializing Members: EnumBaseAndMembers.cs
using System;
// declares the enum
public enum Volume : byte
{
    Low = 1,
    Medium,
    High
}
class EnumBaseAndMembers
{
    static void Main()
    {
        // create and initialize
        // instance of enum type
        Volume myVolume = Volume.Low;
        // make decision based
        // on enum value
        switch (myVolume)
        {
            case Volume.Low:
                Console.WriteLine("The volume has been turned Down.");
                break;
            case Volume.Medium:
                Console.WriteLine("The volume is in the middle.");
                break;
            case Volume.High:
                Console.WriteLine("The volume has been turned up.");
                break;
        }
        Console.ReadLine();
    }
}
The Volume enum in Listing 17-2 shows how to modify the base type and members of an enum.Its base type is changed to byte with the : <type> syntax following the enum identifier, Volume.This ensures that the Volume enum may only have members with values that are valid for type byte.
The first member of the Volume enum, Low, has its value changed to 1. The same syntax, <member> = <value>, may be applied to any member of the enum. You are restricted from creating forward references, circular references, and duplicate references in enum members.
The default values of the Volume enum are Low=0, Medium=1, and High=2 because the first member of an enum defaults to 0 and the following members default to one more than their predecessor. However, the Volume enum in Listing 17-2 has its Low member set to 1, which means that Medium=2 and High=3.
Enum tricks
Enum types implicitly inherit the System.Enum type in the Base Class Library (BCL). This also means that you can use the members of System.Enum to operate on enum types. This section does just that, showing some useful tips and tricks to use with enums in your programs.
A common requirement with enums is to convert between the enum and a variable of its base type. For example, if you are getting input in the form of an int from a user or a file stream, then you can cast it to an enum and use it in a meaningful way in your program. You can also get a complete list of enum member names or enum values, which is useful if you have logic that needs to iterate through every enum member. Listing 17-3 shows how to perform conversions between enums and their base types and how to use some of the System.Enum type members.
Listing 17-3. Enum Conversions and using the System.Enum Type: Enumtricks.cs
using System;
// declares the enum
public enum Volume : byte
{
    Low = 1,
    Medium,
    High
}
// shows different ways
// to work with enums
class Enumtricks
{
    static void Main(string[] args)
    {
        // instantiate type
        Enumtricks enumtricks = new Enumtricks();
        // demonstrates explicit cast
        // of int to Volume
        enumtricks.GetEnumFromUser();
        // iterate through Volume enum by name
        enumtricks.ListEnumMembersByName();
        // iterate through Volume enum by value
        enumtricks.ListEnumMembersByValue();
        Console.ReadLine();
    }
    // demonstrates explicit cast
    // of int to Volume
    public void GetEnumFromUser()
    {
        Console.WriteLine("\n----------------");
        Console.WriteLine("Volume Settings:");
        Console.WriteLine("----------------\n");
        Console.Write(@"
1 - Low
2 - Medium
3 - High
Please select one (1, 2, or 3): ");
        // get value user provided
        string volString = Console.ReadLine();
        int volInt = Int32.Parse(volString);
        // perform explicit cast from
        // int to Volume enum type
        Volume myVolume = (Volume)volInt;
        Console.WriteLine();
        // make decision based
        // on enum value
        switch (myVolume)
        {
            case Volume.Low:
                Console.WriteLine("The volume has been turned Down.");
                break;
            case Volume.Medium:
                Console.WriteLine("The volume is in the middle.");
                break;
            case Volume.High:
                Console.WriteLine("The volume has been turned up.");
                break;
        }
        Console.WriteLine();
    }
    // iterate through Volume enum by name
    public void ListEnumMembersByName()
    {
        Console.WriteLine("\n---------------------------- ");
        Console.WriteLine("Volume Enum Members by Name:");
        Console.WriteLine("----------------------------\n");
        // get a list of member names from Volume enum,
        // figure out the numeric value, and display
        foreach (string volume in Enum.GetNames(typeof(Volume)))
        {
            Console.WriteLine("Volume Member: {0}\n Value: {1}",
                volume, (byte)Enum.Parse(typeof(Volume), volume));
        }
    }
    // iterate through Volume enum by value
    public void ListEnumMembersByValue()
    {
        Console.WriteLine("\n----------------------------- ");
        Console.WriteLine("Volume Enum Members by Value:");
        Console.WriteLine("-----------------------------\n");
        // get all values (numeric values) from the Volume
        // enum type, figure out member name, and display
        foreach (byte val in Enum.GetValues(typeof(Volume)))
        {
            Console.WriteLine("Volume Value: {0}\n Member: {1}",
                val, Enum.GetName(typeof(Volume), val));
        }
    }
}
The code in Listing 17-3 includes three method calls to GetEnumFromUser, ListEnumMembersByName, and ListEnumMembersByValue. Each of these methods demonstrate a different aspect of using System.Enum to work with enums.
The GetEnumFromUser method shows how to obtain int input and translate it to an appropriate enum type. Converting an int to an enum makes the code more readable and type safe. The following is an excerpt from Listing 17-3 that shows the pertinent part of the code that performs the conversion:
        // get value user provided
        string volString = Console.ReadLine();
        int volInt = Int32.Parse(volString);
        // perform explicit cast from
        // int to Volume enum type
        Volume myVolume = (Volume)volInt;
After the program displays a menu, it prompts the user for a selection in the form of a number (1, 2, or 3). When the user makes a selection and presses the Enter key, the code reads the value with Console.ReadLine, which returns the value as a string type. Since you can only cast an int to a Volume enum type, the user's input must be converted from a string to an int with the Int32.Parse method. Converting the int to a Volume enum type is simply a matter of applying a cast operation during assignment.
To get all the members of an enum at the same time, you can use the GetNames method of the System.Enum type, which returns a string array of the names of all an enum's members. An excerpt from the ListEnumMembersByName method in Listing 17.3 that shows this appears below:
        // get a list of member names from Volume enum,
        // figure out the numeric value, and display
        foreach (string volume in Enum.GetNames(typeof(Volume)))
        {
            Console.WriteLine("Volume Member: {0}\n Value: {1}",
                volume, (byte)Enum.Parse(typeof(Volume), volume));
        }
Because GetNames returns an array of strings, it is easy to use in a loop statement such as foreach. Something you may be curious about in the code above is the second parameter to the WriteLine method's format string. Given the enum type and a string representation of the member name, you can use the Enum.Parse method to get the underlying value of that member. Because the Volume enum's base type is byte, the return value from Enum.Parse must be cast to a byte before assignment, forcing the numeric representation of the enum value to appear. If we would have omitted the byte cast, the output would be the Volume enum member, which would then be converted to a string representation of the member name, which is not what the code intended to show.
Instead of getting names of all the members of an enum, you may have a reason to get all the values of the enum at one time. The code below, from the ListEnumMembersByValue method in Listing 17.3, shows how to accomplish this:
        // get all values (numeric values) from the Volume
        // enum type, figure out member name, and display
        foreach (byte val in Enum.GetValues(typeof(Volume)))
        {
            Console.WriteLine("Volume Value: {0}\n Member: {1}",
                val, Enum.GetName(typeof(Volume), val));
        }
Given the type of the enum, the GetValues method of System.Enum will return an array of the given enum's base type, which in this case is byte. While iterating through this list, each member is printed to the console showing its value and name. The name is obtained by using the GetName method of System.Enum, which accepts an enum type and value for which to get the corresponding name of.
Summary
Enums are lists of strongly typed constants with members that are symbolic names, corresponding to an underlying integral type. Enum base types can be changed and member values can be specified. The System.Enum .NET Framework Class Library type is the base class of enum types and contains methods that allow you to work with enums in different ways, such as working with a list of names or values, converting from value to name, and converting from name to value. For more information on the System.Enum type, see the .NET Framework SDK documentation.