Tuesday, September 15, 2009

Create Custom RoleProvider for ASP.NET Role Permissions and Security


Note: It is recommended that you read the following post, Create Custom Membership Provider for ASP.NET Website Security, before reading this tutorial for a complete understanding of the topic and scenario.
Most ASP.NET Applications implement roles to deal with role permissions and security. Often the permissions a user has on the website is based on the roles that the user is assigned to. User roles might be anything from “Guest”,”User”, “Admin”, etc.
Just like with a Custom MembershipProvider in ASP.NET, one can create a Custom RoleProvider to be used by the web application. A Custom RoleProvider inherits from the abstract base class RoleProvider and has a number of optional methods and properties that can be overrriden. However, as with a Custom MembershipProvider, implementing the details of a method or property is completely optional depending on the needs of the application. In this tutorial I am going to create a simple roleprovider, called SimpleRoleProvider, that shows just how easy it is to get started with a custom roleprovider.


In my case, I am only going to implement one method, GetRolesForUser, which is all I need to provide role based security in conjunction with the Custom MembershipProvider I built in the following tutorial:
Create Custom Membership Provider for ASP.NET Website Security
First thing first, I need to enable the RoleManager in web.config and tell it that my SimpleRoleProvider Class will now be the provider responsible for provider role information:


<'rolemanager enabled="true" defaultprovider="SimpleRoleProvider">
<'providers>

<'providers>
<'clear>
<'add name="SimpleRoleProvider" type="Hayden.RoleProviders.SimpleRoleProvider, Hayden.RoleProviders">
<'/add>
<'/clear>'

I next need to create the Custom RoleProvider, where I essentially just want to give myself, with the username “Dave”, administrator privileges on the website. Normally you would not hardcode the roles in code, but again, this is an example of how easy it is to get started with a Custom RoleProvider. Here is my SimpleRoleProvider with all other methods and properties not shown throwing a NotImplementedException:

public class SimpleRoleProvider : RoleProvider
{
public override string[] GetRolesForUser(string username)
{
List roles = new List();
roles.Add("Guest");
if (username.Equals("Dave"))
roles.Add("Admin");
return roles.ToArray();
}
}

Everyone is given a "Guest" Role, but only the username "Dave" has an additional role of "Admin".
To test this out, let's add security on Page1.aspx that only allows users in the “Admin” Role to view / use the page:

[PrincipalPermission(SecurityAction.Demand, Role = "Admin")]
public partial class Page1 : System.Web.UI.Page
{
// ...
}

When a user logs in and gets redirected to Page1.aspx, the GetRolesForUser Method in SimpleRoleProvider will be called to verify the user is assigned to the “Admin” Role. If so, the page works fine. If not, a SecurityException will be thrown, not allowing the page to be viewed. In the case shown above, the page will only be available to username “Dave”.
And that is the 5 minute review on how to get started with a Custom RoleProvider for your ASP.NET Websites. ASP.NET comes with a few built-in providers, like SqlRoleProvider, but it is just as easy to role your own.

