Thursday, December 13, 2007

BizTalk Server Questions & Answers

What is BizTalk?

BizTalk is a messaging based integration tool. It solves common problems that many businesses encounter while automating business processes, integrating multiple heterogeneous systems and communicating with business partners.

It provides a standard for efficient business process development and deployment by providing an internal architecture with deep integration between messaging and orchestration as well as scalable publish and subscribe messaging infrastructure

Explain how BizTalk works ?

BizTalk architecture mainly works on 2 ideas. a) Messaging b) Orchestration

Messaging is a low-level concept involving the exchange of structured data
Orchestration is the high-level view of a sequence of messaging exchanges

A message arrives at a receive location from an application or business partner. The receive location is a particular URL that is being actively monitored by a listener for the protocol involved. The listener is the component that grabs the message and introduces it into the BizTalk runtime environment. Some postreceipt processing occurs in the form of a receive pipeline. The incoming message might be encrypted and signed, for example, in which case the pipeline is responsible for decrypting it and verifying the signature. If the actions in the receive pipeline are successful, the message is entered into the BizTalk MessageBox.
The MessageBox is the heart of BizTalk messaging. It is a SQL Server database that allows for reliable messaging and simple clustering for scalability
Messages are stored with identifying properties, such as the type of message and the originating source of the message. These properties are known as the context of a message.
Applications subscribe to messages based on their context


What is the purpose of message box database?

1) To store inbound messages
2) To store orchestrations subscriptions
3) To coordinate the delivery of messages to orchestrations and send ports

What is required for including BAS in BizTalk installation

Business Activity services require windows SharePoint services which require IIS 6.0 [Available only in win 2003 server].

What is schema in BizTalk?

All messages processed by BizTalk should be represented by schema definitions. It describes the data type of each record and field contained in the message.

What are the two types of schemas supported by BizTalk?

1) Xml Schemas

Xml schema defines the structure of xml messages. Xml messages are arranged in a hierarchical format that is defined by the schema. Messages are identified and validated against their associated schema.

2) Flat File Schemas

Flat File schema defines the structure of messages that use a flat file format. It can be either delimited or positional.

What is default data type used in schemas?

String

What is the difference between property promotions and distinguished fields?
Property promotions are used in routing. It requires property schema
Distinguished fields can only be used in orchestrations. No need for property schema.

What is the purpose of DistinguishedFieldAttribute?

This attribute causes our properties to be emitted as distinguished fields in the message so that we will have access to them in the orchestration.

Note: We need to refer Microsoft.XLang.BaseTypes.dll for this special attribute.

What are the different types of functoid groups available in BizTalk 2006?

String Functoids
Mathematical Functoids
Logical Functoids
Data/Time Functoids
Conversion Functoids
Scientific Functoids
Cumulative Functoids
DataBase Functoids
Advanced Functoids

What is difference between Looping Functoids and Iteration Functoids

The Looping functoid combines multiple records or fields in the source schema into a single record in the destination schema.

The Iteration functoid outputs the index of the current record in a looping structure, beginning at 1 for the first record, 2 for the second record, and so on. It is equivalent to For Loop. An Iteration functoid combined with a Greater Than or Equal To functoid, a Less Than or Equal To functoid, and an And functoid to create the equivalent of a For loop.

What is Value Mapping Functoid ?

The Value Mapping functoid returns the value of its second parameter if its first parameter is true. A common use of the functoid is to change the attributes of a field into the attributes of a record

What is the purpose of Value Mapping Flattening?

The Value Mapping (Flattening) functoid returns the value of its second parameter if its first parameter is true. The Value Mapping (Flattening) functoid enables you to flatten a portion of an input instance message by converting multiple records into a single record

What is validate schema, validate instance and generate instance

Validate schema is used to validate the schema. It lists error messages or warning messages describing validation problems found in the schema by the extension.

Generate instance is used to generate an Xml or Flat File with dummy values based on the schema.

What is Test Map? What are the properties need to be set for testing a map? What is Validate map?
Test Map is used to test the map with the instance data provided in Test Map input instance filename. We need to set the Test Map input instance file and Test Input to Xml or Native [Other than xml]. Optionally we can specify the o/p file name + path also.

Validate map is used to validate message instance data against the source schema before you test the map.


