Saturday, August 29, 2009

Working with IIS Metabase with DirectoryServices in .Net

Introduction:

While working with the IIS we all like to know the settings done on the Virtual Directory are correct or not. So we are going to see how to do that programmatically.

To check some properties of the IIS (Virtual Directory) of Web based application

after install, one can create custom application for that.

There are list of IIS Properties which we can get after post installation. The list of properties exposed by the IIS API or Web Settings Property is mentioned below

  • AuthFlags
  • Path
  • AppFriendlyName
  • EnableDirBrowsing
  • AccessRead
  • AccessExecute
  • AccessWrite
  • AccessScript
  • AuthNTLM
  • EnableDefaultDoc
  • DefaultDoc
  • AspEnableParentPaths

The above settings are configured in the Metabase of the IIS.

IIS Metabase:

IIS Metabase is a structure where IIS configuration settings are stored. The metabase configuration and schema for IIS 4.0 and IIS 5.0 were stored in a binary file, but from IIS6.0 the configuration and setting is stored in single binary file (MetaBase.bin), with plain text, Extensible Markup Language (XML) formatted files named MetaBase.xml and MBSchema.xml. You can navigate through the IIS Metabase using MetaEdit or Metabase Explorer.

The Metabase is based on a hierarchical design with inheritance. Each object in the metabase has a KeyType. The KeyType property specifies the type of metabase key.

Implementation:

.Net provides the namespace which is used to get the properties of the IIS Virtual Directory. .Net have the "System.DirectoryServices" namespace which exposes the DirectoryEntry Class.

Code:

WebSettings.cs:

public class WebSettings

