Tuesday, December 2, 2008

IIS Errors on Windows XP: Failed to access IIS metabase, and Mutex could not be created

Failed to access IIS metabase

System.Web.Hosting.HostingEnvironmentException: Failed to access IIS metabase

I solved this by Reinstalling the .NET 2.0 Framework via aspnet_regiis -i

Mutex could not be created

System.InvalidOperationException: Mutex could not be created

The Solution for this error is bit more complicate:

  1. Close all opened Visual Studios.
  2. Navigate to C:\Windows\Microsoft.NET\Framework\v2[....]\Temporary ASPNET pages.
  3. Delete the folder for your application (You can delete the temporary folder completley)
  4. Perform IISReset via command line or via inetmgr.exe
  5. Browse your application directly from IIS and not from any where else.
  6. You should see your application correctly now.

Good Luck !

http://blogs.microsoft.co.il/blogs/giladlavian/archive/2008/02/26/iis-errors-on-2003-server-failed-to-access-iis-metabase-and-mutex-could-not-be-created.aspx

Monday, December 1, 2008

30 Common String Operations in C# and VB.NET – Part II

In the previous article, 30 Common String Operations in C# and VB.NET – Part I, we explored 15 common String operations while working with the String class. In Part II of the article, we will continue with the series and cover 15 more.
All the samples are based on two pre-declared string variables: strOriginal and strModified.
C#
string strOriginal = "These functions will come handy";
string strModified = String.Empty;
VB.NET
Dim strOriginal As String = "These functions will come handy"
Dim strModified As String = String.Empty
16. Count Words and Characters In a String – You can use Regular Expression to do so as shown below:
C#
// Count words
System.Text.RegularExpressions.MatchCollection wordColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @"[\S]+");
MessageBox.Show(wordColl.Count.ToString());
// Count characters. White space is treated as a character
System.Text.RegularExpressions.MatchCollection charColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @".");
MessageBox.Show(charColl.Count.ToString());
VB.NET
' Count words
Dim wordColl As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, "[\S]+")
MessageBox.Show(wordColl.Count.ToString())
' Count characters. White space is treated as a character
Dim charColl As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, ".")
MessageBox.Show(charColl.Count.ToString())
17. Remove characters in a String - The String.Remove() deletes a specified number of characters beginning at a given location within a string
C#
// Removes everything beginning at index 25
strModified = strOriginal.Remove(25);
MessageBox.Show(strModified);
or
// Removes specified number of characters(five) starting at index 20
strModified = strOriginal.Remove(20,5);
MessageBox.Show(strModified);
VB.NET
' Removes everything beginning at index 25
strModified = strOriginal.Remove(25)
MessageBox.Show(strModified)
Or
' Removes specified number of characters(five) starting at index 20
strModified = strOriginal.Remove(20,5)
MessageBox.Show(strModified)
18. Create Date and Time from String – Use the DateTime.Parse() to convert a string representing datetime to its DateTime equivalent. The DateTime.Parse() provides flexibility in terms of adapting strings in various formats.
C#
strOriginal = "8/20/2008";
DateTime dt = DateTime.Parse(strOriginal);
VB.NET
strOriginal = "8/20/2008"
Dim dt As DateTime = DateTime.Parse(strOriginal)
19. Convert String to Base64 - You will have to use the methods in System.Text.Encoding to convert string to Base64. The conversion involves two processes:
a. Convert string to a byte array
b. Use the Convert.ToBase64String() method to convert the byte array to a Base64 string
C#
byte[] byt = System.Text.Encoding.UTF8.GetBytes(strOriginal);
// convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt);
VB.NET
Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(strOriginal)
' convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt)
20. Convert Base64 string to Original String - In the previous example, we converted a string ‘strOriginal’ to Base64 string ‘strModified’. In order to convert a Base64 string back to the original string, use FromBase64String(). The conversion involves two processes:
a. The FromBase64String() converts the string to a byte array
b. Use the relevant Encoding method to convert the byte array to a string, in our case UTF8.GetString();
C#
byte[] b = Convert.FromBase64String(strModified);
strOriginal = System.Text.Encoding.UTF8.GetString(b);
VB.NET
Dim b As Byte() = Convert.FromBase64String(strModified)
strOriginal = System.Text.Encoding.UTF8.GetString(b)
21. How to Copy a String – A simple way to copy a string to another is to use the String.Copy(). It works similar to assigning a string to another using the ‘=’ operator.
C#
strModified = String.Copy(strOriginal);
VB.NET
strModified = String.Copy(strOriginal)
22. Trimming a String – The String.Trim() provides two overloads to remove leading and trailing spaces as well as to remove any unwanted character. Here’s a sample demonstrating the two overloads. Apart from trimming the string, it also removes the "#" character.
C#
strOriginal = " Some new string we test ##";
strModified = strOriginal.Trim().Trim(char.Parse("#"));
VB.NET
strOriginal = " Some new string we test ##"
strModified = strOriginal.Trim().Trim(Char.Parse("#"))
23. Padding a String – The String.PadLeft() or PadRight() pads the string with a character for a given length. The following sample pads the string on the left with 3 *(stars). If nothing is specified, it adds spaces.
C#
strModified = strOriginal.PadLeft(34,'*');
VB.NET
strModified = strOriginal.PadLeft(34,"*"c)
24. Create a Delimited String – To create a delimited string out of a string array, use the String.Join()
C#
string[] strArr = new string[3] { "str1", "str2", "str3"};
string strModified = string.Join(";", strArr);
VB.NET
Dim strArr As String() = New String(2) { "str1", "str2", "str3"}
Dim strModified As String = String.Join(";", strArr)
25. Convert String To Integer - In order to convert string to integer, use the Int32.Parse(). The Parse method converts the string representation of a number to its 32-bit signed integer equivalent. If the string contains non-numeric values, it throws an error.
Similarly, you can also convert string to other types using Boolean.Parse(), Double.Parse(), char.Parse() and so on.
C#
strOriginal = "12345";
int temp = Int32.Parse(strOriginal);
VB.NET
strOriginal = "12345"
Dim temp As Integer = Int32.Parse(strOriginal)
26. Search a String – You can use IndexOf, LastIndexOf, StartsWith, and EndsWith to search a string.
27. Concatenate multiple Strings – To concatenate string variables, you can use the ‘+’ or ‘+=’ operators. You can also use the String.Concat() or String.Format().
C#
strModified = strOriginal + "12345";
strModified = String.Concat(strOriginal, "abcd");
strModified = String.Format("{0}{1}", strOriginal, "xyz");
VB.NET
strModified = strOriginal & "12345"
strModified = String.Concat(strOriginal, "abcd")
strModified = String.Format("{0}{1}", strOriginal, "xyz")
However, when performance is important, you should always use the StringBuilder class to concatenate strings.
28. Format a String – The String.Format() enables the string’s content to be determined dynamically at runtime. It accepts placeholders in braces {} whose content is replaced dynamically at runtime as shown below:
C#
strModified = String.Format("{0} - is the original string",strOriginal);
VB.NET
strModified = String.Format("{0} - is the original string",strOriginal)
The String.Format() contains 5 overloads which can be studied over here
29. Determine If String Contains Numeric value – To determine if a String contains numeric value, use the Int32.TryParse() method. If the operation is successful, true is returned, else the operation returns a false.
C#
int i = 0;
strOriginal = "234abc";
bool b = Int32.TryParse(strOriginal, out i);
VB.NET
Dim i As Integer = 0
strOriginal = "234abc"
Dim b As Boolean = Int32.TryParse(strOriginal, i)
Note: TryParse also returns false if the numeric value is too large for the type that’s receiving the result.
30. Determine if a String instance starts with a specific string – Use the StartsWith() to determine whether the beginning of a string matches some specified string. The method contains 3 overloads which also contains options to ignore case while checking the string.
C#
if (strOriginal.StartsWith("THese",StringComparison.CurrentCultureIgnoreCase))
MessageBox.Show("true");
VB.NET
If strOriginal.StartsWith("THese",StringComparison.CurrentCultureIgnoreCase) Then
MessageBox.Show("true")
End If
So those were some 30 common string operations that we saw in these two articles. Since these articles contained only a short introduction of each method, I would suggest you to explore each method in detail using the MSDN documentation. Mastering string operations can save us a lot of time in projects and improve application performance too. I hope this article was useful and I thank you for viewing it.

