Thursday 7 February 2013

Creating and Configuring FTP Sites in IIS


File Transfer Protocol (FTP) is a standard protocol for moving files from one computer to another across the Internet. The files are stored on a server computer, which runs FTP server software. Remote computers can then connect using FTP and read files from the server or copy files to the server. An FTP server is similar to an HTTP server (that is, a Web server) in that you can communicate with it using an Internet protocol. However, an FTP server does not run Web pages; it only sends and receives files from remote computers.

You can configure Internet Information Services (IIS) to function as an FTP server. This allows other computers to connect to the server and copy files to and from the server. For example, you might configure IIS to act as an FTP server if you are hosting Web sites on your computer and you want to allow remote users to connect to your computer and copy their files to the server.


Typically, FTP credentials are passed as clear text and not encrypted for transmission. It is recommended that you use FTP with Anonymous or Basic authentication. For more information, see the topics "Securing FTP Sites" and "Authentication Methods Supported in IIS 6.0" in the IIS Technical Reference.

IIS as an FTP Server

In addition to acting as a Web server, IIS can act as an FTP server. The FTP service is not installed by default on IIS. Therefore, to use IIS as an FTP server, you must install the FTP service. For more information about installing and configuring IIS as an FTP server, see the Help documentation that is included with IIS, or see the section "Configuring FTP Sites" in the IIS Technical Reference.

Note

You will need your Windows CD.
To set up an FTP server using IIS

    Click the Start button, click Control Panel, and then click Add or Remove Programs.

    Click Add/Remove Windows Components.

    In the Windows Components Wizard dialog box, if you are running at least Windows Server 2003, select Application Server, and then click Details.

    Select Internet Information Services (IIS) and then click Details.

    In the Internet Information Services (IIS) dialog box, select the File Transfer Protocol (FTP) Service check box and click OK.

    In the Windows Components Wizard dialog box, click Next. If prompted, insert your Windows CD.

    When the installation process is finished, you can use the FTP service with IIS.

Creating Folders

After setting up an FTP server, you need to create a folder structure for the server. By default, the FTP server will have a root folder with the following path: C:\inetpub\ftproot.

The FTP root folder acts as the root for your FTP server in the same way that C:\inetpub\wwwroot is the root for your Web server.

You must create the physical folders where the files will reside. This can either be a subfolder of the FTP root or another folder elsewhere on the computer. Then, you create a virtual root, or alias, that the FTP server will use to point to the physical directory in which files will reside.
To configure an FTP folder and virtual root

    Create a new folder to hold files. You can name the folder anything you like. For example, name the new folder ExampleFtpFiles, so that the path of the folder is C:\inetpub\ftproot\ExampleFtpFiles.

    In Windows, from the Administrative Tools menu, select Internet Information Services.
    NoteNote

    In Windows XP, you can also right-click My Computer in the Start menu or on the desktop, and then click Manage. In the Computer Management dialog box, open the Services and Applications node.

    Open the node for your computer, and then open the FTP Sites node.

    Right-click the Default FTP Site node, click New, and then click Virtual Directory.

    In the Virtual Directory Creation Wizard, specify an alias (or name) that users can use to get to the FTP folder that you created in step 1. The name can be anything you like. It is often least confusing to use the directory name as the alias name, so that the virtual directory might be called ExampleFtpFiles.

    For the path, type or browse to the path of the directory from step 1, for example Inetpub\ftproot\ExampleFtpFiles.

    For Access Permissions, specify Read, and then click Next to finish with the wizard.
    NoteNote

    Do not enable Write permissions unless you understand how to secure your IIS FTP server. For more information, see the topic titled "Securing FTP Sites" in the IIS Technical Reference.

Configuring Permissions

You must also grant permissions to users so that they will be able to read and write to the folder.
To establish permissions for the FTP folder

    In Windows, from the Administrative Tools menu, choose Internet Information Services.
    NoteNote

    In Windows XP, you can also right-click My Computer in the Start menu or on the desktop and then select Manage. In the Computer Management dialog box, open the Services and Applications node.

    Open the node for your computer, open the FTP Sites node, and then open the Default FTP Site node.

    Right-click the virtual directory node for the FTP folder that you want (for instance ExampleFtpFiles) and click Permissions.

    On the Security tab, select or add your user account and assign Modify permissions.

    This sets NTFS permissions. To specify IP restrictions, right-click the folder name, click Properties, and add restrictions on the Directory Security tab. For more information, see the topics "Access Control in IIS 6.0" in the IIS Technical Reference.

    Close the Properties dialog box.

