Professional Documents
Culture Documents
0 Hands On Labs
Scenario
This lab demonstrates the use of the Enterprise Library Data Access
Application Block. It requires a (local)\SQLEXPRESS instance of SQL Server
or SQL Server Express.
First step
only attribute warning appear, then select the file in Window Explorer.
Choose File | Properties and uncheck the Read only checkbox at the
bottom of the window.
1. Select the MainForm.cs file in the Solution Explorer. Select the View
| Designer menu command.
• Microsoft.Practices.EnterpriseLibrary.Common.dll, and
• Microsoft.Practices.EnterpriseLibrary.Data.dll.
2. Select the MainForm.cs file in the Solution Explorer. Select the View
| Code menu command.
3. Add the following namespace inclusion to the list of namespaces at the
top of the file:
using Microsoft.Practices.EnterpriseLibrary.Data;
Database db = null;
db = DatabaseFactory.CreateDatabase("QuickStarts
Instance");
MessageBox.Show(message);
}
Database db = null;
db = DatabaseFactory.CreateDatabase();
DataSet ds = db.ExecuteDataSet(
CommandType.Text,
"SELECT * From Customers");
dataGrid1.DataSource = ds.Tables[0];
}
Note: This time we have not passed a database instance name to the
CreateDatabase method. Rather the default database defined in the
application configuration file will be used.
3. Select the App.config file in the Solution Explorer. Select the View |
Open With… menu command. The OpenWith dialog is displayed.
Click the Add button.
This name has to match the name you used in the code. This is
how you can create an alias in code that maps to the concrete
database instance you wish to use at runtime.
9. Select the Database node for this connection string. Change the
Value property on the right hand side to EntLibQuickStarts.
10. Similarly, select the Server node, and set its Value to
"(local)\SQLEXPRESS".
11. Select the Data Access Application Block node. Set the
DefaultDatabase property is to the QuickStarts Instance.
12. Select the File | Save All menu command to save the application
configuration. Close the Enterprise Library Configuration tool.
First step
1. Run the batch file SetUpEx02.bat, which can be found in the lab
directory:
labs\cs\Data Access\exercises\ex02\DbSetup.
This adds a set of categories that you can use to filter the set of
products you retrieve and manipulate.
using Microsoft.Practices.EnterpriseLibrary.Data;
2. Add the following private field to the form, as you'll re-use this
database instance in multiple places.
Note that you can hold onto this, as the Database instance does not
represent an open connection, but instead represents a reference to a
database.
this.cmbCategory.Items.Add(item);
}
}
if (this.cmbCategory.Items.Count > 0)
this.cmbCategory.SelectedIndex = 0;
}
Note: You are not doing any connection management here, but it is
very important to Dispose the data reader returned. This is
accomplished by the using statement in the code above. When the
data reader is disposed, the underlying DbConnection is also closed.
Category selectedCategory =
(Category)this.cmbCategory.SelectedItem;
if (selectedCategory == null)
return;
There are two methods on the Database class that populate a DataSet;
ExecuteDataSet and LoadDataSet. ExecuteDataSet returns a
newly created DataSet, while LoadDataSet populates an existing one.
1. Find the btnSave_Click method. Insert the following code, which will
update the database based on any changes in the dataset.
Select a category from the drop down, and observe how it loads and
saves the data.
More information
First step
• System.Configuration.dll.
3. Select the Program.cs file in the Solution Explorer. Select the View |
Code menu command. Add the following namespace inclusion to the
list of namespaces at the top of the file:
using System.Configuration;
Scenario
This lab demonstrates the use of the Enterprise Library Caching Block. It
requires a (local)\SQLEXPRESS instance of SQL Server or SQL Server
Express.
First step
1. Run the batch file SetCachingHOL.bat, which can be found in the lab
directory:
labs\cs\Caching\setup.
This adds a set of employees which you will use to create an employee
directory.
• Microsoft.Practices.EnterpriseLibrary.Caching.dll.
2. Select the EmployeeService.cs file in the Solution Explorer. Select
the View | Code menu command.
3. Add the following namespace inclusion to the list of namespaces at the
top of the file:
using Microsoft.Practices.EnterpriseLibrary.Caching;
cache.Add(employeeId.ToString(), photoData);
}
// No data found.
if (photoData == null)
return null;
This method uses the factory model, as with the rest of Enterprise
Library, to create a new CacheManager instance. This can be purely in-
memory, or can be backed by a physical storage medium, depending
on configuration.
Items can be retrieved from the cache by using an indexer, and can be
added (or replaced) by using the Add method. The overload used in
this method does not specify an expiration policy.
5. Add the following code to the ClearCache method, to allow the form
to request the service to get new data.
2. Select the App.config file in the Solution Explorer. Select the View |
Open With… menu command. The OpenWith dialog is displayed.
Click the Add button.
The App.config file now contains the caching configuration settings you
added previously. Notice the backing store is Null Storage. That is,
the cache will be stored in-memory.
First step
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
{
EmployeeDataProvider dataProvider = new
EmployeeDataProvider();
dsEmployees = dataProvider.GetEmployees();
// Expire in 2 days
AbsoluteTime expiry = new AbsoluteTime(new
TimeSpan(2, 0, 0, 0));
cache.Add(CACHE_KEY, dsEmployees,
CacheItemPriority.High, null,
new ICacheItemExpiration[] { expiry });
}
return dsEmployees;
}
This code will only attempt to contact the database when the
application is online.
This contact details are loaded into the cache using an overload of the
Add method which allows the specifying of cache item priority, a cache
item removal callback (which must be serializable for persistent
caches), and a set of expiration policies. In this case, you do not want
to allow our users to keep the employee data on their machines for
more than 2 days without checking in. This helps to reduce the
possibility of an employee taking the contact data to another company,
as the caching infrastructure will remove the contents once they have
expired.
cache.Add(employeeId.ToString(), photoData);
}
// No data found.
if (photoData == null)
return null;
1. Select the App.config file in the Solution Explorer. Select the View |
Open With… menu command. Select Enterprise Library
Configuration and click the OK button.
2. Select the Caching Application Block | Cache Managers | Cache
Manager node. Select the Action | New | Isolated Storage menu
command.
The Partition Name allows multiple caches to share the same Isolated
storage location.
4. Save the configuration by selecting the menu File | Save All. Close
the configuration console.
Browse to a few of the employees, to load the cache with data, but
don't browse all the employees (e.g. don't browse to Fuller,
Dodsworth, or Callahan, so that their images are not cached). Close
the application when you are finished browsing.
First step
if (dsEmployees == null)
return;
cache.Add(employee.EmployeeID.ToString(), photoData);
}
}
}
PopulateCacheDelegate mi = new
PopulateCacheDelegate(PopulateCache);
mi.BeginInvoke(null, null);
}
The Caching Block guarantees us thread safety when using the Cache,
so it is safe to access from multiple threads at the same time.
if (tempDataset != null)
this.EmployeesDataSet.Merge(tempDataset);
Don't bother browsing to any other employees, but rather wait for at
least 10 seconds then exit the application.
More Information
Scenario
This lab demonstrates the use of the Enterprise Library Logging Application
Block.
First step
The EnoughPI application calculates the digits of pi (π, the ratio of the
circumference of a circle to its diameter). Enter your desired precision
via the NumericUpDown control and click the Calculate button. Be
prepared to wait if you want more than 500 digits of precision.
Adding Logging
• Microsoft.Practices.EnterpriseLibrary.Logging.dll.
2. Select the Calc\Calculator.cs file in Solution Explorer. Select the
View | Code menu command.
using Microsoft.Practices.EnterpriseLibrary.Logging;
Logger.Write(log);
if (Calculated != null)
Calculated(this, args);
}
Create a new LogEntry, set parameters, then use the Logger to write
the entry to one or more TraceListeners.
Notes:
•You have used constants for the Category and Priority rather
than use hard-coded tags and integers (see Constants.cs in the
EnoughPI.Logging project).
4. Log the calculation progress by adding the following code to the
OnCalculating method in the Calculator.cs file.
if (Calculating != null)
Calculating(this, args);
if (args.Cancel == true)
{
// TODO: Log cancellation
Logger.Write("Calculation cancelled by user!",
Category.General, Priority.High);
}
}
Notes:
if (CalculatorException != null)
CalculatorException(this, args);
}
Notes:
2. Select the App.config file in the Solution Explorer. Select the View |
Open With… menu command. The OpenWith dialog is displayed.
Click the Add button.
This TraceListener will log formatted entries (using the Text Formatter)
to the windows event log.
4. Select the File | Save All menu command to save the application
configuration. Close the Enterprise Library Configuration tool.
Adding Tracing
1. Often you would like to time sections of our application. The Logging
and Instrumentation Application Block includes tracing which allows us
to book-end a section of code and log the execution time.
2. Select the Calc\Calculator.cs file in the Solution Explorer. Select the
View | Code menu command.
try
{
if (digits > 0)
{
// TODO: Add Tracing around the calculation
using (new Tracer(Category.Trace))
{
pi.Append(".");
for (int i = 0; i < digits; i += 9)
{
CalculatingEventArgs args;
args = new CalculatingEventArgs(pi.ToString(), i+1);
OnCalculating(args);
result = pi.ToString();
return result;
}
Often you would like to time sections of our application. Tracing allows
us to book-end a section of code and log the execution time.
The Tracer will stop timing, and log its end trace message, when it is
disposed. The using block guarantees us that Dispose() will be
called on the Tracer at the end of the block. Allowing the Garbage
Collector to dispose of the Tracer will result in incorrect timings.
3. Select the App.config file in the Solution Explorer. Select the View |
Open With… menu command. Select Enterprise Library
Configuration and click the OK button.
4. Select the Logging Application Block node. Set the
TracingEnabled property to True.
The category name "Trace" was used in our code (see Constants.cs in
the EnoughPI.Logging project). Using the ActivityTracing source
level will restrict the trace logging to the start and end log entries only.
9. Right click on the new Trace category, and select the New | Trace
Listener Reference menu command, and set the following property:
10. Select the File | Save All menu command to save the application
configuration. Close the Enterprise Library Configuration tool.
11. Select the Debug | Start Without Debugging menu command to
run the application. Enter your desired precision and click the
Calculate button.
12. You may view the elapsed time for the trace in the trace.log file.
----------------------------------------
Category: Trace
Priority: 5
EventId: 1
Severity: Start
Title:TracerEnter
Machine: TAGGERT
Thread Name:
Extended Properties:
----------------------------------------
----------------------------------------
Category: Trace
Priority: 5
EventId: 1
Severity: Stop
Title:TracerExit
Machine: TAGGERT
Thread Name:
Extended Properties:
----------------------------------------
First step
• Microsoft.Practices.EnterpriseLibrary.Common.dll, and
• Microsoft.Practices.EnterpriseLibrary.Logging.dll.
2. Select the TraceListeners\ConsoleTraceListener.cs file in the
Solution Explorer. Select the View | Code menu command. Add the
following namespaces:
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
[ConfigurationElementType(typeof(CustomTraceListenerData))
]
public class ConsoleTraceListener : CustomTraceListener
{
public ConsoleTraceListener()
: base()
{
}
The Type Selector lists class, from assemblies in the same directory
as the Enterprise Library Configuration tool, which inherit from
CustomTraceListener and have a ConfigurationElementType of
CustomTraceListenerData.
6. Select the Attributes property and click the ellipses to display the
EditableKeyValue Collection Editor.
10. Select the File | Save All menu command, and close the Enterprise
Library Configuration tool.
Note: If you don't close the Enterprise Library Configuration tool you
will get a build error next time you build the EnoughPI.Logging post
build event will fail.
First step
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
[ConfigurationElementType(typeof(CustomFormatterData))]
public class XmlFormatter : LogFormatter
{
private NameValueCollection Attributes = null;
w.WriteStartDocument(true);
w.WriteStartElement(prefix, "logEntry", ns);
w.WriteAttributeString("Priority", ns,
log.Priority.ToString(CultureInfo.InvariantCulture));
w.WriteElementString("Timestamp", ns,
log.TimeStampString);
w.WriteElementString("Message", ns, log.Message);
w.WriteElementString("EventId", ns,
log.EventId.ToString(CultureInfo.InvariantCulture));
w.WriteElementString("Severity", ns,
log.Severity.ToString());
w.WriteElementString("Title", ns, log.Title);
w.WriteElementString("Machine", ns,
log.MachineName);
w.WriteElementString("AppDomain", ns,
log.AppDomainName);
w.WriteElementString("ProcessId", ns, log.ProcessId);
w.WriteElementString("ProcessName", ns,
log.ProcessName);
w.WriteElementString("Win32ThreadId", ns,
log.Win32ThreadId);
w.WriteElementString("ThreadName", ns,
log.ManagedThreadName);
w.WriteEndElement();
w.WriteEndDocument();
return s.ToString();
}
}
}
The log entry will be formatted as XML. Two parameters are expected
(prefix, and namespace).
3. Select the Type property, and click the ellipses to display the Type
Selector dialog.
The Type Selector lists class, from assemblies in the same directory
as the Enterprise Library Configuration tool, which inherit from
LogFormatter and have a ConfigurationElementType of
CustomFormatterData.
5. Select the Attributes property and click the ellipses to display the
EditableKeyValue Collection Editor.
8. Select the File | Save All menu command, and close the Enterprise
Library Configuration tool.
9. Select the Debug | Start Without Debugging menu command to
run the application. Enter your desired precision and click the
Calculate button. The log entries will be displayed in the applications
Console Window.
More information
Scenario
This lab demonstrates the use of the Enterprise
Library Exception Handling Application Block.
First step
• Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll.
2. Select the Puzzler.cs file in the Solution Explorer. Select the View |
Code menu command.
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
{
bool rethrow = ExceptionPolicy.HandleException(ex, "UI
Policy");
if (rethrow)
throw;
MessageBox.Show(string.Format(
"Failed to add word {0}, please contact support.",
txtWordToCheck.Text));
}
}
3. Select the App.config file in the Solution Explorer. Select the View |
Open With… menu command. The OpenWith dialog is displayed.
Click the Add button.
• Name = UI Policy.
The policy name here must match that specified in the code.
Typically you would use constants to help prevent typographical errors,
especially since the exception handling typically is not tested as
thoroughly as normal code paths.
• PostHandlingAction = None.
7. Select the File | Save All menu command to save the application
configuration. Close the Enterprise Library Configuration tool.
Click on Yes in the dialog box warning about the app.config being
modified outside the source editor.
• Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.
dll.
Because one of the goals of the Enterprise Library is to keep the blocks
de-coupled, it is possible to use the Exception Handling block without
needing the Logging block (e.g. by creating your own exception
handler). If you want to use the two blocks together, then you need to
use this assembly, which contains an Exception Handler that logs via
the logging block.
Try adding a number (type a number in the Word to check text box,
and click Add Word) - a MessageBox is displayed with an error
- "Failed to add word …, please contact support".
2. Check the Event Log by using the Event Viewer (Control Panel |
Administrative Tools | Event Viewer). Look at the top of the
Application Log. The exception will be logged.
3. Select the Startup.cs file in the Solution Explorer. Select the View |
Code menu command. Add the following namespace inclusion at the
top of the file:
Application execution begins here. There are two events you can use
to listen for unhandled exceptions:
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
throw ex;
}
if (rethrow)
{
// WARNING: This will truncate the stack of the exception
throw ex;
}
else
{
MessageBox.Show("An unhandled exception occurred and has "
+
"been logged. Please contact support.");
}
}
This method will use the exception handling block, and will also display
valid information if there is a problem with the exception handling
block itself (e.g. missing configuration).
This event handler will use the policy (UI Policy) that you defined
before for the UI layer. In the next exercise you will customize this
policy to allow certain types of exception to "escape" and shut the
application down.
This handler will use a new policy, named Unhandled Policy, which
will set up in the next exercise. The Unhandled Policy should almost
always just log the exception, and not re-throw.
AppDomain.CurrentDomain.UnhandledException +=
new
UnhandledExceptionEventHandler(CurrentDomain_UnhandledE
xception);
Try adding a number (type a number in the Word to check text box
and click Add Word) - a MessageBox is displayed - "An unhandled
exception occurred and has been logged. Please contact support.".
Look in the event log for the logged exception.
First step
Protect the Service's 'Add Word' Functionality with Code Access Security
{
if (!IsWord(wordToAdd))
{
// It is not alphabetic! Throw an exception
throw new ApplicationException(
"Word to add does not consist of alphabetic letters");
}
if (Dict[wordToAdd] == null)
{
Dict.Add(wordToAdd, wordToAdd);
}
return true;
}
This method can now only be executed by a member of the role Grand
PoohBah, an unlikely situation.
• PostHandlingAction = ThrowNewException.
• FormatterType = TextExceptionFormatter,
• LogCategory = General, and
• Title = Security Exception in Service Layer.
Although you have kept the type the same, by creating a new
SecurityException, this will not provide the client any of the stack
information or internal security exception information, which could
compromise security.
• PostHandlingAction = NotifyRethrow.
• FormatterType = TextExceptionFormatter,
• LogCategory = General, and
• Title = Security Exception in UI Layer.
3. Select the File | Save All menu command to save the application
configuration. Close the Enterprise Library Configuration tool.
This time the Exception will be shown three times in the Event Log.
Scenario
This lab demonstrates the use of the Enterprise Library Cryptography Block.
Keeping secrets is both important and difficult. Probably the most common
secrets you wish to keep are connection strings that often include usernames
and passwords, however the task of securing these is handled for us by the
Configuration Application Block and was discussed in the Data Access topic
earlier. This lab looks at securing non configuration data and using hashing
to secure passwords.
First step
1. Select the Chat.cs file in the Solution Explorer. Select the View |
Designer menu command.
The Chat form is used for sending and receiving instant messages.
The top TextBox (gray color) displayed the conversation trace. The
bottom TextBox (white color) is used to send new messages.
Two Chat forms will be opened (called Sam and Toby). Messages can
be passed between these forms. Select the Toby window. Type some
text into the Toby Says TextBox, and click the Send button. Repeat
for the Sam window. Note, the conversation appears in both Chat
forms.
The messages are being sent between the windows as plaintext. You
will use the Cryptography Block to encrypt and decrypt these
communications using a symmetric key.
• Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.dll.
2. Select the Chat.cs file in the Solution Explorer. Select the View |
Code menu command.
using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;
3. Add the following code to the Chat class (added code in bold).
...
this.txtMessages.AppendText(
args.Sender + " says: " + plainText + Environment.NewLine);
}
3. Select the App.config file in the Solution Explorer. Select the View |
Open With… menu command. The OpenWith dialog is displayed.
Click the Add button.
4. The Cryptographic Key Wizard will start. Select the Create a new
key option, and click the Next button.
The wizard will lead you through the process of creating and protecting
a cryptographic key.
5. Click the Generate button to generate a new key. Click the Next
button.
6. Select the Ellipsis (…) button and choose a key file location. For this
lab, the Windows Desktop may prove to be a convenient location.
Select a file name (e.g. ChatterBox.key). Click the Next button.
The key is no longer stored in the configuration file. Each key is stored
in a separate file that is protected with DPAPI.
7. Select User mode, or Machine mode, and click the Finish button.
When you create the key, you choose either machine mode or user
mode to limit access to the key.
Note:
• Name = ChatProvider.
Pass messages between Toby and Sam. The messages are passed
encrypted (see the encrypted messages in the Console), but decrypted
by the receiver.
2. You may or may not have noticed that the application has become a
little less stable now that you are using Cryptographer (hint, try
sending an empty string). you would normally add some code to check
the strings before you try to encrypt or decrypt them. For example you
should check for zero length strings in both the SendMessage and
MessageReceived methods. The MessageReceived method should
also check that the strings you are about to decrypt are a multiple of 4
bytes long and only contain valid Base64 characters. These checks
have been omitted for clarity.
3. Close the application.
1. The best way to handle exceptions is to make sure that they don't
happen in the first place with some guard code. Let's first make sure
that you don't try to encrypt a zero length string.
Select the Chat.cs file in the Solution Explorer. Select the View |
Code menu command. Add the following code to the SendMessage
method.
{
// TODO: Encrypt message
string encrypted =
Cryptographer.EncryptSymmetric(symmProvider, message);
First step
Add a new user named, Elmo. Click the New User button. Enter the
name Elmo, and leave the passwords as the default (P@ssw0rd).
Click the Ok button.
You can see the password in plain text, not what you would like.
type="UserStore.Configuration.UserSettings, UserStore,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</configSections>
<userStore>
<users>
<add name="Elmo" password="P@ssw0rd" />
<add name="Zoe" password="P@ssw0rd" />
</users>
</userStore>
</configuration>
3. Right click on the application configuration file and select the New |
Cryptography Application Block menu command.
7. Select the File | Save All menu command to save the application
configuration. Close the Enterprise Library Configuration Console.
1. Select the UserStore project in the Solution Explorer. Select the Project | Add
Reference … menu command. Select the Browse tab and select the following
assembly located here:
• Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.dll.
2. Select the Security | HashHelper.cs file (in the UserStore project)
in the Solution Explorer. Select the View | Code menu command.
using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;
class HashHelper
{
private HashHelper() { }
...
return hash;
}
Notice the hashing is different in each case, even though the actual
password is the same. The difference is due to the addition of the
'Salt'. Hence, to test the validity of a password we cannot simply
reapply the hashing to the plain text password and string compare to
two hashed values. This is why the Change Password failed earlier.
11. Select the Security | HashHelper.cs file (in the UserStore project)
in the Solution Explorer. Select the View | Code menu command.
return compare;
}
(the default). Use any new password you like (not zero length) and
click the Ok button.
More information
Scenario
This lab demonstrates the use of the Enterprise Library, Security Application
Block.
First step
using System.Web.Security;
return authenticated;
}
6. Select the App.config file in the Solution Explorer. Select the View |
Open menu command.
type="BugSmak.Security.Providers.ReadOnlyXmlMembershipPr
ovider, BugSmak"
description="Read-only XML membership provider"
xmlFileName="Users.xml" />
</providers>
</membership>
...
</system.web>
</configuration>
Once you have a custom membership provider, you can configure your
application to use that provider in the same way that you configure the
application to use an ASP.NET provider. The Membership class will
automatically invoke your custom provider to communicate with your
authentication data source.
7. Select the Users.xml file in the Solution Explorer. Select the View |
Open menu command.
Select the File | Sign Out menu command and attempt to sign in with
an incorrect username or password.
Notes:
The RaiseBug form demands that the user have any of the Developer,
Employee, or Manager roles. Attempting to run the form without the
necessary authorization results in a SecurityException which is
caught by the MainForm (see MainForm.cs).
IIdentity identity;
identity = new GenericIdentity(username,
Membership.Provider.Name);
return authenticated;
}
The roles are retrieved from the Users.xml file via a custom
RoleProvider (ReadOnlyXmlRoleProvider.cs), and a new principal
created which contains the users identity and roles.
3. Select the App.config file in the Solution Explorer. Select the View |
Open menu command.
<roleManager enabled="true"
defaultProvider="ReadOnlyXmlRoleProvider">
<providers>
<add name="ReadOnlyXmlRoleProvider"
type="BugSmak.Security.Providers.ReadOnlyXmlRoleProvider,
BugSmak"
description="Read-only XML role provider"
xmlFileName="Users.xml" />
</providers>
</roleManager>
</system.web>
</configuration>
Sign-in as Tom, Dick and Harry in turn to confirm the correct setup
of the role provider.
First step
2. Select the App.config file in the Solution Explorer. Select the View |
Open With… menu command. The OpenWith dialog is displayed.
Click the Add button.
8. Select the Security Application Block node and set the following
property:
9. Select the File | Save All menu command to save the configuration.
Close the Enterprise Library Configuration tool.
Notes:
•For compile-time checking, the rule names (e.g. "Raise Bug") are
mapped to constants in the Constants.cs file.
2. Select the Project | Add Reference … menu command. Select the
Browse tab and select the following assembly located here.
•Microsoft.Practices.EnterpriseLibrary.Security.dll.
3. Select the Security \ SecurityHelper.cs file in the Solution Explorer.
Select the View | Code menu command.
using Microsoft.Practices.EnterpriseLibrary.Security;
ruleProvider =
AuthorizationFactory.GetAuthorizationProvider();
authorized =
ruleProvider.Authorize(Thread.CurrentPrincipal, rule);
return authorized;
}
Sign-in as Tom, Dick and Harry in turn to confirm the correct setup
of the role provider.
More information