How to suppress the creation of empty tags

We can use the Not Equal to Logical Functoid along with Value Mapping Functoid to suppress empty tags.

How to force the creation of empty tags

By selecting the in the value of destination field.

What is the use of Flat File Schemas

Flat file schemas serve two purposes. They define all of the same record and field characteristics (including structure) as XML schemas, and they provide a mechanism for defining all of the flat file characteristics that are required to translate a flat file instance message into an equivalent XML instance message (or vice versa). The former purpose is most useful when using the flat file schema within BizTalk Mapper to define a transformation of conforming flat file instance messages into a different, destination structure. The destination structure, defined by the destination schema in BizTalk Mapper, may or may not be governed by a flat file message schema (it could be an XML schema).

The latter purpose, that of translating between the flat file format of the document and its equivalent XML format, uses an extensive set of information that is added to the XML Schema definition (XSD) language schema using its annotation syntax.

What is the purpose of Activate Property in Receive Shape in Orchestration?

This allows the messaging system to direct the runtime engine to launch a new instance of the orchestration when a message arrives.Activate should be set to true. Default false.

What is the lifecycle of send port?. What is the purpose of enlisting send port?.

1. Specify the send port. Once specified, it is said to be bound.
2. Enlist the send port.
3. Start the send port.

Purpose of enlisting:

Enlisting is the process by which the subscription filters we specify are verified against the available receive ports and the subscriptions are created in the Message Box Database. Until the send port is enlisted, its subscription is not active and therefore it has no source of messages.


What are the default pipelines ?

There are 4 default pipelines paired into 2 [Receive/Send].
1. PassThru

The receive pass-through pipeline requires that the source and destination of the message be known and that the message is in clear-text and does not require validation. Its send counterpart, meanwhile, takes the message and sends it along to its known destination without any sort of post-processing.

2. Xml Receive

The default XML receive pipeline breaks the message down into its component parts so that it will be ready for the runtime engine. It also invokes a standard component that looks at the message and resolves the identity of the message source. The default XML send pipeline takes a message from the messaging engine, assembles it for transmission, and hands it off to the outbound adapter for transmission

What is the purpose of send port grps?

When we have multiple destination partners with same filter criteria we can configure them here. Ie when we want to send the same msg to multiple receipents.

Whether distinguished fields appear in Correlation Types?

No. Only promoted properties are available..

What are the modes available in debugging orchestration ?

1. Replay Mode [ Reporting Mode ]

It gives insight into the execution of a particular orchestration instance.

2. Live Mode [ Interactive Mode ]

The Live mode debugging allows users to debug an orchestration instance via usage of breakpoints. Breakpoints can be set at class level and instance level.

In class level every orchestration will break at the break point.
In Instance Level it's applicable to that particular instance of the message alone.

Note :

Debugger should be attached to the instance of the orchestration

What is the purpose of tracking?

Tracking provides capabilities to understand and trouble shoot when an error occurs and save messages for further analysis. This tool will help to find messages based on schemas, promoted properties, ports and parties.

What are the default events tracked?

1. Service start and stop events
2. Orchestration events required by debugger
3. Message send and receive events


Where is the tracking information stored in sql database?

BizTalkDTADb

What is Facts in Rules Architecture?

Fact is the elementary component in rules architecture. A fact can be a field in an xml document, a property in .Net object or the value of a column in a relational data.

What is BRE?

Using BRE users can create dynamic rules to reflect changing conditions without the need of recoding/modifying orchestration.

Each rule will consist of a IF clause nad then clause.

What is Vocabularies in BRE?

Vocabularies are user defined names for the facts used in rules and conditions. It increases the readability.

What is Policies?

Policies are nothing but logical grouping of rules. Policies are versioned and becomes immutable once deployed.
These rules can be exported as XML also.


What are the important things to take care while calling rules from Orchestration?

Orchestration should be configured to Long Running Transaction
Call Rules shape should be configured to Atomic Transaction.

Why should we publish Facts and Policies in Business Rules Composer?
When we save it is just stored in sql rules database. To submit these policies and facts to BRE we need to publish it.


How to subscribe a message ?
How to inherit schemas?
Steps for creating a Custom Functoid and a real time example.

Dynamic Ports