30 Common String Operations in C# and VB.NET – Part I

In this article, I have compiled some common String operations that we encounter while working with the String class. In Part I, I have covered 15 common string operations. In the next article, I will continue this article and cover 15 more.
Update: Part II of this series can be found over here 30 Common String Operations in C# and VB.NET – Part II
All the samples are based on two pre-declared string variables: strOriginal and strModified.
C#
string strOriginal = "These functions will come handy";
string strModified = String.Empty;
VB.NET
Dim strOriginal As String = "These functions will come handy"
Dim strModified As String = String.Empty
1. Iterate a String – You can use the ‘for’ loop or ‘foreach’ loop to iterate through a string. The ‘for’ loop gives you more flexibility over the iteration.
C#
for (int i = 0; i <>
{
MessageBox.Show(strOriginal[i].ToString());
}
or
foreach (char c in strOriginal)
{
MessageBox.Show(c.ToString());
}
VB.NET
For i As Integer = 0 To strOriginal.Length - 1
MessageBox.Show(strOriginal(i).ToString())
Next i
Or
For Each c As Char In strOriginal
MessageBox.Show(c.ToString())
Next c
2. Split a String – You can split strings using String.Split(). The method takes an array of chars, representing characters to be used as delimiters. In this example, we will be splitting the strOriginal string using ‘space’ as delimiter.
C#
char[] delim = {' '};
string[] strArr = strOriginal.Split(delim);
foreach (string s in strArr)
{
MessageBox.Show(s);
}
VB.NET
Dim delim As Char() = {" "c}
Dim strArr As String() = strOriginal.Split(delim)
For Each s As String In strArr
MessageBox.Show(s)
Next s
3. Extract SubStrings from a String – The String.Substring() retrieves a substring from a string starting from a specified character position. You can also specify the length.
C#
// only starting position specified
strModified = strOriginal.Substring(25);
MessageBox.Show(strModified);
// starting position and length of string to be extracted specified
strModified = strOriginal.Substring(20, 3);
MessageBox.Show(strModified);
VB.NET
' only starting position specified
strModified = strOriginal.Substring(25)
MessageBox.Show(strModified)
' starting position and length of string to be extracted specified
strModified = strOriginal.Substring(20, 3)
MessageBox.Show(strModified)
4. Create a String array – There are different ways to create a Single Dimensional and Multi Dimensional String arrays. Let us explore some of them:
C#
// Single Dimensional String Array
string[] strArr = new string[3] { "string 1", "string 2", "string 3"};
// Omit Size of Array
string[] strArr1 = new string[] { "string 1", "string 2", "string 3" };
// Omit new keyword
string[] strArr2 = {"string 1", "string 2", "string 3"};
// Multi Dimensional String Array
string[,] strArr3 = new string[2, 2] { { "string 1", "string 2" }, { "string 3", "string 4" } };
// Omit Size of Array
string[,] strArr4 = new string[,] { { "string 1", "string 2" }, { "string 3", "string 4" } };
// Omit new keyword
string[,] strArr5 = { { "string 1", "string 2" }, { "string 3", "string 4" } };
VB.NET
' Single Dimensional String Array
Dim strArr As String() = New String(2) { "string 1", "string 2", "string 3"}
' Omit Size of Array
Dim strArr1 As String() = New String() { "string 1", "string 2", "string 3" }
' Omit new keyword
Dim strArr2 As String() = {"string 1", "string 2", "string 3"}
' Multi Dimensional String Array
Dim strArr3 As String(,) = New String(1, 1) { { "string 1", "string 2" }, { "string 3", "string 4" } }
' Omit Size of Array
Dim strArr4 As String(,) = New String(, ) { { "string 1", "string 2" }, { "string 3", "string 4" } }
' Omit new keyword
Dim strArr5 As String(,) = { { "string 1", "string 2" }, { "string 3", "string 4" } }
5. Reverse a String – One of the simplest ways to reverse a string is to use the StrReverse() function. To use it in C#, you need to add a reference to the Microsoft.VisualBasic dll.
C#
string strModified = Microsoft.VisualBasic.Strings.StrReverse(strOriginal);
MessageBox.Show(strModified);
VB.NET
Dim strModified As String = StrReverse(strOriginal)
MsgBox(strModified)
6. Compare Two Strings – You can use the String.Compare() to compare two strings. The third parameter is a Boolean parameter that determines if the search is case sensitive(false) or not(true).
C#
if ((string.Compare(strOriginal, strModified, false)) <>
{
MessageBox.Show("strOriginal is less than strOriginal1");
}
else if ((string.Compare(strOriginal, strModified, false)) > 0)
{
MessageBox.Show("strOriginal is more than strOriginal1");
}
else if ((string.Compare(strOriginal, strModified, false)) == 0)
{
MessageBox.Show("Both strings are equal");
}
VB.NET
If (String.Compare(strOriginal, strModified, False)) < style="color: blue;">Then
MessageBox.Show("strOriginal is less than strOriginal1")
ElseIf (String.Compare(strOriginal, strModified, False)) > 0 Then
MessageBox.Show("strOriginal is more than strOriginal1")
ElseIf (String.Compare(strOriginal, strModified, False)) = 0 Then
MessageBox.Show("Both strings are equal")
End If
7. Convert a String to Byte[] (Byte Array) – The Encoding.GetBytes() encodes all the characters into a sequence of bytes. The method contains six overloads out of which we will be using the Encoding.GetBytes(String).
C#
byte[] b = Encoding.Unicode.GetBytes(strOriginal);
VB.NET
Dim b As Byte() = Encoding.Unicode.GetBytes(strOriginal)
Note: You can adopt different character encoding schemes (ASCII, Unicode etc.) based on your requirement.
8. Convert Byte[] to String – The Encoding.GetString() decodes a sequence of bytes into a string.
C#
// Assuming you have a Byte Array byte[] b
strModified = Encoding.Unicode.GetString(b);
VB.NET
' Assuming you have a Byte Array byte[] b
strModified = Encoding.Unicode.GetString(b)
9. Convert a String to Char[](Char Array) – To convert a String to Char Array, use the String.ToCharArray() which copies the characters in the string to a Unicode character array.
C#
char[] chArr = strOriginal.ToCharArray();
VB.NET
Dim chArr As Char() = strOriginal.ToCharArray()
10. Convert a Char[] to String – A convenient way to convert a character array to string is to use the String constructor which accepts a character array
C#
strModified = new String(chArr);
VB.NET
strModified = New String(chArr)
11. Test if String is null or Zero Length – A simple way to test if a string is null or empty is to use the String.IsNullOrEmpty(string) which returns a Boolean value.
C#
bool check = String.IsNullOrEmpty(strOriginal);
VB.NET
Dim check As Boolean = String.IsNullOrEmpty(strOriginal)
Create a String of characters accepted from user -
12. Convert the Case of a String – The String class contains methods to convert a string to lower and upper cases. However, it lacks a method to convert a string to Proper Case/Title Case. Hence we will use the ‘TextInfo’ class to do the same.
C#
System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;
// Lower Case
MessageBox.Show(textInfo.ToLower(strOriginal));
// Upper Case
MessageBox.Show(textInfo.ToUpper(strOriginal));
// Proper Case
MessageBox.Show(textInfo.ToTitleCase(strOriginal));
VB.NET
Dim cultureInfo As System.Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture
Dim textInfo As System.Globalization.TextInfo = cultureInfo.TextInfo
' Lower Case
MessageBox.Show(textInfo.ToLower(strOriginal))
' Upper Case
MessageBox.Show(textInfo.ToUpper(strOriginal))
' Proper Case
MessageBox.Show(textInfo.ToTitleCase(strOriginal))
13. Count the occurrences of words in a String – You can adopt multiple ways to find the occurrence of a word in a string. One of them is to use the String.IndexOf() which is one of the ways of finding the occurrence of the word. In VB.NET, use String.InStr().
Another simple way is to use ‘Count’ property of the Regex.Matches() collection. However this method is slow. We will explore both these methods in the sample.
C#
// Using IndexOf
int strt = 0;
int cnt = -1;
int idx = -1;
strOriginal = "She sells sea shells on the sea shore";
string srchString = "sea";
while (strt != -1)
{
strt = strOriginal.IndexOf(srchString, idx + 1);
cnt += 1;
idx = strt;
}
MessageBox.Show(srchString + " occurs " + cnt + " times");
// Using Regular Expression
System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(srchString);
int count = rex.Matches(strOriginal).Count;
MessageBox.Show(srchString + " occurs " + count + " times");
VB.NET
' Using IndexOf
Dim strt As Integer = 0
Dim cnt As Integer = -1
Dim idx As Integer = -1
strOriginal = "She sells sea shells on the sea shore"
Dim srchString As String = "sea"
Do While strt <> -1
strt = strOriginal.IndexOf(srchString, idx + 1)
cnt += 1
idx = strt
Loop
MessageBox.Show(srchString & " occurs " & cnt & " times")
' Using Regular Expression
Dim rex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(srchString)
Dim count As Integer = rex.Matches(strOriginal).Count
MessageBox.Show(srchString & " occurs " & count & " times")
14. Insert Characters inside a String – The String.Insert() inserts text at a specified index location of a string. You can insert either a character or a string at a given index location. For eg: We will insert a string “very” at index 26 in string strOriginal.
C#
strModified = strOriginal.Insert(26, "very ");
MessageBox.Show(strModified);
VB.NET
strModified = strOriginal.Insert(26, "very ")
MessageBox.Show(strModified)
15. Replace characters in a String – The String.Replace() removes characters from a string and replaces them with a new character or string.
C#
strModified = strOriginal.Replace("come handy", "be useful");
MessageBox.Show(strModified);
VB.NET
strModified = strOriginal.Replace("come handy", "be useful")
MessageBox.Show(strModified)
So those were 15 common string operations that we saw in this article. In the next article, we will explore some more string operations that are used commonly in projects. I hope this article was useful and I thank you for viewing it.

Wednesday, November 26, 2008

A DetailsView Control for ASP.NET (Putting It All Together)

Putting It All Together

Let's write a page that provides a master/detail view of the Customers table in the Northwind database using a DataGrid and a DetailsView control. The page is shown in Figure 5 below.



Figure 5. A sample page to demonstrate master/details view

The following code snippet illustrates a possible handler for the UpdateCommand event fired when the user clicks to save changes made to a record. For simplicity, the handler saves only the Country field, but the mechanism shown can easily be extended to any other field.

Private Sub DetailsView1_UpdateCommand( _
ByVal sender As System.Object, _
ByVal e As Expoware.DetailsViewUpdateEventArgs) _
Handles DetailsView1.UpdateCommand
' Prepare the update statement (only field Country)
Dim cmdText As String = "UPDATE customers SET country=@country " + _
"WHERE customerid=@customerid"
Dim conn As New SqlConnection("...")
Dim cmd As New SqlCommand(cmdText, conn)
cmd.Parameters.Add("@country", e.DataItems("country"))
cmd.Parameters.Add("@customerid", e.DataItems("customerid"))

' Execute the statement
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()

' Continue update
e.NewMode = e.CurrentMode

' Reload and refresh data
BindData()
End Sub

Note the use of the DataItems collection to retrieve field values as the user edited them in the form

Move Over DataGrid, There's a New Grid in Town!

http://msdn.microsoft.com/en-us/magazine/cc163933.aspx

This article is based on the May 2004 Technology Preview of ASP.NET 2.0. All information herein is subject to change.



This article discusses:
  • The ASP.NET 2.0 GridView, FormView, and DetailsView
  • Differences between the DataGrid and the GridView
  • The programming interfaces of these controls
  • How to achieve master/detail views
This article uses the following technologies:
ASP.NET, ASP.NET 2.0, C#



Code download available at:
GridView.exe
(124 KB)
Browse the Code Online

Letter/Alphanumeric Based Paging in ASP.NET


Letter/Alphanumeric Based Paging in ASP.NET
By Joseph S. Keller
The original post is here :

http://www.codeproject.com/KB/aspnet/letterbasedpaging.aspx

Saturday, November 15, 2008

ASP.NET Site-Map Security Trimming




A common security requirement for Web sites is to allow only some members or other authenticated users to see certain pages. ASP.NET role management provides a way to restrict access to Web files based on security roles. Site-map security trimming provides a way to hide navigational links in a site map, also based on security roles. For information about role-base security, see Understanding Role Management [ http://msdn.microsoft.com/en-us/library/5k850zwb.aspx ] .


Consider the following navigational structure, which is displayed in an ASP.NET page.

Home

Products
Hardware
Software
Discounts
Services
Training
Consulting
Support


Clients who are not members of a role called Customers are restricted from viewing the Support Web page by an ASP.NET access rule that is configured for the Support.aspx page.


To hide the Support link in the navigational display, configure the site-map provider in the Web.config file to enable security trimming. No additional changes are needed because the application will use ASP.NET URL authorization and file authorization to hide the link to the Support page. The XmlSiteMapProvider [ http://msdn.microsoft.com/en-us/library/system.web.xmlsitemapprovider.aspx ] control that is included with ASP.NET version 2.0 automatically performs authorization checks against each site-map node by using the URL- and file-authorization features.



If you want show the Support link to clients who are not in the Customers role, you can use the roles attribute in the site-map node for the Support.aspx file. The roles attribute expands access to a site-map node beyond the level of access that URL authorization and file authorization grant.


The following code example sets the roles attribute for the Support page to Customers. After enabling security trimming, this setting allows users in the Customers role to view the navigation link to the Support page, even if they are not permitted to view the actual file by URL authorization or file authorization.

<?xml version="1.0" encoding="utf-8" ?>


<siteMap>
<!-- other <siteMapNode> elements -->
<siteMapNode title="Support" description="Support"
url="~/Customers/Support.aspx" roles="Customers" />
</siteMap>

Users who are not members of the Customers role would see the following navigational structure if they are restricted from viewing the Support page because of URL- or file-authorization rules.

Home

Products
Hardware
Software
Discounts
Services
Training
Consulting

Enabling Security Trimming


Security trimming works in conjunction with ASP.NET roles. Therefore, pages must be restricted by using access rules (allow and deny elements) for security trimming to work. For more information about access rules, see Managing Authorization Using Roles [ http://msdn.microsoft.com/en-us/library/9ab2fxh0.aspx ] .


Security trimming is not enabled by default, and it cannot be enabled programmatically; it can only be set in the Web.config file. This is also true for any custom class that inherits from the SiteMapProvider [ http://msdn.microsoft.com/en-us/library/system.web.sitemapprovider.aspx ] class.


To enable security trimming, you need to configure a siteMap Element (ASP.NET Settings Schema) [ http://msdn.microsoft.com/en-us/library/1e333zt4.aspx ] element in your Web.config file. If your site map uses the default ASP.NET site-map provider, then the Web.config file might not contain a siteMap Element (ASP.NET Settings Schema) [ http://msdn.microsoft.com/en-us/library/1e333zt4.aspx ] element, in which case you will need to add one. The following code example adds the default site-map provider and enables security trimming.

<system.web>


<!-- …other configuration settings -->
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>
<add name="XmlSiteMapProvider"
description="Default SiteMap provider."
type="System.Web.XmlSiteMapProvider "
siteMapFile="Web.sitemap"
securityTrimmingEnabled="true" />
</providers>
</siteMap>

</system.web>




The security-trimming feature uses URL authorization on each request to determine whether a user has access to a URL that is associated with a siteMapNode element. This extra work reduces performance depending on the number of nodes that are being authorized. When security trimming is enabled, you can use the following methods to improve performance:



  • Limit the number of nodes in the site-map file Site-map files with more than 150 nodes can take substantially longer to perform security-trimming operations.


  • Set the roles attribute explicitly on siteMapNode elements Note that setting the roles attribute to a wildcard character, or asterisk (*), should be used only for nodes that can safely be displayed to any client. The presence of a roles attribute allows ASP.NET to bypass URL authorization for the URL that is associated with the siteMapNode when a user belongs to one of the roles that is listed in the attribute.




To prevent the unintended trimming of child site-map nodes, configure authorization rules and roles attributes carefully. Consider the following navigational structure, which is displayed in an ASP.NET page.

Home

Products
Hardware


The URL- or file-authorization rules set on the Products.aspx file should not be more restrictive than the authorization rules that are set on the Hardware.aspx file. Otherwise, the Hardware link will be hidden from users who should be able to view it because the parent link to Products will be hidden. To expose the hidden links, add to both site-map nodes a roles attribute that lists the neglected ASP.NET roles.



It is recommended that the root node in a site map allow everyone access. To do this, set the roles attribute to an asterisk (*), or wildcard character, as shown in the following code example.

<?xml version="1.0" encoding="utf-8" ?>

<siteMap>
<siteMapNode title="Home" description="Home"
url="default.aspx" roles="*">
<!-- other <siteMapNode> elements -->

</siteMapNode>
</siteMap>


In a site map, you can reference URLs that are outside of your Web application. Access to a URL outside of the application cannot be tested by ASP.NET. Therefore, if you enable security trimming, the site-map node will not be visible unless you set the roles attribute to an asterisk (*), which enables all clients to view the site-map node without first testing access to the URL.



You can use multiple site maps together to define the navigation structure for a single Web site. For example, a Web.sitemap file is similar to a Web.config file because it can be split up and placed in different folders.


Site maps are linked to each other by referencing a child site-map file or provider in the siteMapFile or provider attribute of a SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] object in the parent site map.



The following code example illustrates a site-map node that references another site map.

<?xml version="1.0" encoding="utf-8" ?>

<siteMap>

<!-- other <siteMapNode> elements -->
<siteMapNode siteMapFile="~/Customers/Customers.sitemap"
securityTrimmingEnabled="true" />

</siteMap>





You can use navigation controls to add site navigation to your pages with little or no code, but you can also work with site navigation programmatically. When your Web application runs, ASP.NET exposes a SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] object that reflects the site-map structure. All of the members of the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] object are static. The SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] object, in turn, exposes a collection of SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] objects that contain properties for each node in the map. This is because, when you use the SiteMapPath [ http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sitemappath.aspx ] control, the control works with the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] and SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] objects to render the appropriate links automatically.



