ASP.NET Uncategorized

ASP.NET Security : 1- Basics

Lately at SCS I have been assigned to build up the security module and related tasks in the Real Estate Management System we are building. So I decided to share what I have learned in this past period and of course to hear from the community to find optimal solutions for the scenarios I worked with, all what I write here might be repeated but I will share it anyway. [more]

In this part, I will show some important basic points that should be clear to everyone before implementing security tasks.

Looking at any web application, the security is a matter of users/passwords/roles/groups… etc. While ASP.NET provides more mechanisms for authentication and authorization that work with the Operating system,IIS and .NET framework classes. So the ASP.NET application runs through these 3 levels.

  • IIS Level
  • ASP.NET worker process level
  • ASP.NET pipeline level

So, the Big Question, What is the Identity that runs my application ?

First, When an IIS web server machine receives an ASP.NET request, the IIS assigns it to one of the threads pooled in it, IIS runs under the SYSTEM account which has all the powers in a Microsoft Windows operating system. You can read extra information in the ASP.NET Application Life Cycle Overview article on the msdn.

Next, the 3 security levels run on the request one after the other.

1- The IIS thread context : the identity of this thread is determined according to the settings of the website in the IIS which has one of the following settings:

  1. Basic authentication prompts the user for a user name and a password, also called credentials, which are sent unencrypted over the network.
  2. Integrated Windows authentication uses hashing technology to scramble user names and password before sending them over the network.
  3. Digest authentication operates much like Basic authentication, except that passwords are sent across the network as a hash value. Digest authentication is only available on domains with domain controllers running Windows Server operating systems.
  4. Anonymous authentication allows everyone access to the public areas of the Web sites, without asking for a user name or password. When this is set, the identity impersonates the identity set in the textboxes, with the default user name IUSR_MACHINENAME. Like shown in the figure down below.

Further more, IIS provides SSL (Secure Socket Layer) authentication mode that is based on certificates, to authenticate users requesting/providing secret information on the server, two trusted certificate providers (which I know but never used) are and

AuthenticationMethods IIS 5

After authentication, the thread sends the request to the appropriate external module.

Next part I will talk about the 2 next security level contexts.

GDI + Uncategorized

Exploring GDI+ : Using the Pen

In my tour in exploring GDI+ I explored the Brush object, now its time for some Pen stuff.

While the Brush classes are used to fill shapes, the Pen class is used to frame shapes. However, Pens are not only used for simple frames. Here in this post I show some advanced uses for the Pen. [more]

Some interesting members are :

sealed class Pen : MarshalByRefObject, ICloneable,  IDisposable 
// Constructors
public Pen(Brush brush);
public Pen(Brush brush, float width);
public Pen(Color color);
public Pen(Color color, float width);
// Properties
public Color Color { get; set; }
public CustomLineCap CustomEndCap { get; set; }
public CustomLineCap CustomStartCap { get; set; }
public DashCap DashCap { get; set; }
public float DashOffset { get; set; }
public float[] DashPattern { get; set; }
public DashStyle DashStyle { get; set; }
public LineCap EndCap { get; set; }
public LineJoin LineJoin { get; set; }
public LineCap StartCap { get; set; }
public float Width { get; set;
//Other members removed here.}

As you can see, the pen can be instantiated with a Color or with a defined Brush that means the pen can be one of the Brush TypesI previously wrote about.

In addition to their brushlike behavior, pens have behavior at starting and ending along their length that brushes don’t have. For example, each end can have a different style, as determined by the LineCap enumeration shown next.

Line Caps


You can set different LineCaps for pens in the StartCap and EndCap properties of the Pen, there are predefined caps and custom caps are allowed too.

        private void RenderPens1(Graphics g)
using (Pen p = new Pen(Color.Black, 10))
p.EndCap = LineCap.ArrowAnchor;
g.DrawLine(p, new Point(10, 20), new Point(300, 20));
//other pens
p.EndCap = LineCap.Custom;
// width and height of 3 and unfilled arrow head
p.CustomEndCap = new AdjustableArrowCap(3, 3, false);
g.DrawLine(p, new Point(10, 260), new Point(300, 260));


In addition to the ends having special styles the starts can have as well, further more a line can have a dash style, as defined by the DashStyle enumeration.

Dash Style of Pen

        private void RenderPens2(Graphics g)
using (Pen p = new Pen(Color.Black, 10))
{ p.DashStyle = DashStyle.Dash;
g.DrawLine(p, new Point(10, 20), new Point(300, 20));
//other DashStyles
p.DashStyle = DashStyle.Custom;
p.DashPattern = new float[] { 1f, .5f, 2f, .5f, 3f, .5f, 4f };
g.DrawLine(p, new Point(10, 170), new Point(300, 170)); } }