Dynamic send ports do not contain a fixed destination address, only a pipeline. The destination address is determined at run time from the value of the OutboundTransportLocation message context property

We can also make use of OutboundTransportType to specify the transport protocol type

What are the different types of transactions available for orchestration

LongRunning and Atomic

Atomic supports ACID
LongRunning supports Consistency and Durability

Diff stages in Receive and Send

Receive Pipeline Stages

1. Decode
2. Disassemble
3. Validate
4. Resolve Party

Send Pipeline Stages

1. Pre Assemble
2. Assemble
3. encode

What is the purpose of Flat File Disassembler ?

The Flat File Disassembler component parses delimited and positional flat file format messages and converts them into an XML representation.

What is dehydrating and rehydrating?

Dehydration is the process of serializing the state of an orchestration into a SQL Server database. Rehydration is the reverse of this process: de-serializing the last running state of an orchestration from the database. Dehydration is used to minimize the use of system resources by reducing the number of orchestrations that have to be instantiated in memory at one time.

How to map messages without orchestration?

In the configuration dialog box of Send Port ,Select Fileters and Maps -> OutBoundMaps

Monday, December 10, 2007

Understanding the Page Life Cycle in ASP.NET

From Web Browser to IIS

When a POST request is initiated from the client side, the Web Server traps the request and it is usually routed to an .aspx web page. The request is actually routed to the HTTP Pipeline, a chain of managed objects.

After the HTTP Page handler class is identified, the ProcessRequest () method is called which eventually fires the different page events in the life cycle of a web page. The sequence of events that takes place in the life cycle of a web page in ASP.NET is:

  1. Page_Init
  2. LoadViewState
  3. LoadPostData
  4. Page_Load
  5. RaisePostDataChangedEvent
  6. RaisePostBackEvent
  7. Page_PreRender
  8. SaveViewState
  9. Page_Render
  10. Page_UnLoad

 

All these events are associated with their respective handlers and you can even override them to customize their default behaviour. The following section discusses each of these events in detail.

The Page Life Cycle Events Explained

Once the request for the web page arrives at the web server, the ASP.NET runtime determines whether the page needs to be parsed or whether a cached version of the page needs to be rendered to the requestor. Then the Request and the Response objects for the page are set and the page life cycle starts.

The Page_Init event is the first event to be triggered in the page life cycle. It is responsible for the initialization activities that are essential to create a page instance. In this phase of the page life cycle, all the server controls of the web page are initialized to their default values. However, it should be noted that the View State for a page is not available at this stage of the page life cycle and a server control of the page cannot access other server controls of the page at this phase.

You can use the Page_Init event to create or re-create the controls that need to be created or re-created dynamically. The following example illustrates how you can override the OnInit() method.

protected override void OnInit(EventArgs e)
{
  if (Page != null)
  {
     Page.Trace.Write ("The OnInit method has been called");
     base.OnInit(e);                                
     Page.RegisterRequiresPostBack(this);
  }
}

Next, the LoadViewState method is called. "The load view state stage only happens when the page has been posted back.  During this stage the view state data saved from the previous page visit is loaded and recursively populated into the Page's control hierarchy". This method restores the View State information of a web page that was last saved using the SaveViewState method. You can override the LoadViewState() method to get an idea on how the viewstate is actually restored.

The following code example illustrates how you can override the LoadViewState() method.

protected override void LoadViewState(Object viewState)
{
  Page.Trace.Write ("The LoadViewState method has been called.");
  if (viewState == null)
  {
    base.LoadViewState(viewState);
  }
}

View State is a hidden field that is associated with every web page. It is responsible for maintaining the state of web pages between postbacks. It maintains a state of a page as it moves back and forth between the web browser at the client side and the web server at the server side. However, it should be noted that ViewState does not hold the controls, rather it holds the values of the form controls and their corresponding ID's that would otherwise be lost due to a post back because they do not post with the form.
After the View State for a web page is restored, the server controls in the web page are populated with posted data, i.e., the data that was posted when the web page was sent from the we browser at the client side to the web server.

The LoadPostBackData event is fired next that processes the data that was last posted to the server for all the server controls that requires the same. Note that all controls in an ASP.NET web page is identified by a unique id. The runtime now parses the controls to match their unique ids against the Name Value Collection in the View State for the control (that has its View State enabled) and updates the control with the posted data.