Creating a Web Server Virtual Directory

You typically create a virtual directory for the Web server that maps to the FTP site so that the Web server can access the files in the FTP root. The Web virtual directory name can be the same as the FTP virtual directory name, but this is not required.
To create a Web server virtual directory

    In the Internet Information Services dialog box, open the Web Sites node.

    Right-click the Default Web Site node, click New, and then click Virtual Directory.

    In the wizard, specify an alias that users will use with http:// protocol to access the files in the FTP folder. This can be the same as the FTP alias, for instance ExampleFtpFiles.

    For the directory path, type or browse to the path of the FTP directory, for example C:\inetpub\ftproot\ExampleFtpFiles.

    For access permissions, select Read and Run scripts.

    Click Finish to create the virtual directory and close the wizard

Wednesday 6 February 2013

Mocking Frameworks for .NET



The four major competitors in the free/open source .NET mocking framework arena are microsoft .netNMock/NMock2, NMock3, Rhino Mocks and MOQ. NMock and NMock2 were actually built by different teams, but they kept the same design philosophy and are backwards compatible so they can be used almost interchangeably. If you're familiar with NMock/NMock2, you'll see that NMock3 is from the same gene pool, but it starts fresh and has somewhat different syntax from its siblings. All of the major mocking libraries are mature products with a decent-sized user base, so it's not tough to find good examples and help for all of them but NMock3.

Like many other .NET developers, I started using NMock, and then "upgraded' to nMock2, but both use "magic strings" which can't take advantage of Intellisense, and make tests brittle because they're not easily amenable to refactoring without the use of additional tools like ReSharper to replace name-similar text in strings. On the plus side, NMock doesn't rely on the explicit record/replay statements as Rhino Mocks does. The NMock2 codebase hasn't been updated since late in 2009, and should not be expected to see continued development.

On the plus side, Rhino Mocks has a syntax that supports code refactoring and compile-time checking. Unfortunately, I don't find the syntax to be particularly intuitive, and the variety of ways to construct and condition mocks can lead to some confusion when different people are writing tests. There is also the annoying need to write explicit record and replay statements. Another problem with Rhino Mocks is that the project appears to be running out of steam. Aside from a few bug-fix patches, not much has happened since early in 2009.

MOQ is one of the new kids, with an annoying name that needs to be spelled out so that people know what you're talking about. The latest release became available in April of 2011, and MOQ has active developers and community. It's different from the first two in several ways. When using NMock and Rhino you create mock objects of a specific type. When using MOQ you create mocks that contain an objects of a specific type, and that wrapper around the mock objects lends itself to simpler syntax in your tests. MOQ requires .Net 3.5 or greater due to its use of lambdas, so if you haven't learned to use lambda expressions, now is the time. I haven't used it extensively, but so far I like everything about MOQ... except for the name.

NMock3 is the other new kid, and the one who seems less well known. Maybe it isn't on the radar for most folks because NMock/NMock2 seem behind the times, and that may have kept expectations low. Versions of NMock3 are available for .NET 3.5 and 4.0, and the latest RTM became available in January of 2011 with a beta release in July of 2011. Like MOQ, you create mocks that contain objects of a specific type, and that wrapper around the mock objects leverages lambda expressions, so NMock/NMock2 users are in for some culture shock. Since the NMock3 examples are a little thin in the wild I've include sample code below. Note that in conditioning your mocks, the parameters in the lambda expressions are just placeholders, while the "real" parameters are specified in the "With" method.
using NUnit.Framework;
using NMock; /* NMock3 */

namespace Foo.Test
{
    [TestFixture]

    public class FundsTransferPresenterTest
    {
        private MockFactory _mocks;
        private Mock<IFundsTransferView> _viewMock;
        private Mock<IAccountService> _serviceMock;
        private FundsTransferPresenter _presenter;

        [SetUp]
        public void SetUp()
        {
            _mocks = new MockFactory();
            _viewMock = _mocks.CreateMock<IFundsTransferView>();
            _serviceMock = _mocks.CreateMock<IAccountService>();
            _presenter = new FundsTransferPresenter(_viewMock.MockObject, _serviceMock.MockObject);
        }