{

//Authentication Bitmask Values

//Constant Value Description

public const int MD_AUTH_ANONYMOUS = 0x00000001;

//Anonymous authentication available.

public const int MD_AUTH_BASIC = 0x00000002;

//Basic authentication available.

public const int MD_AUTH_NT = 0x00000004;

//Windows authentication schemes available.

string Auth_Type;

public string calc(int AuthValue)

{

if (AuthValue == MD_AUTH_ANONYMOUS)

{

Auth_Type = "ANONYMOUS ACCESS ENABLED";

}

if (AuthValue == MD_AUTH_BASIC)

{

Auth_Type = "BASIC ACCESS ENABLED";

}

if (AuthValue == MD_AUTH_NT)

{

Auth_Type = "INTEGRATED WINDOWS ACCESS ENABLED";

}

if (AuthValue == (MD_AUTH_ANONYMOUS + MD_AUTH_NT))

{

Auth_Type = "INTEGRATED WINDOWS + ANONYMOUS ACCESS ENABLED";

}

if (AuthValue == (MD_AUTH_ANONYMOUS + MD_AUTH_BASIC))

{

Auth_Type="BASIC + ANONYMOUS";

}

if (AuthValue == (MD_AUTH_ANONYMOUS + MD_AUTH_NT))

{

Auth_Type = "INTEGRATED + ANONYMOUS";

}

if (AuthValue == (MD_AUTH_BASIC + MD_AUTH_NT))

{

Auth_Type = "BASIC + INTEGRATED";

}

if (AuthValue == (MD_AUTH_ANONYMOUS + MD_AUTH_BASIC + MD_AUTH_NT))

{

Auth_Type = "ANONYMOUS + BASIC + INTEGRATED";

}

return Auth_Type;

}

Main.cs

string serverName;

string vDir;

serverName = System.Environment.MachineName;

vDir = "DirectoryName";

vdir = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/ROOT/" + vDir);

wbs = new WebSettings();

string[] sComp = new string[12];

sComp[0] = "AuthFlags";

sComp[1] = "Path";

sComp[2] = "AppFriendlyName";

sComp[3] ="EnableDirBrowsing";

sComp[4] ="AccessRead";

sComp[5] ="AccessExecute";

sComp[6] ="AccessWrite";

sComp[7] ="AccessScript";

sComp[8] ="AuthNTLM";

sComp[9] ="EnableDefaultDoc";

sComp[10] ="DefaultDoc";

sComp[11] ="AspEnableParentPaths";

ListViewItem[] listViewItem = new ListViewItem[12];

lstIISProperty.Items.Clear();

for (int i = 0; i <>

{

//lstComponents.MultiColumn = 2;

lstIISProperty.Sorting = SortOrder.Ascending;

if (sComp[i] != null)

{

listViewItem[i] = new ListViewItem(new string[]{ sComp[i], IISPropertyValue(sCompi]), fnExpected_Value(sComp[i])}, -1);

lstIISProperty.Items.Add(listViewItem[i]);

}

}

Authentication Modes in ASP.Net for Security

Introduction:

When you begin a program for a customer using ASP.Net, you should consider about security. Security is one of the most important components of any application. Security is even more important when you are making a web application which is exposed to million of users. Asp.net provides classes and methods that ensure that the application is secure from outside attacks. In this article we will investigate the different types of authentication provided by ASP.Net. In web.config file you can set authentication mode value 'windows' or 'forms'. What's about difference and how to you use them? (Authentication have some other values to, this article does not consider them.)

Configure the Security Settings in the Web.config File:

This section demonstrates how to add and modify the and configuration sections to configure the ASP.NET application to use window-based or forms-based authentication.

How to use mode "Windows"?

Change the authentication mode to Windows.

Windows Authentication mode provides the developer to authenticate a user based on Windows user accounts. This is the default authentication mode provided by ASP.Net. You can easily get the Identity of the user by using User.Identity.Name. This will return the computer name along with the user name. Windows authentication also provides IsInRole method to find the role of the user and than you can give permissions to the user depending on the role.

<authentication mode="Windows">

<forms name=" AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/" timeout="30" />

authentication>

Deny access to the anonymous user in the section as follows:

<authorization>

<deny users ="?" />

<allow users = "*" />

authorization>

Other you can make a special client to access you project with windows authentication. Code like this (this case you can get value using 'User.Identity.Name', then you can use it to do other work you like.):

<authorization>

<deny users ="?" />

authorization>

How to use mode "Forms"?

Change the authentication mode to Forms.

Insert the tag, and fill the appropriate attributes. (For more information about these attributes, refer to the MSDN documentation)

First you should specify a page and make sure all clients can found it. Code like this

<authentication mode="Forms">

<forms name=" AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/" timeout="30" />

authentication>

Deny access to the anonymous user in the section as follows:

<authorization>

<deny users ="?" />

authorization>

Second in that page you to validate the user's Id and Password. Code like this:

You can use one of two methods to generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event. Sample code is provided for both scenarios. Use either of them according to your requirement.

(1). Call the RedirectFromLoginPage method to automatically generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event:

private void cmdLogin_ServerClick(object sender, System.EventArgs e)

{

If (ValidateUser(txtUserName.Value,txtUserPass.Value) )

{

FormsAuthentication.RedirectFromLoginPage(txtUserName.Value, false);

}

else

{

Response.Redirect("logon.aspx", true);

}

}

(2). Generate the authentication ticket, encrypt it, create a cookie, add it to the response, and redirect the user. This gives you more control in how you create the cookie. You can also include custom data along with the FormsAuthenticationTicket in this case.

Private void cmdLogin_ServerClick(object sender, System.EventArgs e)

{

if (ValidateUser(txtUserName.Value,txtUserPass.Value) )

{

FormsAuthenticationTicket tkt;

string cookiestr;

HttpCookie ck;

tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,

DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");

cookiestr = FormsAuthentication.Encrypt(tkt);

ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);

if (chkPersistCookie.Checked)

ck.Expires=tkt.Expiration;

ck.Path = FormsAuthentication.FormsCookiePath;

Response.Cookies.Add(ck);

string strRedirect;

strRedirect = Request["ReturnUrl"];

if (strRedirect==null)

strRedirect = "default.aspx";

Response.Redirect(strRedirect, true);

}

else

Response.Redirect("logon.aspx", true);

}

Additional Notes:

You may want to store passwords securely in a database. You can use the FormsAuthentication class utility function named HashPasswordForStoringInConfigFile to encrypt the passwords before you store them in the database or configuration file.

You may want to store the SQL connection information in the configuration file (Web.config) so that you can easily modify it if necessary.

You may consider adding code to prevent hackers who try to use different combinations of passwords from logging on. For example, you can include logic that accepts only two or three logon attempts. If the user cannot log on in a certain number of attempts, you may want to set a flag in the database to not allow that user to log on until that user re-enables his or her account by visiting a different page or by calling your support line. In addition, you should add appropriate error handling wherever necessary.