The next event that gets fired is the Page_Load event that typically restores the page's control values. At this phase of the page life cycle, the web page "calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded." Typically, you bind data to the controls of your web form in this method or call methods write code that should be executed or loaded first before any other event of the web page is triggered.
A typical example of Page_Load event is cited below.

protected override void OnLoad(EventArgs e)
{

 if(!IsPostBack)
  {
    //Code to bind static data to the controls
  }

}

You can check the IsPostBack property of the web page to avoid re-setting the server control values. But why is the IsPostBack property necessary? Well, the reason is that the Page_Load event is fired with every request to the web page. Hence, this property is used to check whether the page was submitted to itself. Further, you can create dynamic controls for your web page here.

The RaisePostBackData and the RaisePostBackEvent events call their respective handlers if the request was a postback. The RaisePostBackEvent that executes next "notifies the server control that caused the postback that it should handle an incoming postback event."

The Pre_Render event is triggered next and you can perform any update operations that you require prior to saving the View State and rendering of the web page content. You can perform the update operations on the ready-to-be rendered output in the PreRender event. Use the Pre_Render event to make any last minute changes to the contents of the web page or any of its controls.

The following code snippet illustrates how you can override the OnPreRender() method.

protected override void OnPreRender (EventArgs e)
{
  Page.Trace.Write ("The OnPreRender has been called.");
  //Any custom code
  base.OnPreRender(e);    
}

The SaveViewState that is called next saves the View State for the web page and its controls in the hidden field called __viewstate that is associated with every web page. Note that the SaveViewMethod that is associated with the SaveViewState event returns a null reference if there is no view state associated with the control. Refer to the code snippet below that illustrates how you can override the SaveViewState() method.

protected override object SaveViewState ()
{
  Page.Trace.Write ("The SaveViewState method has been called.");
  //Write your custom code here.
  return base.SaveViewState ();
}

The rendering event is the next stage in the web page life cycle. This actually is not an event. Rather, it is a state of processing where the Page instance executes this method on all the controls of the web page to eventually render the web page content to the web browser at the client or the requestor side. It makes use of "a text writer that writes its output to the OutputStream of the page's Response property." However, it should be noted that prior to rendering the web page, the view state for the web page and all its controls (provided view state for the web page and/or its controls enabled) are saved. You can trap the rendered output and make any changes on it, i.e., adding headers and footers to the rendered page, etc.

The last stage in the ASP.NET web page life cycle is the Page_UnLoad event. This event is called prior to the disposal of the web page and usually contains the code that is responsible for releasing of resources that were acquired in the earlier stages of the page life cycle. Once this is done, the web browser receives the "HTTP response packet" and the web page is displayed in the web browser. In this method, you can perform typical cleanup activities. According to MSDN, "Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed." It should be noted that you cannot make any changes to the response stream in this event as the page and its controls have already been rendered.

The web browser now receives the HTTP response packet and displays the same in the web page. This concludes the page life cycle of an ASP.NET web page.

 

            ---------------------------------------------------------------------------------

 

Summary of Authentication Options

Authentication option

Description

Windows - Basic

Use for nonsecure identification of clients, as the user name and password are sent in base 64-encoded strings in plain text. Passwords and user names are encoded, but not encrypted, in this type of authentication. A determined, malicious user equipped with a network-monitoring tool can intercept user names and passwords.

Windows - Basic over SSL

Use for secure identification of clients in Internet scenarios. The user name and password are sent over the network using Secure Sockets Layer (SSL) encryption, rather than plain text. This is relatively easy to configure and works for Internet scenarios. However, using SSL degrades performance.

Windows - Digest

Use for secure identification of clients in Internet scenarios. Uses hashing to transmit client credentials in an encrypted manner so the password is not transmitted in clear text. In addition, Digest authentication can work through proxy servers. However, it is not widely supported on other platforms.

Windows - Integrated Windows

Uses NTLM or Kerberos. Uses a cryptographic exchange with the user's Microsoft Internet Explorer Web browser.

Windows - Client Certificates

Use for secure identification of clients in Internet and intranet scenarios. Requires each client to obtain a certificate from a mutually trusted certificate authority. Certificates are optionally mapped to user accounts, which are used by IIS for authorizing access to the Web service.