You can use the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] , SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] , and SiteMapProvider [ http://msdn.microsoft.com/en-us/library/system.web.sitemapprovider.aspx ] objects in your own code to traverse the site-map structure or create a custom control to display site-map data. You cannot write to the site map, but you can alter site-map nodes in the instance of the object. For more information, see How to: Programmatically Modify Site-Map Nodes in Memory [ http://msdn.microsoft.com/en-us/library/ms178425.aspx ] or How to: Programmatically Enumerate Site-Map Nodes [ http://msdn.microsoft.com/en-us/library/ms178424.aspx ] .



ASP.NET uses the default site-map provider, XmlSiteMapProvider [ http://msdn.microsoft.com/en-us/library/system.web.xmlsitemapprovider.aspx ] , to read the Web.sitemap file. If you want to store site-map information in a location other than the site-map file, you can create your own site-map provider and configure your application to call the custom provider. The site-map provider is configured in the Web.config file. When the application runs, ASP.NET will invoke your provider, which can retrieve site-map information as needed. ASP.NET then creates and populates the SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] objects based on the information that your provider returns. These objects can be programmatically accessed by using the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] class. For more information, see Implementing ASP.NET Site-Map Providers [ http://msdn.microsoft.com/en-us/library/ms178431.aspx ] .

ms178428.alert_security(en-us,VS.90).gifSecurity Note:



Implementing a custom site-map provider that stores site-map data in a file with a file name extension other than .sitemap is a potential security risk. By default, ASP.NET is configured to protect files with known file name extensions — such as .sitemap — from being downloaded by a client. To help protect your data, place any custom site-map data files that have a file name extension other than .sitemap in the App_Data folder. For more information, see

Securing ASP.NET Site Navigation [ http://msdn.microsoft.com/en-us/library/ms227425.aspx ] .


When enabled, security trimming affects the behavior of some of the members in the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] , SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] , and SiteMapNodeCollection [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnodecollection.aspx ] classes. When using these classes, you will see the following behavior:



  • A null is returned by a site navigation API member if it attempts to reference a site-map node that the user does not have the security rights to see. For example, the CurrentNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.currentnode.aspx ] , NextSibling [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.nextsibling.aspx ] , ParentNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.parentnode.aspx ] , and PreviousSibling [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.previoussibling.aspx ] properties will return a null if the properties attempt to return a site-map node that is restricted.



  • If a site navigation API member needs to traverse the tree of site-map nodes, any site-map node that the user is not allowed to see is excluded from the traversal. For example, when the ChildNodes [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.childnodes.aspx ] method runs, the collection of nodes is filtered to include only those nodes that the user is allowed to see. In the case of API members that need to keep track of node paths, such as the Clone [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.clone.aspx ] or IsDescendantOf [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.isdescendantof.aspx ] methods, the paths end at restricted nodes. This can result in cloning operations returning a reduced number of nodes. It can also result in the IsDescendantOf [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.isdescendantof.aspx ] method returning a value of false even though structurally a node might actually be a descendant of the requested node.



  • An InvalidOperationException [ http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx ] exception is returned if a site navigation API member references a root node that the user does not have the security rights to see. Only the root node of the root provider needs to be accessible to all users, which prevents an exception from being thrown when first obtaining the SiteMap [ http://msdn.microsoft.com/en-us/library/system.web.sitemap.aspx ] object.


  • A ConfigurationException [ http://msdn.microsoft.com/en-us/library/system.configuration.configurationexception.aspx ] exception is thrown if a SiteMapNode [ http://msdn.microsoft.com/en-us/library/system.web.sitemapnode.aspx ] object references another site-map file or provider incorrectly.

ms178428.alert_note(en-us,VS.90).gifNote:



In a site map, you can reference URLs that are outside of your Web application. Access to a URL outside of the application cannot be tested by ASP.NET. Therefore, if you enable security trimming, the site-map node will not be visible unless you set the roles attribute to an asterisk (*), which enables all clients to view the site-map node without first testing access to the URL.

Tasks

Walkthrough: Filtering Site-Map Nodes Based on Security Roles [ http://msdn.microsoft.com/en-us/library/ms178429.aspx ]

Concepts

Securing ASP.NET Site Navigation [ http://msdn.microsoft.com/en-us/library/ms227425.aspx ]
Securing Data Access [ http://msdn.microsoft.com/en-us/library/ms178375.aspx ]

Other Resources

Managing Authorization Using Roles [ http://msdn.microsoft.com/en-us/library/9ab2fxh0.aspx ]
ASP.NET Application Security in Hosted Environments [ http://msdn.microsoft.com/en-us/library/ssd9kbbc.aspx ]


Tags:














Counter