Finding Out which Groups a User is a Member Of When Using Windows Authentication in Asp.Net

March 13, 2008

When using Windows authentication with Asp.net, I often need to know which active directory groups a user is a member of. Now I know that you can do something like:

if (User.IsInRole("Admin"))
{
    //Give Access to Secrets
}

The problem with this is you need to know the name of the group ahead of time. And what if you are on a network where the full name of a group is not always clear. The actual group name may be “MyDomain\Admin”. So I wrote up a quick way to just get a list of all the groups a user is a member of. It isn’t super straight forward (as far as which types you need to cast to) so I thought I would list it out here:

public static List<string> GetGroups(RolePrincipal user)
{
    List<string> groups = new List<string>();

    WindowsIdentity identity = p.Identity as WindowsIdentity;
    foreach (IdentityReference group in identity.Groups)
    {
        NTAccount account = (NTAccount)group.Translate(typeof(NTAccount));

        groups.Add(account.Value);
    }

    return groups;
}

the user of it on a web page would be something like:

List<string> groups = GetGroups(User as RolePrincipal);

Keep in mind that this is assuming you are using Windows Authentication. So the weird part of the code above is:

NTAccount account = (NTAccount)group.Translate(typeof(NTAccount));

if you do not get this step, you will just get a bunch of Active Directory IDs that won’t do you much good.

Also, sorry about the long title. I just can’t think of a clever title today. Maybe I should add something like “Ultimate Edition for Developers” on the end to make it extra clear.

kick it on DotNetKicks.com


What I Miss

March 11, 2008

So I have been living up here in Washington for about 5 months now and I am really missing some of the food I am used to in San Diego. In no particular order they are:

Hopefully it is just a matter of having to learn about the local spots up here for good food. I am not all that hopeful that I will find mexican food up here like they have in San Diego.


Using BlogEngine.net as a General Purpose Content Management System – Part I

February 28, 2008

So I keep running into the same problem – I am building a small website for somebody (in this case, my Mom) and I need to provide them with a way to update the content of their site so I don’t have to. Basically, I need a lightweight and flexible content management system that is easy to use.

In this series of posts, I will show how I converted a small website from just standard .aspx pages into a site where all pages are editable by Windows Live Writer and via an online interface. In Part I of this series I will just set some background on how I am approaching the creation of this lightweight CMS.

If The Shoe Fits…

cmsWhen I first thought of a lightweight CMS, I thought of graffiti. It sounds like exactly what I need. So I downloaded the express edition and started evaluating it. It seemed like a nice product and all is not free for commercial use ($399 is the cheapest commercial licence) and I can’t afford that price tag when building small websites.

Enter BlogEngine.net. My favorite blogging platform. There, I said it. I host my blog on wordpress but I like BlogEngine.net better. In fact, I will probably be migrating to BlogEngine.net in the near future. How do I know I like it so much? Well, I use it to run my wife’s blog and I am constantly tinkering around with her site all of the time because I enjoy using BlogEngine.net so much.

I thought that BlogEngine.net has all of the key pieces I needed for my lightweight CMS:

  1. A WYSIWYG Editor
  2. A Metaweblog interface
  3. Tons of extensibility

Basic Idea

I decided to base my CMS implementation on the concept of pages. Most blog engines have two distinct types of content: pages and posts. Posts are the typical type of content that becomes part of your blogs feed whereas pages are usually static content which can be anything outside of a blog post (for example an ‘About Me’ page). BlogEngine.net already has everything I need to get the content of page created and persisted in a data store (it supports xml and sql server out of the box). I decided to write a web control which I can place on any webpage and include the contents of a given page from the data store.

I made a control called PageViewer which you can place on the page like this:

<blog:PageViewer ID="view" runat="server" DisplayTitle="false"
    PageId="167eb7f3-135b-4f90-9756-be25ec10f14c" />

This control basically just looks up the page using the given id (this functionality is all provided by the existing BlogEngine.Core library) and displays its content. Here is the rendering logic

BlogEngine.Core.Page page = null;
if (PageId != Guid.Empty)
    page = BlogEngine.Core.Page.GetPage(PageId);