        [Test]
        public void CanQueryViewUseAccountServiceToFundsTransfer()
        {
            _viewMock.Expects.One.Method(v => v.GetSourceAccount()).WillReturn("1234");
            _viewMock.Expects.One.GetProperty(v => v.TargetAccount).WillReturn("9876");
            _viewMock.Expects.One.GetProperty(v => v.TransferAmount).WillReturn(200.00m);
            _serviceMock.Expects.Exactly(1).Method(s => s.TransferFunds(null, null, 0m)).With("1234", "9876", 200.00m);
            _presenter.Transfer_Clicked();
            _mocks.VerifyAllExpectationsHaveBeenMet();
        }
    }
}

/*******************************   Fragment of System Under Test (SUT)   *******************************/

    public interface IFundsTransferView
    {
        string GetSourceAccount();
        string TargetAccount { get; }
        decimal TransferAmount { get; }
    }

    public interface IAccountService
    {
        void TransferFunds(string source, string target, decimal amount);
    }

    public class FundsTransferPresenter
    {
        private IFundsTransferView _view;
        private IAccountService _service;

        public FundsTransferPresenter(IFundsTransferView view, IAccountService service)
        {
            _service = service;
            _view = view;
        }

        public void Transfer_Clicked()
        {
            _service.TransferFunds(_view.GetSourceAccount(), _view.TargetAccount, _view.TransferAmount);
        }
    }

Source: Robert Zormeir

Tuesday 5 February 2013

Diagramming for Java 4.0 Released

Diagramming for Java 4.0 Released

MindFusion has released a new version of its Diagramming component for Java with various new features.

Node Effects

Diagramming for Java adds support for two visual effects - the GlassEffect and AeroEffect, which can be applied to nodes. Effects can be added, removed or modified at any time and this will immediately reflect on the diagram. You can apply more than one effect of the same type.

Styles & Themes

The Style is a set of properties, which can be applied to a given diagram item or to all items of a specific type. A Theme is a collection of styles. Each style in the theme is associated with a specific type of diagram items and affects all items of this type. Themes can be loaded and saved from / to XML files. Use the Theme Editor tool to create your own themes.

Diagram documents and tabbed views

The new DiagramDocument class represents a collection of pages (sheets). Each sheet is an instance of DiagramPage. DiagramPage is derived from the Diagram class and adds a Title property. All your current code that uses Diagram objects will work with DiagramPage objects. You can add, modify, rearrange and delete DiagramPage-s with the Pages collection.

The new TabbedScrollPane displays tabs for each DiagramDocument page. You can specify the active page by activating its associated tab. Use the buttons in the tab tray to add and remove pages to/from the document. Drag the tab of a page with the mouse to change its location.

Layer List Control

The new LayerListView control displays all layers of the Diagram together with a title and an overview area. You can edit the Visible and Locked properties of the layer and set the currently active layer. Use the plus (+) button to add new layers to the Diagram.

Layers

Now you can assign diagram Item-s into layers. Layers can be locked, hidden moved up or down in the Z-order or as a group. Call the setLayerIndex method of items to associate them with layers in the Diagram.Layers collection. Each Layer has Visible, Locked and ZIndex properties, which affect all items in the layer.

    
One-way Layout

The OneWayLayout class ensures that links enter into nodes from the same general direction and exit them from the opposite side.
Ruler improvements

The new MeasureUnit class lets you specify units of the ruler. The MeasureUnit class provides several built-in units as well as the opportunity to create custom units of measure.


Magnifier

The new magnifier tool allows users to interactively zoom in (or out) portions of the diagram by holding down a modifier key or pressing a mouse button. You can customize the magnifier's zoom factor and appearance.
Miscellaneous

The Shape property in ContainerNode and TreeViewNode can be set to Rectangle or RoundRect;
the value of DiagramItem.ZIndex property is no longer required to be unique and smaller than the number of items;
and more.

API Changes

A few changes were required to keep the API elegant and easy to use with the numerous new features added to Diagramming for Java. The changes are described in details in the "What's new" section in the documentation of the component.

Monday 4 February 2013

Reading Connection Strings from the Web.config File

Reading Connection Strings from the Web.config File 

The connectionStrings element is a ConnectionStringSettingsCollection collection of ConnectionStringSettings objects. Working with collection elements can be slightly more complicated than working with other configuration elements.