Forms

Not supported by Web services. This is a system by which unauthenticated requests are redirected to an HTML form using HTTP client-side redirection. Most clients of Web services will not want to provide credentials using a UI; you must work around this if you want to use forms authentication.

SOAP headers – Custom

Useful for both secure and nonsecure Internet scenarios. User credentials are passed within the SOAP header of the SOAP message. The Web server, regardless of the platform hosting the Web service, provides a custom authentication implementation.

Understanding and Using .NET Partial Classes

 

 one of the language enhancements in .NET 2.0—available in both VB.NET 2005 and C# 2.0—is support for partial classes. In a nutshell, partial classes mean that your class definition can be split into multiple physical files. Logically, partial classes do not make any difference to the compiler. During compile time, it simply groups all the various partial classes and treats them as a single entity.

One of the greatest benefits of partial classes is that it allows a clean separation of business logic and the user interface (in particular the code that is generated by the visual designer). Using partial classes, the UI code can be hidden from the developer, who usually has no need to access it anyway. Partial classes will also make debugging easier, as the code is partitioned into separate files.

In this article, I will examine the use of partial classes in more detail and discuss how Visual Studio 2005 makes use of partial classes.

Using Partial Classes
Listing 1 contains two class definitions written in VB.NET, with the second class definition starting with the partial keyword. Both class definitions may reside in two different physical files. Functionally, Listing 1 is equivalent to Listing 2.

Listing 1

'---File1.vb---
Public Class Class1
    Public Sub method1()
 
     End Sub
End Class
  
File2.vb
Partial Public Class Class1
     Public Sub method2()
 
     End Sub
End Class

Listing 2

 '---File1.vb---
Public Class Class1
     Public Sub method1()
 
     End Sub
    Public Sub method2()
  
    End Sub
End Class 

So, what are the uses for partial classes?

Here are some good reasons to use partial classes:

  1. They allow programmers on your team to work on different parts of a class without needing to share the same physical file. While this is useful for projects that involve big class files, be wary: If you find your class file getting too large, it may well signal a design fault and refactoring may be required.
  2. The most compelling reason for using partial class is to separate your application business logic from the designer-generated code. For example, the code generated by Visual Studio 2005 for a Windows Form is kept separate from your business logic (we will discuss this in a later section). This will prevent developers from messing with the code that is used for the UI. At the same time, it will prevent you from losing your changes to the designer-generated code when you change the UI.

Author's Note: The "partial" keyword in VB.NET used to be called "expands" in pre-beta versions of Visual Studio 2005.


Examining Partial Classes
The following code sample shows the class definition of MyClass1. I declared all my properties in this file. To avoid confusion, I named my class file MyClass1.Properties.vb, in order to make it obvious that this file contains a properties definition.

'---MyClass1.Properties.vb 
'---one of the classes need not have the Partial keyword
Public Class MyClass1 
    Private pX As Integer
     Private py As Integer
    Property x() As Integer
         Get
            Return pX
         End Get
        Set(ByVal value As Integer)
            pX = value
         End Set
    End Property
     Property y() As Integer
         Get
            Return py
         End Get
        Set(ByVal value As Integer)
             py = value
        End Set
     End Property
End Class  

In another file, named MyClass1.Methods.vb, I provide the methods implementation of MyClass1. I used the Partial keyword to indicate that this definition should be combined with the original MyClass1 definition.

'---MyClass1.Methods.vb
'---must have the Partial keyword
Partial Public Class MyClass1
     Private py  As Integer
 
     Public Sub method1()
         ' implementation here
     End Sub
  
    Public Sub  method3(ByVal x As Integer , ByVal y  As Integer)
        ' implementation here 
    End Sub 
 
     Public Sub method2()
        ' implementation here 
    End Sub 
End Class 

In reality, you can mix and match properties and method definitions in any of the files, but for clarity it is a good idea to group properties definitions in one file and methods definitions in another. The usual rules of OO apply: If there is a method1 in both files, then both method1s must have unique signatures.

The syntax of partial classes in VB.NET and C# differs slightly. The following shows the implementation of partial classes in C#:

 // In C#, the partial keyword must 
     // appear in all class definitions
     public partial class MyClass1 
    {
         public MyClass1 ()
        {
             //implementation here
        }
     }
 
     public partial class  MyClass1
    {
             //implementation here
     } 