if (page != null)
{
    ServingEventArgs arg = new ServingEventArgs(page.Content, ServingLocation.SinglePage);
    BlogEngine.Core.Page.OnServing(page, arg);

    if (arg.Cancel)
        Page.Response.Redirect("error404.aspx", true);

    if (DisplayTitle)
    {
        writer.Write("<h1>");
        writer.Write(page.Title);
        writer.Write("</h1>");
    }

    writer.Write("<div>");
    writer.Write(arg.Body);
    writer.Write("</div>");
}

This code is pretty straight forward – all it does is get an instance of the page and then display its title in <h1> a tag and its body in <div> tag. This logic is actually straight from the existing page retrieval code that already exists in BlogEngine.net. This web control is pretty much the only new code I had to write. The rest of the project mostly involves moving files around and removing parts of the BlogEngine.net framework that I don’t need.

Armed with this control, we are ready to start converting the static pages from the old version of the website to be BlogEngine.net pages which can be stored and retrieved using the BlogEngine.Core classes.

In part II of this series, I will cover what changes I made to the website project used for BlogEngine.net blogs to make it function like a straight up website, not a blog. Any feedback is welcome.

kick it on DotNetKicks.com


YUI: I Officially Can’t Keep Up

February 20, 2008

First off, congratulations to Eric Miraglia and the YUI team – they have just announced the release of YUI 2.5.0:

The YUI Team just released version 2.5.0 of the library. We’ve added six new components — Layout Manager, Uploader (multi-file upload engine combining Flash and JavaScript), Resize Utility, ImageCropper, Cookie Utility and a ProfilerViewer Control that works in tandem with the YUI Profiler. This release also contains major improvements to the DataTable Control and new Dual-Thumb Slider functionality in the Slider Control.

Six new components?!? Man, I just can’t keep up with learning all this new stuff let alone keep YUI.Net up to date.

Roadmap Gone Off Track

waitup I was working on a roadmap for YUI.Net but now I have some serious consideration to do about what next steps to take. Although there has been plenty of interest in the YUI.Net project, nobody has really come forward to help out. I am not complaining. I really enjoy working on YUI.Net. I just don’t have the time to dedicate to it right now. I am going to continue to follow the development of the YUI, but I don’t think I will continue development on the YUI.Net library for the foreseeable future.


Google Charts for Asp.Net now on Codeplex

February 10, 2008

image I have received very positive feedback on my Asp.Net control for Google charts so I decided to place it up on Codeplex to allow people to participate and add code to the project.

I am currently working on a project roadmap so please let me know if you are interested in participating. One feature I have already begun work on is giving the control support for data binding.

Here is some example data binding code I have got working:

protected void Page_Load(object sender, EventArgs e)
{
    chart.DataSource = GetDataSource();
    chart.DataBind();
}

private DataTable GetDataSource()
{
    DataTable table = new DataTable();
    
    table.Columns.Add("Type", typeof(string));
    table.Columns.Add("Jan", typeof(float));
    table.Columns.Add("Feb", typeof(float));
    table.Columns.Add("Mar", typeof(float));

    table.Rows.Add("Men", 68, 78, 88);
    table.Rows.Add("Women", 68, 58, 78);
    table.Rows.Add("Both", 88, 48, 98);
    return table;
}

I am just binding to a simple DataTable which has one column containing the labels for the chart and multiple other columns which contain the data for the chart. The code above produces the following chart:

image

I look forward to seeing this project improve.

kick it on DotNetKicks.com


C# Language Improvements: Know What You Are Getting Into

February 6, 2008

The C# language has changed a lot since its initial release in 2000. C# 2.0 brought us:

imageC# 3.0 brought us:

And that is just the new language features in the last 3 years! This does not include all of the new classes added to the BCL over the same time period.

Know the Cost

I am as excited about these new changes as the next guy. I have used various combinations of these improvements in my projects with great success. But is there a cost to new features?

Recently I read a couple of articles that reminded me that you not only have to understand how a feature is used, you also have to understand the cost of using it. Sometimes that cost is performance, other times it could be something like readability or portability. I’ll take one example from the 2.0 framework and then one from the 3.5 framework to show that you need to understand the implications of using new features.