As you can notice in the members of the Pen, the DashCap property which also accepts a LineCap enumeration, so you can take more control over the line that appears.
Thats all for this part. Happy Coding.

PensForm.cs (2.86 kb)

Design Time Support Uncategorized

Enabling Design Time Template Editing

Few days ago, I blogged about how to enable auto formats in the design time smart tag by overriding simple property, this post will describe how to enable design time template editing in a similar simple way.

Template Editing 


The following steps will show how to do this in your template controls, assuming you already have a template control ( template controls are web server controls that have one or many properties of type ITemplate ).

So, this is how it works :

  1. Implement a custom designer that inherits from System.Web.UI.Design.ControlDesigner
  2. Override the TemplateGroups Collection.
  3. In the get define your template group collection and return it.
  4. Don't forget to enable TemplateEditing flag.

The Sample I introduce here contains a template control having 4 templates which I divide them into 2 template groups.

The SampleControl

[ToolboxData("<{0}:SampleControl runat=server></{0}:SampleControl>")]
public class SampleControl : TemplateControl
private ITemplate _firstTemplateX;
 private ITemplate _firstTemplateY;
 private ITemplate _secondTemplateX;
 private ITemplate _secondTemplateY;
public ITemplate FirstTemplateX
 get { return _firstTemplateX; }
 set { _firstTemplateX = value;
public ITemplate FirstTemplateY
 get { return _firstTemplateY; }
 set { _firstTemplateY = value; }
public ITemplate SecondTemplateX
 get { return _secondTemplateX; }
 set { _secondTemplateX = value; }
public ITemplate SecondTemplateY
 get { return _secondTemplateY; }
 set { _secondTemplateY = value; }

The Control Desginer

class SampleControlDesigner : ControlDesigner
 public override void Initialize(IComponent component)
  SetViewFlags(ViewFlags.TemplateEditing, true);
 private TemplateGroupCollection _templateGroups;
 public override TemplateGroupCollection TemplateGroups
  if (_templateGroups == null)
   _templateGroups = new TemplateGroupCollection();
   TemplateGroup tempGroup1, tempGroup2;
   TemplateDefinition tempDef1, tempDef2, tempDef3, tempDef4;
   SampleControl ctl;
   ctl = (SampleControl)this.Component;
   tempGroup1 = new TemplateGroup("FirstTemplateGroup");
   tempGroup2 = new TemplateGroup("SecondTemplateGroup");
   tempDef1 = new TemplateDefinition(this, "TemplateX", ctl, "FirstTemplateX", true);
   tempDef2 = new TemplateDefinition(this, "TemplateY", ctl, "FirstTemplateY", true);
   tempDef3 = new TemplateDefinition(this, "TemplateX", ctl, "SecondTemplateX", true);
   tempDef4 = new TemplateDefinition(this, "TemplateY", ctl, "SecondTemplateY", true);
  return _templateGroups;

The final output of the sample looks like this

Final output of sample

Here's the code so have fun.

SampleControl.cs (3.32 kb)

Design Time Support Uncategorized

Adding Auto Format for ASP.NET Custom Controls Design Time

Back to design time support, but this time with ASP.NET server controls, most complex & simple controls built in the .NET framework are associated with an Auto Format.. link in the smart tag as the one shown in the figure, I showed in a previous post how to add links and properties to the smart tag of a control.

autoLink  [more]

Ok, now when clicking that link a new window is popped out and you get a list of predefined formats on the left and a preview panel in the right like this.


Of course if you want to implement these features you will not have to design a new windows form and deal with all the head ache for previewing and those. You only will need some basic steps, I will show next, Assuming you already have your own custom control ( I will just use a simple LabelEx control for this sample);

1- Define your designer.

class LabelExDesigner : ControlDesigner


2- override the AutoFormats property and return some DesignerAutoFormats, to be used.

private DesignerAutoFormatCollection _autoformats = null;
public override DesignerAutoFormatCollection AutoFormats
        if (_autoformats == null)
            _autoformats = new DesignerAutoFormatCollection();
            _autoformats.Add(new LabelExAutoFormat("Remove All"));
            _autoformats.Add(new LabelExAutoFormat("Reddish"));
            _autoformats.Add(new LabelExAutoFormat("Blueish"));
        return _autoformats;

3- Define a custom DesignerAutoFormat, which comes with an abstract Apply method, which is called when trying to apply a format on the preview control.

class LabelExAutoFormat : DesignerAutoFormat
    public LabelExAutoFormat(string name)
        : base(name)
    { }
    public override void Apply(Control control)
        if (control is LabelEx)
            LabelEx ctrl = control as LabelEx;
            switch (this.Name)
                case "Remove All":
                case "Reddish":
                    ctrl.ControlStyle.ForeColor = ColorTranslator.FromHtml("#ff0000");
                    ctrl.ControlStyle.BackColor = ColorTranslator.FromHtml("#ffccff");
                    ctrl.ControlStyle.Font.Bold = true;
                case "Blueish":
                    ctrl.ControlStyle.ForeColor = ColorTranslator.FromHtml("#0000ff");
                    ctrl.ControlStyle.BackColor = ColorTranslator.FromHtml("#99ccff");
                    ctrl.ControlStyle.Font.Italic = true;

4- And don’t forget to decorate the control with the designer attribute

public class LabelEx : Label

And now everything is set and you have your own auto formats.

Default format reddish auto format Blueish auto format

Here is the code and Happy Coding…

Uncategorized Windows Forms

Extracting Icons from Files

Update: This approach is only to show one of the hidden gems in the .net framework and not to steal copyrighted icons.
Icons of other programs should only be used after owner approval.

Have you ever seen a file with a pretty icon you wanted to use but you couldn't get a similar one in your program?

If yes,  try this method >> Icon.ExtractAssociatedIcon here is the code I wrote that works fine, you will also find the sample attached


Icon ico;

public Form1()
  ico = this.Icon;

private void btnGetIcon_Click(object sender, EventArgs e)
  if(dlgOpen.ShowDialog() == DialogResult.OK)
    ico = Icon.ExtractAssociatedIcon(dlgOpen.FileName);
    this.Icon = ico;

private void pnlIcon_Paint(object sender, PaintEventArgs e)
  e.Graphics.DrawIcon(ico, pnlIcon.ClientRectangle);

[/code] (7.03 kb)

GDI + Uncategorized

Exploring GDI+ : Using The Brush

Brush HierarchyOne of the core classes in the GDI+ framework built in .Net is the Brush class. There are 5 types of Brushes in .Net that help you to color your objects by lot of variations the five types are as shown in the figure :



The 5 types as shown are :

SolidBrush Defines a brush of a single color. Brushes are used to fill graphics shapes, such as rectangles, ellipses, pies, polygons, and paths.
HatchBrush Defines a rectangular brush with a hatch style, a foreground color, and a background color.
LinearGradientBrush Encapsulates a Brush with a linear gradient.
PathGradientBrush Encapsulates a Brush object that fills the interior of a GraphicsPath object with a gradient.
TextureBrush Each property of the TextureBrush class is a Brush object that uses an image to fill the interior of a shape.

I have built a simple application that uses and shows the output of each brush, remember that options of each bursh is not limited to my sample, there are much more one can do using these brushes.

solid hatch linearGradient

pathGradient texture

Sample Application Code :

Exploring GDI+ (13.24 kb)

ASP.NET Uncategorized

The ASP.NET Configuration Model

ASP.NET as well as .NET applications have one more excellent feature, ASP.NET uses a flexible configuration management system that keeps the application configuration separate from application code. ASP.NET configuration is stored in XML files with the .config extension, which makes it easy for users to change it before, during and after deployment.

The configuration file we all are aware of is the web.config file found in the application root, which when added has almost very simple configurations. But guess what that is not the only configuration file that your ASP.NET application relies on, there are other config files that your application inherit that configuration by default, next I will show the Configuration Hierarchy in ASP.NET. [more]

Configuration Hierarchy

  1. Server settings – machine.config : This is at the root of the configuration hierarchy. It defines global, default settings for all of the applications on the(a) server. The machine.config is located in the Config folder for the version of the .NET Framework installed on the computer. In default installation will be found in this path C:WindowsMicrosoft.NETFrameworkv2.0.50727CONFIGmachine.config *.
  2. Root Web setting – web.config : This defines the default settings for ASP.NET applications on the(a) server, which inherits all the settings from machine.config. Can be located at C:WindowsMicrosoft.NETFrameworkv2.0.50727CONFIGweb.config*.
  3. Web site settings – web.config : This file is the first optional file in the hierarchy it defines some settings that will be applied on all the ASP.NET applications within a website. For example, to set some default settings for all web applications in the Default Web Site that comes in the IIS, place a web.config file in this path C:inetpubwwwrootweb.config *.
  4. ASP.NET application root settings – web.config : This comes to be the web.config we all know that is found in the application root.This file is also optional.
  5. ASP.NET application subfolder settings – web.config : This file is found in subfolders of an application to set some specific settings on the pages contained in this folder. For Example, Admin folder needs an extra <authorization> setting to not allow non admins for accessing the folder.

NOTE : Although some of the settings in the machine.config file can be overridden by settings in the web.config file, other settings that apply to ASP.NET as a whole are protected and cannot be overridden.

Merging configuration at runtime

At runtime, all these settings are merged, all configuration settings are retrieved from the machine.config, then settings from the default web.config are then retrieved, new settings are add to those of the machine.config, changed settings override the orignal ones. And So on, for the rest of the config files.

Editing the web.config

It is highly recommended not to change the default settings in the machine.config and in the default web.config of a server, unless you know exactly what you are doing.
Example for changing, there is a default connectionString in the machine.config named LocalSqlServer, a lot of extensions and providers strongly rely on it, but this default connection string uses sqlexpress which is not preferred by a lot of developers which do not want to override it in every application they use, so you can change that.

Tools for editing Web.Config; Since the web.config is XML based there are many tools that can help reading and writing settings in it, like notepad , also there are tools that are made for the sake of editing the web.config. Example tools:

  1. Web Administration Tool : which enables easy and quick creation and editing web.config files for specific web application and subfolders. The web administration tool comes with Visual Studio 2005, 2008, It is found in the Project/WebSite menu usually the last item named
  2. My friend here found another tool that helps changing web.config file in a nice visual tree.

* These paths are the default when installing the visual studio

Design Time Support Uncategorized

Custom Controls Design Time Support Part 15: Debugging Design Time

This is final part of my series/tutorial on design time support, it was really fun writing it and hearing your comments and suggestions, I really learnt alot and hope you too had some experience in writing design time support for the custom controls.

In this part, I will show you how to debug the design time code we are writing (works with vs 2005 and 2008).



  1. Have a solution containing the control.
  2. Configuration set to Debug.


  1. Open that solution containing the control.
  2. Right click the project and select Properties.
  3. Select Debug Tab as in Figure.
  4. From Select Action Group select Start external program then browse the devenv.exe usually found in this path C:Program FilesMicrosoft Visual Studio 9.0Common7IDEdevenv.exeDebug Tab
  5. Save Settings.
  6. Place breakpoints where ever design time code should be called.
  7. Now Debug the project a new instance of Visual studio will open.
  8. Start a new project to be a container of the project (new web application to test a web control or a windows application for a windows control).
  9. Choose from the toolbox the control you already built ( Right click toolbox > Choose Items > browse for the dll of the control.)
  10. Now drag your control to the testing container and make any design time action (as using smart tag methods), the first instance will stop in breakpoints. Congratulations you are debugging design time code now.

That's the end of the series, but not the end of design time tips and tricks any one comes in my mind, I will be sure to include it in this blog under the category of Design Time Support.

Hope someone out there will benefit from this tutorial, please let me know if you need any help concerning this issue.

Design Time Support Uncategorized

Custom Controls Design Time Support Part 14: Extra Property Tab

The default PropetryWindow in the visual studio shows 2 Tabs one for properties and another for events. If one day you thought that you have set of members might be Properties that you need to put them in an extra property tab then in this post you will learn how to put extra tabs.

When this can be useful?

After the ajax era has arrived and component authors started to build some ajax controls we usually see Properties named " ClientXXX " where xxx is the event name and these properties just appear in the properties tab while it would be more appropriate to show them in an extra tab say a Client side events.  [more]

How Can you do it?

You need to follow some steps.

  1. Create a Custom Tab that extends the System.Windows.Forms.Design.PropertyTab
  2. override the GetProperties method to send back the selected properties
  3. override the TabName property to set the name of the tab.
  4. override the Bitmap property to set the image of the tab button.
  5. Mark the control/component with PropertyTabAttribute and pass the type of the new Custom Tab.

In code:


public class ExtraSuperTab : System.Windows.Forms.Design.PropertyTab
    public override PropertyDescriptorCollection GetProperties(object component, Attribute[] attributes)
        PropertyDescriptor pd = TypeDescriptor.CreateProperty(component.GetType(), "XXX",typeof(int), new CategoryAttribute("Super Properties"));

        return (new PropertyDescriptorCollection(new PropertyDescriptor[]{pd}));

    public override string TabName
        get { return "Super Tab"; }

    public override System.Drawing.Bitmap Bitmap
            return (System.Drawing.Bitmap)System.Drawing.Image.FromFile(@"D:icon.bmp");


And in the control don't forget the attribute


[PropertyTab(typeof(ExtraSuperTab), PropertyTabScope.Component)]
public partial class TestUserControl : UserControl


How it looks at the end in visual studio. 

Extra Property Tab 

TestUserControl.cs (1.37 kb)

Design Time Support Uncategorized

Custom Controls Design Time Support Part 13: Adding Snaplines

Another new feature added in the Design Time Environment in visual studio 2005 and 2008 for windows forms and windows user controls designers is the Snaplines.

What is a snapline?

A snapline is a dynamically generated UI layout guide line. Snaplines are generated during control move operations in the designer. The location of other controls on the design surface provide the lines.

All controls by default inherit the default the Snaplines which appear while moving that interact with Tops, Lefts, Bottoms and Rights of other controls, with the form border, spacings from other controls and some other. One remarkable snapline is the one that appears while moving a Label control beside TextBox controls the purple snapline that aligns the text position instead of the control position. [more]

Now using thr sample control I used in the previous part , I added two labels and two texboxes to simulate a Login control, like the following:

By default when placing this control on a windows form and start moving it around there are no snaplines to interact with the inner labels and textboxes in this sample I will show how to implement custom Snaplines for this usercontrol.


1- Add a designer.

2- override Snaplines property and add your own custom ones.


public override System.Collections.IList SnapLines
        IList snaplines = base.SnapLines; //get old snaplines and then add new ones
        snaplines.Add(new SnapLine(SnapLineType.Baseline, _control.lblUserName.Bottom));
        snaplines.Add(new SnapLine(SnapLineType.Baseline, _control.lblPassword.Bottom));
        return snaplines;


3- Don't forget to add the Designer attribute to the Control definition


public partial class TestUserControl : UserControl


The final looks as this.

Final look

So good luck and happy coding with custom controls design time.

UserControlDesigner.cs (7.70 kb)