Besides the order in which the "partial" keyword is placed, the most significant difference is the strict enforcement of the use of the "partial" keyword in all partial classes in C#. It is mandatory, whereas in VB.NET, not all of the partial classes have to have the "partial" keyword. This has caused a significant amount of newsgroup discussion about the rationale for the difference. My advice is that you should always prefix partial classes with the "partial" keyword. At least this will give you a visual clue that part of the implementation of the class lies somewhere else, and it is definitely useful when it comes to debugging.

While partial classes allow you to split the definition of a class into multiple files, you cannot mix languages. That is, all partial classes must be written in the same language. Besides using the "partial" keyword for classes, you can also use it for structures and interfaces.

If your class implements multiple interfaces, it is a good idea to use partial classes to contain the implementation for each interface.

Page 1 of 2

 

Practical Uses of Partial Classes in Visual Studio 2005
Hide-protecting code is one of the best uses of partial classes; you can prevent mishaps and provide useful code-layer abstraction at the same time. In Visual Studio 2005, Microsoft uses partial classes to hide designer-generated code. For example, in Visual Studio .NET 2003, the designer-generated code for a Windows form is encapsulated within the region "Windows Form Designer generated code" (see Figure 1). Very often, developers will accidentally modify the code within this region and cause the form to display incorrectly.

 

 

 

 

 

In Visual Studio 2005 however, the designer-generated code is no longer visible in the Code View window (see Figure 2). Instead, it is hidden within Solution Explorer.

To see the designer-generated code, go to Solution Explorer and click on the Show All Files button (see Figure 3). Under the name of the Windows form, you will see a file post fixed with the "Designer.vb" name. Double-clicking on Form1.Designer.vb will reveal the designer-generated code:

Partial Public Class Form1
     Inherits System.Windows.Forms.Form
 
     <System.Diagnostics.DebuggerNonUserCode()> _
    Public Sub New() 
        MyBase.New()
  
        'This call is required by the   
        ' Windows Form Designer. 
        InitializeComponent()
         ... 

 

Figure 2. Out of Sight, Out of Mind: In Visual Studio 2005, the designer-generated code is not visible.

 