by David Hayden ( Microsoft MVP C# ), Filed: ASP.NET 2.0


Monday, September 7, 2009

ASP.NET MVC

ASP.NET was a huge shift when it first arrived, not just in terms of the
brand-new .NET multilanguage managed code platform (which was a
landmark in its own right), but in that it sought to close the gap between
stateful, object-oriented Windows Forms development and stateless,
HTML-oriented web development.Microsoft attempted to hide both HTTP (with its intrinsic statelessness) and HTML (which, at the time, was unfamiliar to many developers) by modeling a user interface (UI) as a server-side hierarchy of control objects.

Each control kept track of its own state across requests (using the ViewState facility), automatically rendered itself as HTML when needed, and automatically connected client-side events (e.g., a button click) with the corresponding server-side event handler code. In effect, WebForms is a giant abstraction layer aimed to deliver a classic event-driven GUI over the Web. Developers no longer had to work with a series of independent HTTP requests and responses, as we did with earlier technologies; we could now think in terms of a stateful UI. We could “forget” about the Web, build UIs using a drag-and-drop designer, and imagine that everything happened on the server.

What’s Wrong with Traditional ASP.NET?
Traditional ASP.NET was a fine idea, and a thrilling prospect at first, but of course reality turned out to be more complicated. Over the years, realworld use of WebForms uncovered a range of weaknesses:
ViewState: The actual mechanism of maintaining state across requests(ViewState) often results in giant blocks of data being transferred between client and server. It can reach hundreds of kilobytes in many real-world applications, and it goes back and forth with every request, frustrating site visitors with a long wait each time they click a button or try to move to the next page on a grid. ASP.NET AJAX suffers this just as badly,1 even though bandwidth-heavy page updating is one of the main problems that Ajax is supposed to solve.

Page life cycle: The mechanism of connecting client-side events with serverside event handler code, part of the page life cycle, can be extraordinarily complicated and delicate. Few developers have success manipulating the control hierarchy at runtime without getting ViewState errors or finding that some event handlers mysteriously fail to execute.

Limited control over HTML: Server controls render themselves as HTML, but not necessarily the HTML you want. Not only does their HTML often fail to comply with web standards or make good use of CSS, but the system of server controls generates unpredictable and complex ID values, which are hard to access using JavaScript.

False sense of separation of concerns: ASP.NET’s code-behind model provides a means to take application code out of its HTML markup and into a separate code-behind class. This has been widely applauded for separating logic and presentation, but in reality, developers are encouraged to mix presentation code (e.g., manipulating the server-side control tree) with application logic (e.g., manipulating database data) in these same monstrous code-behind classes. Without better separation of concerns, the end result is often fragile and unintelligible.

Untestable: When ASP.NET’s designers first set out their platform, they could not have anticipated that automated testing would become such a mainstream part of software development as it is today. Not surprisingly, the architecture they designed is totally unsuitable for automated testing.

Model-View-Controller Architecture
ASP.NET MVC provides greatly improved separation of concerns thanks to its adoption of MVC architecture. The MVC pattern isn’t new—it dates back to 1978 and the Smalltalk project at Xerox PARC—but it’s gaining enormous popularity today as an architecture for web applications, perhaps because of the following:
- User interaction with an MVC application naturally follows a cycle: the user takes an action, and then in response the application changes its data model and delivers an updated view to the user. And then the cycle repeats. This is a very convenient fit for web applications delivered as a series of HTTP requests and responses.
- Web applications already necessitate combining several technologies (e.g., databases, HTML, and executable code), usually split into a set of tiers or layers, and the patterns that arise naturally map onto the concepts in MVC.

Extensibility
The MVC Framework is built as a series of independent components—satisfying a .NET interface or built on an abstract base class—so you can easily replace the routing system, the view engine, the controller factory, or any other framework component, with a different one of your own implementation. In fact, the framework’s designers set out to give you three options for each MVC Framework component:
1. Use the default implementation of the component as it stands (which should be enough for most applications).
2. Derive a subclass of the default implementation to tweak its behavior.
3. Replace the component entirely with a new implementation of the interface or abstract base class.

Testability
MVC architecture gives you a great start in making your application maintainable and testable, because you will naturally separate different application concerns into different, independent software pieces. Yet the ASP.NET MVC designers didn’t stop there. They took the framework’s component-oriented design and made sure each separate piece was ideally structured for automated testing.

Tight Control over HTML
The MVC Framework recognizes the importance of producing clean, standards-compliant markup. Its built-in HTML helper methods do of course produce XHTML-compliant output, but there’s a bigger change of mindset at work. Instead of spewing out huge swathes of barely readable HTML code to represent what should be simple UI elements like lists, tables, or string literals, the MVC Framework encourages you to craft simple, elegant markup styled with CSS.

Powerful New Routing System
Today’s web developers recognize the importance of using clean URLs. It isn’t good for business to use incomprehensible URLs like /App_v2/User/Page.aspx?action=show%20prop&prop_id=82742—it’s far more professional to use /to-rent/chicago/2303-silver-street.

Comparisons with ASP.NET WebForms
- WebForms takes the view that UIs should be stateful, and to that end adds a sophisticated abstraction layer on top of HTTP and HTML, using ViewState and postbacks to create the effect of statefulness. This makes it suitable for drag-and-drop Windows Forms–style development, in which you pull UI widgets onto a canvas and fill in code for their event handlers.
- MVC embraces HTTP’s true stateless nature, working with it rather than fighting against it. It requires you to understand how web applications actually work; but given that understanding, it provides a simple, powerful, and modern approach to writing web applications with tidy code that’s easy to test and maintain over time, free of bizarre complications and painful limitations.

Wednesday, September 2, 2009

Linq to SQL - SubmitChanges() problem with XElement fields

Problem:

When I change an XElement field in a Linq to SQL class and call SubmitChanges on the data context, it doesn't update. Linq to SQL seems to just flat out ignore XElement's change notifications.

Solution:

LINQ to SQL only understands changes by comparing the current and original values of data fields. When you first modify an entity, L2S makes a backup copy of the entity by copying all the field values into a new object instance. It does not do a deep copy, so values like XElements are copied over by reference. L2S treats all valus in fields as immutable, therefore the value is only ever considered changed for a reference type if the reference has actually changed. In your example, the XElement itself never changes but its contents do. L2S will not see the difference, since both current and original values of the field refer to the same XElement instance.

The same problem exists if you model binary data using a byte array. Since an array is mutable, if you change the contents of the array without changing the array itself, L2S will not see it.

The solution is to create an entirely new XElement object (based on the original) and assign it to the field in the entity.

Let's se an example:

// retrieve XElement from database
InterviewTbl dbInterviewData = _context.InterviewTbls.SingleOrDefault(c => c.UserAccountId == 2);

// create new XElement passing to constructor the XElement retrieved from database
XElement element = new XElement(dbInterviewData);

//modify the new XElement
element.Element("nameOfNode").Remove();

//Assing the new XElement to the database XElement
dbInterviewData.InterviewData = element;

//submit changes
_context.SubmitChanges();

Tuesday, September 1, 2009

Code review and Source Safe


It has been over three years since I worked on a team that had any notion of a structured code review. I previously worked for Microsoft and the team I was part of had a sophisticated process in place to ensure the stability of the code base. This process included a 10 step checklist that a developer had to walk through before they were allowed to check changes into the repository. It didn't matter if you changed only a single line of code, only added a few unit tests or completely rewrote the whole application, you still had to follow the same process before you changes could be committed. One of the items on the checklist was for getting your code peer reviewed. And it usually went something like this

1. The developer sends out an email to 3 other developers and quality assurance members referencing the number of the bug/feature they were working on (no changes were allowed to be made to the codebase without a bug number), and a command (something like "windiff $\vssroot\src \\developers_machine\src") that allowed the recipients of the email to bring up the changes in Windiff on their local PC

2. The developer waited for the team to review the changes, then upon receiving feedback (from at least 2 of them) the developer addressed the items in the email, either saying they incorporated the feedback into the code, or explained why they didn't feel the change was necessary

3. The developer checked in the changes and put the names of the reviewers on the bug for reference

Looking back, there are a number of aspects about this process that I really liked. First, the review is done before the code is actually checked-in - theoretically stopping bad code from infecting the rest of the codebase. Second, at least 2 other people have to review at the code before it makes it in, and finally, 3 people are responsible for the changes since there names are all linked to the bug. Now, at Microsoft we followed this process because we had a large team and any amount of instability lead to unproductive employees, but this level of sophistication would be over-kill for most other development shops. That being said, I don't think it is ok for any size development team (my team is guilty of this too) to not do any type of code review. The last three projects I have worked on did not have any type of formal (or informal) code review process in place, and I believe part of the reason is that there aren't any decent tools that support it (from what I understand Team Systems supports this, but we aren't on it yet).

To help solve this problem, I have been looking for a tool that would meet the following requirements:

1. Integrates with Visual Source Safe
2. Supports command-line or hyperlink or something simple that can be easily sent via email (like the windiff command above)
3. Allows for reviewing diffs before the changes are submitted

Not surprisingly I didn't find anything. As a result, I started playing around with the ss.exe command-line interface (http://msdn2.microsoft.com/en-us/library/39czz3he(...) that ships with VSS to see if it would support some of the primitive operations that I needed to build this tool. It turns out id does, so I created a command line tool (crutil.exe) that accepts 3 arguments on the args[0] = the VSS project path, args[1] = the network share path that maps to the developers PC whose code is being reviewed and args[2] = the VSS user ID of the developer whose changes are being reviewed.

When supplied with these values the tool does the following:
1. Queries VSS (using ss.exe) and requests all of the files changed by the developer (in this example user matt.berseth)
2. Creates a temporary folder on the reviewer's local PC
3. Copies the modified files from the developers PC (\\mattspc\project1\src) to the reviewer's local PC - these files are copied into the local temporary directory
4. Gets the latest version of the changed files from VSS - these files are copied into the local temporary directory
5. Opens WinMerge (http://winmerge.org/) and diffs the directories

M.B.