To update a configuration setting, use the Save or SaveAs method of the configuration object. For more information, see Using the Configuration Classes. For additional code examples, see the ConnectionStringsSection class and related classes.

This example uses the non-static method of obtaining configuration data, which allows you to pull configuration information from any application. If you are going to obtain configuration information from the application in which your code resides, use the static method, which processes faster. For more information, see the Working with Local and Remote Configuration Settings section in ASP.NET Configuration API Overview.

This example applies to a Web site named MyWebSiteRoot. To run the sample, you will have to either run it in a Web site by that name or replace the string supplied to the OpenWebConfiguration method with the name of your Web site.


C#


System.Configuration.Configuration rootWebConfig =
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
{
    connString =
        rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
    if (null != connString)
        Console.WriteLine("Northwind connection string = \"{0}\"",
            connString.ConnectionString);
    else
        Console.WriteLine("No Northwind connection string");
}

VB
Dim rootWebConfig As System.Configuration.Configuration
    rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot")
Dim connString As System.Configuration.ConnectionStringSettings
If (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count) Then
    connString = rootWebConfig.ConnectionStrings.ConnectionStrings("NorthwindConnectionString")
    If Not (Nothing = connString.ConnectionString) Then
        Console.WriteLine("Northwind connection string = {0}", connString.ConnectionString)
    Else
        Console.WriteLine("No Northwind connection string")
    End If
End If

Compiling the Code
This example requires:

    A connectionStrings element in the root Web.config file that contains a connection named NorthwindConnectionString. The element might look like the following:

<connectionStrings>
  <add
    name="NorthwindConnectionString"
    connectionString="Data Source=serverName;Initial
    Catalog=Northwind;Persist Security Info=True;User
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>

The connectionStrings element is a direct child of the <configuration> element and a peer of the system.web element.
Security noteSecurity Note

When storing sensitive information such as user names and passwords in a configuration file, you should encrypt the sensitive values using protected configuration. For more information, see How to: Secure Connection Strings When Using Data Source Controls.
Robust Programming

If the specified connection string does not exist in the Web.config file, no object is returned. When reading connection strings, be sure to check that the code has returned an object.
Security

The configuration file should be protected on the server by using Windows security settings to limit who can read the file. The connectionString element can be encrypted in order to protect it.

Sunday 3 February 2013

Create Custom Configuration Sections Using IConfigurationSectionHandler

Create Custom Configuration Sections Using IConfigurationSectionHandler 

You can extend the standard set of ASP.NET configuration settings with XML configuration elements of your own. To do this, you must create your own configuration section handler.

The handler must be a .NET Framework class that implements either the System.Configuration.IConfigurationSectionHandler interface or the System.Configuration.ConfigurationSection class.

NOTE:
This topic uses the System.Configuration.IConfigurationSectionHandler interface, which has been deprecated in the .NET Framework version 2.0. For an example that uses the System.Configuration.ConfigurationSection class, see How to: Create Custom Configuration Sections Using ConfigurationSection. If you use the following code examples, please build them with the .NET Framework version 1.0 or 1.1.

The section handler interprets and processes the settings defined in XML configuration elements within a specific portion of a Web.config file and returns an appropriate configuration object based on the configuration settings. The configuration object that the handler class returns can be any data structure; it is not limited to any base configuration class or configuration format. ASP.NET uses the configuration object to read and write to your custom configuration element.
To create a custom configuration section handler

Create a public class that implements the System.Configuration.IConfigurationSectionHandler interface, as illustrated in the following code.
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;

namespace MyConfigSectionHandler
{
  public class MyHandler : IConfigurationSectionHandler
  {
    #region IConfigurationSectionHandler Members

    object IConfigurationSectionHandler.Create(
        object parent, object configContext, XmlNode section)
    {
      throw new Exception("The method is not implemented.");
    }

    #endregion
  }
}


Add your own code to perform the configuration work that you desire.


For example, you can replace the throw new Exception("The method is not implemented."); line with code that obtains the attribute names and values from the Attributes property of the section parameter, and return a custom configuration object. The following example uses a Hashtable as the configuration object.

using System;
using System.Collections;
using System.Text;
using System.Configuration;
using System.Xml;

namespace MyConfigSectionHandler
{
  public class MyHandler : IConfigurationSectionHandler
  {
    #region IConfigurationSectionHandler Members