Notice that the Form1.Designer.vb file appears under the Form1.vb file in Solution Explorer. This is a good way to represent the relationship between the two files. So what does Visual Studio do to represent this relationship? The answer lies in the .vbproj or .csproj (for C# projects) file. Open the file in Notepad and use Ctrl + F to locate the <ItemGroup> element:

...
<ItemGroup>
     <Compile Include="Form1.vb">
      <SubType>Form</SubType> 
    </Compile>
     <Compile Include="Form1.Designer.vb">
      <DependentUpon>Form1.vb</DependentUpon> 
      <SubType>Form</SubType>
     </Compile>
    ...  

 

Figure 3. Unhidden: Showing all hidden files in Solution Explorer. Choose Designer.vb from the list to see the designer-generated code.

 

As you can see, the <DependentUpon> element indicates that Form1.Designer.vb is dependent on Form1.vb. So how is this information useful to us?

Recall that earlier in this article I mentioned two partial classes, MyClass1.methods.vb and MyClass1.properties.vb. Assume that these two classes serve as a template and contain general-purpose functions (and you generally would not make changes to these two classes). You may add a third partial class to add business-specific functions. And so, it would be useful to hide the first two partial classes in Solution Explorer by modifying the .vbproj/.csproj file:

 <ItemGroup>
     <Compile Include="MyClass1.vb">
      <SubType>MyClass1</SubType> 
    </Compile>
     <Compile Include="MyClass1.properties.vb" >
      <DependentUpon>MyClass1.vb </DependentUpon>
      <SubType>MyClass1</SubType>
     </Compile>
    <Compile Include="MyClass1.methods.vb " >
      <DependentUpon>MyClass1.vb</DependentUpon>
       <SubType>MyClass1</SubType>
    </Compile>  

 

Figure 4. Hidden: Hiding the partial classes in Solution Explorer.

 

When the project is loaded in Visual Studio 2005, you should see the two partial classes hidden, as shown in Figure 4.

Unfortunately, at this moment you need to manually modify the project file in order to hide partial classes. Hopefully in the next beta Microsoft will build this function into Visual Studio. Or someone else will write a plugin for that.

In this article, you have seen how to split the definitions of a class into multiple classes using the "partial" keyword. The greatest use of partial classes is undoubtedly the separation of UI and business logic. I am interested to know how else you may be using partial classes

Creating and writing ASP.NET 2.0 custom Configuration Sections

 

ASP.NET 2.0 has made it pretty nice to create custom configuration sections and be able to access these configuration sections via code. You can basically implement a new ConfigurationSection class. For example, I've built a configuration section for my Database Resource Provider like this:

 

    public class wwDbResourceProviderSection : ConfigurationSection

    {

        [ConfigurationProperty("connectionString",DefaultValue=""),

        Description("The connection string used to connect to the db Resource provider")]      

        public string ConnectionString

        {

            get { return this["connectionString"] as string; }

            set { this["connectionString"]  = value ; }

        }

       

 

        [ConfigurationProperty("resourceTableName",DefaultValue="Localizations"),

        Description("The name of the table used in the Connection String database for localizations.")]

        public string ResourceTableName

        {

            get { return this["resourceTableName"] as string; }

            set { this["resourceTableName"] = value; }

        }

       

        [ConfigurationProperty("designTimeVirtualPath",DefaultValue=""),

        Description("The virtual path to the application. This value is used at design time and should be in the format of: /MyVirtual")]

        public string DesignTimeVirtualPath

        {

            get { return this["designTimeVirtualPath"] as string; }

            set { this["designTimeVirtualPath"] = value; }

        }

 

       

 

        public wwDbResourceProviderSection(string ConnectionString, string ResourceTableName, string DesignTimeVirtualPath)

        {

            this.ConnectionString = ConnectionString;

            this.DesignTimeVirtualPath = DesignTimeVirtualPath;

            this.ResourceTableName = ResourceTableName;

        }

 

        public wwDbResourceProviderSection()

        {

          

        }

 

    }

 

 

And create your 'properties' for the section by simply creating public properties and marking them up with a few attributes. The whole thing can then be stuck into web.config like this:

 

< configSections> 

  <section name= "wwDbResourceProvider"

           type ="Westwind.Globalization.wwDbResourceProviderSection"

  />

</ configSections>  

< wwDbResourceProvider  

    connectionString ="server=(local);database=Internationalization;integrated security=true;"

    resourceTableName ="Localizations"

    designTimeVirtualPath ="/internationalization"

    localizationFormWebPath ="~/localizationadmin/localizeform.aspx"

    addMissingResources ="false"

    useVsNetResourceNaming ="false"

    showLocalizationControlOptions ="false"

    showControlIcons ="true"

/>

 

Nice.

 

However, I've not been able to figure out how to write data back to the config file through the ConfigurationSection interface. This class representation supports the ability to save the content, but when I try to assign a value like so:

 

protected void Page_Load(object sender, EventArgs e)

{

 

    object T = WebConfigurationManager.GetWebApplicationSection("wwDbResourceProvider") ;

    if (T != null)

    {

        wwDbResourceProviderSection Section = T as wwDbResourceProviderSection;

        Response.Write(Section.ConnectionString);

 

        Section.ShowControlIcons = false;           

    }

}

 

I get an exception that the configuration is read only.

 

Exception Details: System.Configuration.ConfigurationErrorsException: The configuration is read only.

 

 

As it turns out the code to write this needs to look a little differently:

 

protected void Page_Load(object sender, EventArgs e)

{

 

    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

    wwDbResourceProviderSection Section = config.GetSection("wwDbResourceProvider") as wwDbResourceProviderSection;

    Section.ShowControlIcons = true;

    config.Save();

 

    return;

}

 

And this works…

 

 

 

 

 

 

 

 

 

 

<connectionStrings >
    <
remove name ="LocalSqlServer" />
    <
add name ="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName ="System.Data.SqlClient"/>
    <
add name="MainConnStr" connectionString ="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</
connectionStrings>

< connectionStrings>
    <
remove name =" LocalSqlServer" />
    <
add name=" LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true " providerName="System.Data.SqlClient"/>
    <
add name="MainConnStr" connectionString ="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName ="System.Data.SqlClient"/>
</
connectionStrings>