Yield Return

First, there is Fritz Onion’s recent post on the amount of code generated by the yield return syntax introduced in C# 2.0:

The array allocation function generated a total of 20 lines of IL, but the yield return function, if you included all of the IL instructions for the IEnumerable class generation as well was over 100! That’s a 5x penalty in code generation to save 18 characters of typing

So is the 5x penalty ever worth it? Yes, of course it is. There are things you can do with yield that you couldn’t do previously. In most cases, the use of yield improves readability dramatically. It also makes the task of creating a custom enumerator much easier.

In his article The power of yield return, Joshua Flanagan points to an example where using the yield return improved performance dramatically:

With the improved implementation that took advantage of the yield keyword, the program was able to finish its job in less than half the time! It also used much less memory, as it never had to store all 9 strings in a collection. Now imagine the potential impact if GetCombinations returned a collection with thousands of entries!

The point here is that you have to know the costs and how they fit in with the requirements of the project you are working on. If you are building something that must support thousands of concurrent users and must be very performant, you will most likely choose to use the yield return despite the extra code generated by the compiler.

LINQ is Dead, Long Live LINQ

Most of the time when I show somebody the new language enhancements in C# 3.0, the thing that interests them the most (and rightly so) is LINQ. It is just so different to see query syntax built right into the language. The next question they usually ask is how the performance of something written using LINQ would compare the same procedure written using just C# 2.0 control structures.

Steve Hebert recently wrote a post about LINQ performance where he concludes:

Despite my best efforts I just couldn’t make my hand-written code perform as poorly as Linq

What? Seriously? Wow. Then I guess we should stay away from LINQ then right? Well, if you look closer at his post, you will notice that he has optimized his non LINQ version of the code a little bit for the underlying data structure where LINQ has to be able to operate regardless of the underlying data structure. I am not so much interested in the particulars so much as I am the idea that you should understand these things before you start replacing all of your for loops with LINQ queries.

Shifting Sands

One more recent post that fits in here. Rob Conery wrote about his recent experience where his 5 year old code has come back to haunt him:

I spose the moral of the story is to always view the concept of maintenance with an eye towards shifting toolsets and platforms. In 4 years you will need to support the ASP.NET 2.0 site you’re on now, using Visual Studio 2012 and it’s Silverlight-generated Scaffolds :).

This is a great reminder of how tough it can be to deal with changes in technology. I mean, come on, he couldn’t find a machine to compile his 5 year old code?!? I know we can all relate. With the technology learning curve growing at a semi exponential way, just imagine where that same code will be in another 5 years.

Back to Machine Code

Obviously I am not advocating that we just give up on new features because they might not be as fast or resource efficient as our hand coded machine code. In fact, I think we need to embrace abstractions wherever possible. They make our jobs as software developers much easier. Just be smart about it. Have some idea what is going on behind the covers. It is important to realize that yield return eventually becomes a bunch of compiler generated code and that LINQ queries are general case and they may not always be as great as manually doing the coding yourself.

Maybe the documentation on these new language features could do a better job at explaining what sorts of considerations we need to take into account when using them in our applications.

kick it on DotNetKicks.com


Microsoft + Yahoo! and My Affair With YUI

February 1, 2008

If you read my blog regularly, there are two things you may or may not know about me:

So today’s big news that Microsoft has offered to buy Yahoo! for 44.6 billion dollars speaks to both of these facts about me. This is obviously big news for both Yahoo! and Microsoft and many people have their different takes on whether or not it is a good idea or not. I just want to say that I am feeling like my secret love affair with YUI is somehow more justified after hearing this news.

Now if I build sites using the YUI CSS library, or work on YUI.Net, I can be comforted by the fact that I wasn’t the first one to think of Microsoft + Yahoo! being a happy combination.

By the way, I realize that I haven’t added any new code to the YUI.Net controls in a long time. I am working on a roadmap of how to move forward and would love any feedback from people who have used the controls.


Follow

Get every new post delivered to your Inbox.