    object IConfigurationSectionHandler.Create(
      object parent, object configContext, XmlNode section)
    {
      // Creates the configuration object that this method will return.
      // This can be a custom configuration class.
      // In this example, we use a System.Collections.Hashtable.
      Hashtable myConfigObject = new Hashtable();

      // Gets any attributes for this section element.
      Hashtable myAttribs = new Hashtable();
      foreach (XmlAttribute attrib in section.Attributes)
      {
        if (XmlNodeType.Attribute == attrib.NodeType)
          myAttribs.Add(attrib.Name, attrib.Value);
      }

      // Puts the section name and attributes as the first config object item.
      myConfigObject.Add(section.Name, myAttribs);

      // Gets the child element names and attributes.
      foreach (XmlNode child in section.ChildNodes)
      {
        if (XmlNodeType.Element == child.NodeType)
        {
          Hashtable myChildAttribs = new Hashtable();

          foreach (XmlAttribute childAttrib in child.Attributes)
          {
            if (XmlNodeType.Attribute == childAttrib.NodeType)
              myChildAttribs.Add(childAttrib.Name, childAttrib.Value);
          }
          myConfigObject.Add(child.Name, myChildAttribs);
        }
      }

      return (myConfigObject);
    }
    #endregion
  }
}


To add a custom section handler to an ASP.NET configuration file

Add a sectionGroup and section element to your Web.config file inside the configSections element, as illustrated in the following code.

    Nesting a section element in a sectionGroup is optional, but is recommended to help organize configuration data.

    You can add the section handler declaration in a different configuration file than the one where you add your custom configuration elements providing that the configuration file where the section handler is declared is higher in the configuration file hierarchy. For more information, see ASP.NET Configuration File Hierarchy and Inheritance.

    The type attribute of the section element must match the manifest of the assembly or there will be a configuration error. The assembly file itself must be in the same ASP.NET application directory as the Web.config file that defines it.

    <configuration>

    <!-- Configuration section-handler declaration area. -->
      <configSections>
        <sectionGroup name="myCustomGroup">
          <section
            name="myCustomSection"
            type="MyConfigSectionHandler.MyHandler, MyCustomConfigurationHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
            allowLocation="true"
            allowDefinition="Everywhere"
          />
        </sectionGroup>
          <!-- Other <section> and <sectionGroup> elements. -->
      </configSections>

      <!-- Configuration section settings area. -->

    </configuration>

    Add your custom configuration elements in the configuration section settings area of your Web.config file.

    <configuration>

    <!-- Configuration section-handler declaration area. -->

      <!-- Configuration section settings area. -->
      <myCustomGroup>
        <myCustomSection myAttrib1="Clowns">
          <myChildSection
              myChildAttrib1="Zippy"
              myChildAttrib2="Michael Zawondy "/>
        </myCustomSection>
      </myCustomGroup>

      <!-- Other configuration settings, like <system.web> -->

    </configuration>