Because the user is identified based on the authentication cookie, you may want to use Secure Sockets Layer (SSL) on this application so that no one can deceive the authentication cookie and any other valuable information that is being transmitted.

Forms-based authentication requires that your client accept or enable cookies on their browser.

The timeout parameter of the configuration section controls the interval at which the authentication cookie is regenerated. You can choose a value that provides better performance and security.

Certain intermediary proxies and caches on the Internet may cache Web server responses that contain Set-Cookie headers, which are then returned to a different user. Because forms-based authentication uses a cookie to authenticate users, this can cause users to accidentally (or intentionally) impersonate another user by receiving a cookie from an intermediary proxy or cache that was not originally intended for them.


Create Navigation Based Application in WPF

This article will demonstrate how to create the Navigation Based Windows Application in WPF.

There are two types of windows applications the first one is Standard Windows Application which is normally the same old style Stand alone or some time we say Desktop based application. The second one is called as Navigation Based Application which is kind of the Web type application. The behavior is some what as the Wizard Type of application where you can navigate between the windows and perform the task.

The WPF has given the way to create the Web Page kind of Windows application, where one can navigate between the Window or Page controls.

Normally when you create the WPF Application the XAML creates the Window control and which has the Title, Width, Height and Windows Startup attribute as shown below

Window1.xaml:

<Window x:Class="WpfApplication2.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml Title="ListView" Height="350" Width="400" Loaded="Window1_Loaded">
Window>

But when you create the Navigation based application the control has the Page tag instead Window tag and it does can't have Title and few more properties/attributes. The Page tag looks like as below.

Page1.xaml:

<Page x:Class="WpfApplication2.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml WindowHeight="300" WindowWidth="300">
Page>

Example 1: The below example show how to implement the Navigation based application. Basically once you put the Page tag, it will render the window with the Navigation Toolbar as shown in Figure 1.

Window1.xaml

<Page x:Class="wpfnavigationwindow_cs.Window1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

WindowHeight="300" WindowWidth="300"

>

<StackPanel>

<TextBlock HorizontalAlignment="Center" FontSize="25">My First Navigation AppTextBlock>

<StackPanel Orientation="Horizontal">

<Image Source="IMG116.jpg" Width="100px"/>

<TextBlock HorizontalAlignment="Center">This is my Network..TextBlock>

StackPanel>

<TextBlock>

Go <Hyperlink NavigateUri="Page1.xaml">HereHyperlink> to go to Next Page.

<TextBlock>

<Hyperlink NavigateUri="http://www./www.c-sharpcorner.com">Go to the SiteHyperlink>

TextBlock>

TextBlock>

StackPanel>

Page>

Windows1.xaml.cs

using System;

using System.Collections.Generic;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Shapes;

namespace wpfnavigationwindow_cs

{

///

/// Interaction logic for Window1.xaml

///

public partial class Window1 : System.Windows.Controls.Page

{

public Window1()

{

InitializeComponent();

}

}

}

Figure 1

When you click on Here Link then it will navigate to Next Page as mentioned in the NavigationURI property of Hyperlink control. The URI has the Page control (XAML) file and once you move the next page it will enable the Navigation Toolbar as shown in the Figure 2

Page1.xaml

<Page x:Class="wpfnavigationwindow_cs.Page1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

>

<Grid>

<TextBlock>This is Page 1. Congratulations you made it.TextBlock>

Grid>

Page>

Figure 2

But the good practice to make the Navigation based application use the NavigationWindowinstead of Page control. As Page Control is mostly used for the Web Based Application and other benefit you can have the Window Control Properties. Now you can set the Title Property for the NavigationWindow.

Another benefit is you can set the Soruce which will open the Windows Control inside the NavigationWindow Control. The XAML page will look like

Window2.xaml

<NavigationWindow x:Class="wpfnavigationwindow_cs.Window2"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="Here is my application" Height="300" Width="300" Source="Window1.xaml"

>

NavigationWindow>

Note: The Source is set to the Window1.xaml, so it will open the window1.xaml inside the NavigationWindow

Now you can set the StartupUri attribute of App.xaml to Window2.xaml so the when you run the application it will open the NavigationWindow application.

App.xaml

<Application x:Class="wpfnavigationwindow_cs.App"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

StartupUri="Window2.xaml"

>

<Application.Resources>

Application.Resources>

Application>