To programmatically access your custom configuration data

    Obtain an instance of your custom configuration object and use the System.Configuration.ConfigurationManager.GetSection(System.String) method or the System.Web.Configuration.WebConfigurationManager.GetSection(System.String) method to populate it.

    The following example of an ASPX page works with the previous examples to enumerate the attributes and child elements of the custom configuration section when a button is clicked.

    Because the custom section handler uses a Hashtable as the configuration object, the GetSection method returns a Hashtable.

    The following code goes in the .aspx page. The code for the button click event, which goes in the code-behind file, is contained in the next code example.

    The following code examples require the .NET Framework version 1.0 or 1.1.
    C#

    <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="BugTest.WebForm1" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

    <html>
      <head>
        <title>WebForm1</title>
        <meta name="GENERATOR"
              Content="Microsoft Visual Studio .NET 2003">
        <meta name="CODE_LANGUAGE" Content="C#">
        <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">
        <h1>Enumerate MyCustomSection</h1>
        <asp:Label ID="Label1" runat="server"
            Text="" />
        <br />
        <asp:Button ID="Button1" runat="server"
            Text="Get Custom Config Info"
            OnClick="Button1_Click" />
        </form>
      </body>
    </html>

    VB

    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
      <HEAD>
        <title>WebForm1</title>
        <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 2003">
        <meta name="CODE_LANGUAGE" Content="VB">
        <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">
          <h1>Enumerate MyCustomSection</h1>
          <asp:Label ID="Label1" runat="server" Text="" />
          <br>
          <asp:Button ID="Button1" runat="server" Text="Get Custom Config Info" OnClick="Button1_Click" />
        </form>
      </body>
    </HTML>

    The following code for the button click event goes in the code-behind file that belongs to the preceding .aspx page. The code-behind file uses the file name extension of .aspx.cs or .aspx.vb, depending on the language attribute of the @Page declaration.

    [C#]

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Configuration;
    using System.Text;

    namespace BugTest
    {
        /// <summary>
        /// Summary description for WebForm1.
        /// </summary>
        public class WebForm1 : System.Web.UI.Page
        {
            protected System.Web.UI.WebControls.Label Label1;
            protected System.Web.UI.WebControls.Button Button1;
       
            private void Page_Load(object sender, System.EventArgs e)
            {
                // Put user code to initialize the page here
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                //
                // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                //
                InitializeComponent();
                base.OnInit(e);
            }
           
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {   
                this.Button1.Click += new System.EventHandler(this.Button1_Click);
                this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion

            protected void Button1_Click(object sender, System.EventArgs e)
            {
                Hashtable config =
    (Hashtable)System.Configuration.ConfigurationSettings.GetConfig("myCustomGroup/myCustomSection");
               
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("Config object item count = {0}<br/><br/>", config.Count);
                foreach (DictionaryEntry deKey in config)
                {
                    sb.AppendFormat("<h2>Attributes in the {0} Element:</h2>",
                        deKey.Key.ToString());
                    Hashtable attribs = (Hashtable)deKey.Value;
                    foreach (DictionaryEntry deAttrib in attribs)
                    {
                        sb.AppendFormat("{0} = {1}<br/>",
                            deAttrib.Key.ToString(), deAttrib.Value.ToString());
                    }
                }
                Label1.Text = sb.ToString();
                Label1.Visible = true;

            }
        }
    }

    VB

    Imports System.Text

    Public Class WebForm1
      Inherits System.Web.UI.Page

    #Region " Web Form Designer Generated Code "

      'This call is required by the Web Form Designer.
      <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

      End Sub
      Protected WithEvents Label1 As System.Web.UI.WebControls.Label
      Protected WithEvents Button1 As System.Web.UI.WebControls.Button

      'NOTE: The following placeholder declaration is required by
      ' the Web Form Designer.
      'Do not delete or move it.
      Private designerPlaceholderDeclaration As System.Object

      Private Sub Page_Init(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
      End Sub

    #End Region

      Private Sub Page_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
      End Sub

      Protected Sub Button1_Click(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles Button1.Click
        Dim config As Hashtable = _
    System.Configuration.ConfigurationSettings.GetConfig( _
    "myCustomGroup/myCustomSection")

        Dim sb As New StringBuilder
        sb.AppendFormat("Config object item count = {0}<br/><br/>", _
    config.Count)

        For Each deKey As DictionaryEntry In config
          sb.AppendFormat("<h2>Attributes in the {0} Element:</h2>", _
    deKey.Key.ToString())
          Dim attribs As Hashtable = deKey.Value
          For Each deAttrib As DictionaryEntry In attribs
            sb.AppendFormat("{0} = {1}<br/>", deAttrib.Key.ToString(), _
    deAttrib.Value.ToString())
          Next
          Label1.Text = sb.ToString()
          Label1.Visible = True
        Next

      End Sub
    End Class

Saturday 2 February 2013

Access and Modify ASP.NET Configuration Files Remotely


The System.Configuration and System.Web.Configuration types allow your application to access the configuration files on a remote server. In particular, you can open and modify the Machine.config or a Web.config file in any Microsoft Internet Information Services (IIS) application or its child directories on a remote server. This topic:

    Demonstrates how to set the remote server to allow a client computer to access the server configuration files.

    Provides a console application, to run on the client computer, that can read or modify the server configuration files.

    Discusses the security considerations to take into account.

To access configuration files on a remote server, the client computer must be able to communicate with the server. To enable this communication, a remote configuration component must be installed on the server.

The client computer then accesses the server configuration files by calling the ASP.NET configuration API through the remote configuration component. For more information, see Editing ASP.NET Remote Configuration Files.

Note

If the requested configuration file does not exist, the .NET Framework, running on the server, returns a configuration file consisting entirely of inherited settings that apply to the specified path. If your application requests an update, a new file is created. When running the console application, you must enter a valid server name. This is because ASP.NET passes this name directly to the operating system. You must likewise enter a fully qualified user name with the domain name prefix.


To set up the remote server

    Install the remote configuration component on the server using the ASP.NET IIS Registration tool (Aspnet_regiis.exe) with the config+ command, as shown in the following code.

    Aspnet_regiis config+

    Programmatically or manually, make sure that the Web.config file of the IIS server's "Default Web Site" contains values similar to the following:

    <appSettings>
        <add key="keyName1", value = "this entry value"/>
        <add key="keyName2", value = "this entry value"/>
        <add key="keyName3", value = "this entry value"/>
    </appSettings>

To update the remote configuration files using a console application

    Run the console application provided in the code example below to update the Web.config file of the Default Web Site on the remote server. This example assumes that the user running the client application has administrative privileges on the remote server. You can use either of these two commands.

    >remoteconfiguration machineName
    >remoteconfiguration machineName domainName\userName password

Friday 1 February 2013

Create and Configure an HTTP Module

Create and Configure an HTTP Module

configure the httpModules element of a Web-application configuration by using the HttpModulesSection class and related types.

An HTTP module is a type that implements the IHttpModule interface and provides request processing by handing application events. For more information about HTTP modules, see Introduction to HTTP Modules.

The following table lists the accompanying topics, which include the code for an example HTTP module and an example configuration that programmatically adds and removes the HTTP module from an ASP.NET Web application. The HTTP module in these examples is a simple library application called RequestTimeIntervalModule.dll. Members of the RequestTimeIntervalModule class calculate the time interval between the beginning and the end of the Web request, obtain the principal's ID, and finally display the information on any Web page in the application.

Using the Example HTTP Module

The following preparatory steps are required to use the accompanying code examples.

Note:

You must run this example in an intranet environment where you can use Windows authentication to authenticate the users. By default, only administrators have read/write access to a Web.config file.

To create the HTTP module

    Compile the code for the HTTP module (Example HTTP Module) as a class library called RequestTimeIntervalModule. This produces an assembly DLL.

    Create a Web application named Test. You can create the application in IIS as a virtual directory named Test. If you need information about creating and configuring an IIS virtual directory, see How to: Create and Configure Virtual Directories in IIS.

    Create a Bin directory directly under the root directory of your Web application (which is also called the Web-application root).

    In the Bin directory, copy the RequestTimeIntervalModule.dll file.

Note:Alternatively, you can use the ASP.NET dynamic compilation feature to test your HTTP module code without pre-compiling an assembly DLL. ASP.NET dynamically compiles source code files that are placed in the App_Code directory directly under the root directory of your Web site. Therefore, classes in source files in the App_Code directory can be accessed from pages without being pre-compiled into assemblies. The App_Code directory is a new feature that is available in ASP.NET version 2.0. Storing your HTTP module code in the App_Code directory allows you to easily test the module without pre-compiling the code. For an example that uses this kind of implementation, see How to: Create Custom HTTP Modules. For information about compilation options, see ASP.NET Compilation Model.

Configuring the Example HTTP Module

This code example uses the HttpModulesSection class and related types to configure the application.
To configure the HTTP module

    Compile the code for configuring the HTTP module (Example Configuration Code for an HTTP Module) as a console application.

    From a command-line, call your console application. If there is no existing setting for the RequestTimeIntervalModule HTTP module, one is created. If there is no existing Web.config file in your ASP.NET application, one is created with the new setting. The setting might look like the following httpModules element, as a child element of the system.web element, in your Web.config file.

Testing the Example HTTP Module

HTTP modules enable you to examine the outbound response and modify it. The RequestTimeIntervalModule HTTP module uses the System.Web.HttpResponse.Output property to append some text to the response body.
To test the HTTP module

    In the root directory, create a blank ASP.NET page called Default.aspx.

    Open a Web browser and request the Default.aspx page from the application called Test, which you created earlier.

    The RequestTimeIntervalModule HTTP module appends the following text to any requested page in your ASP.NET application:

    Current user: <user name>

    Time span between begin-request and end-request events: <timespan>

    Your friendly HttpModule: RequestTimeIntervalModule

Source:http://msdn.microsoft.com/en-us/library/tfd6k449%28v=vs.85%29.aspx