How to build a modern best practice enterprise application on-premise or in the cloud

May 24, 2012

This is a summary of the key points of my presentation at the Victoria.Net users group, held at Microsoft in Melbourne, Australia, with a few added points thrown in for extra value.

Developing large scale applications is hard, and never before have we been under so much pressure to be efficient with our time. It is imperitive that we spend as little time as we can on unproductive infrastructure code and as much of our time actually implementing the domain/business services logic.

For some reason, many enterprise architects promote leaving performance to the end of the development process. They decide on an architecture, get all their developers to build it, and then when it gets to the end of the development process, wonder why the application runs so slowly. They haven’t even done a basic performance test, to see if any of their assumptions were correct, and at the end of the process sometimes discover serious flaws in the architecture of their sites requiring considerable rework, and occasionally a complete rewrite is required.

In a previous post, I showed statistics produced by Watt’s Humphrey, known as the father of Software Engineering, where he shows the cost of discovering and rectifying defects in their respective project phases. The later you find defects in the development process, the more expensive they are to rectify, so if you wait to the end of a project before dealing with an issue that should have been rectified at the start of the project, it could cost you magnitudes more than if you at least have an attempt at dealing with performance from the start. You can find that post here.

Another issue with large scale web sites is configuration. Most configuration is found in web.config files or app.config files within a .net application. Within a web site, if you modify the web.config file, it resets the web server to refresh the configuration settings. One environment I worked in had a web farm that consisted of 8 web servers. Because of the use of web.config settings and also Enterprise Application Blocks, which heavily utilise configuration files, they were always running into problems with servers that have their configuration out-of-synch, and also have an unstable state during the update. And they still are.

So on Tuesday night, I showed a comprehensive end-to-end application that demonstrates an n-tier, service-oriented architecture that is considered best practice. It also allows on-premise, hybrid and cloud-based tiers. For people that are struggling with the whole “to cloud or not to cloud” arguments, this allows you to hedge your bets. If this point has been holding back project development, you don’t need to worry. This architecture allows you to build an on-premise application, then move it to the cloud at a later date, for very little extra cost, if there is a movement to do so.

The features are:

A configuration block. The configuration block is at the heart of the application. It enables you to centralise configuration for all the tiers of your application. It provides a web based portal for making modifications. When you make changes to configuration, those changes are automatically updated on the server.

Centralised exception handling and errors.

Centralised logging.

A service map. The service map shows a visual representation of all your tiers, where they are hosted, what instances are running, what databases you are running, and it even allows you to drill down into a database and see latency figures and the least performing and most CPU intensive queries. Using the service map, you are able to see any servers that become unavailable, for whatever reason. The architecture actually implements polling of all the component instances, so you’ll know pretty much straight away if any of the services aren’t available.

A large scale application project structure that you can use, separating User Interface, Business Services Logic and Database.

A database layer that is optimised for performance. This was at the heart of the performance tests against IBM WebSphere, so if there was a faster way of interacting with the database, I would be absolutely shocked. Microsoft has to be able to push as many transactions per second as possible through this system. They have to outperform IBM WebSphere, which they do dramatically. (IBM WebSphere is 6 times more expensive for the same grunt.)

A benchmarking tool that allows you to test your architectural choices. What happens with this architecture if you make the wrong choice? Nothing. The application has been designed so that you can change where your tiers are hosted, at runtime, on the fly! So you are protected against making the wrong choice.

I should point out that I demonstrated all of this. I started by running the application fully in-proc. Then I moved the business services layer to be IIS hosted. I was able to show this on the visual service map. Then I switched the application over to a business service layer hosted in the cloud. When I showed the service map, it looked awesome.

There are full instructions on how to set up the application. The installer only takes about 5 to 10 minutes to install everything. It is rich with documentation and it includes full instructions on how to configure Azure to have different tiers, how to install digital certificates, and ensure that all the communication channels are encrypted.

I mentioned that if you host a business services layer in Azure, then you can supply digital certificates to any company that you would like to use that service. So any company can integrate with the business services layer without you having to worry about them gaining access to your network.

I explained how the load balancing works. You can have as many servers you like in the web farm, and the requests are round-robined to each of the services.

I spoke about how to integrate the configuration block into your own application, and also demonstrated the Visual Studio template provided to generate the basic application layers, which include the configuration block.

The application itself was written by Gregory Leake. Gregory is the Technical Product Manager at Microsoft for the SQL Azure and Azure AppFabric teams. The application was first written around 2006, and is now at version 5. Thousands and thousands and thousands of hours have gone into thinking through the mass of scenarios that you might need to consider, and spent on coding this application. At the time of writing, this application has been evolving for 6 years. The application, including a working demonstration of the running Azure version, may be found here: http://msdn.microsoft.com/stocktrader

I guess my final message here is that in order to be more efficient in your coding, you need to simplify. Forget over complicated tricky designs. All that will happen is that they will be difficult to maintain. Spend as little time as you can on infrastructure code. If you can find a framework such as this that has all these goodies already provided, then embrace it. There is no way you can develop all this efficiently in short timeframes, and why would you want to anyway? It’s just reinventing the wheel. Take it on and use it within your environment. Then spend most of your time building your application, and not the infrastructure to support it.


14 Tips for optimising SQL Server 2008 Queries in ASP.Net

June 19, 2010

This article is now here.


How to use ASP.Net Membership and Role providers with ADLDS / ADAM, with Code

February 26, 2010

There are scenarios as a developer where you need to connect to and use Active Directory from your ASP.Net or Silverlight application. For whatever reason, being able to immediately connect to your corporate domain may be difficult. Rather than let this hold you up, there is another possibility – you can install ADAM and configure it as a membership and role repository for your applications. ADAM (otherwise known as Active Directory Lightweight Directory Services), is a cut down version of Active Directory, meant specifically for Applications. It can be installed on your local machine or on a server somewhere, and enable you to get up and running quickly.

The first thing you need to do is install ADAM. On a Windows XP SP1, or Windows 2003 Server, you need to download and install ADAM from here: http://www.microsoft.com/downloads/details.aspx?familyid=9688f8b9-1034-4ef6-a3e5-2a2a57b5c8e4&displaylang=en

Then you follow the instructions from here to get the Membership Provider working:

http://erlend.oftedal.no/blog/?blogid=6

From Windows 2003 R2 and later, you need to go install the Active Directory Lightweight Directory Services role from the Server Manager. On later versions of windows (Windows 2008 R2) you can run the ADLSD Setup Wizard to enable you to install instances. Try to follow the instructions at Erlend’s blog above.

After following Erlend’s instructions, you should be able to click on the ASP.Net Configuration menu item in Visual Studio and use the Web Administration Tool to add users to ADAM.

Next you will want to configure ADAM to be used as a Role Provider. All the documentation talks about this separately from being used as a Membership provider, and you wouldn’t be wrong in forming the conclusion that it should just work, however, the reality is that to have both the users and the roles in the one ADAM instance actually requires you to write a custom role provider. We’ll get to that in a moment. Firstly, you need to follow the instructions to install the Authorization Manager. Those instructions are here:
How To: Use ADAM for Roles in ASP.NET 2.0
Make sure you install the Authorization Manager (AzMan) in the same instance as your users.

Now the best way to obtain a custom role provider is to find one that has already been written. I tried this, but didn’t succeed. The closest I could come to was an Active Directory Role Provider that I found on CodePlex. Everything else just wasn’t good enough or didn’t work. But I downloaded the Active Directory Provider so that I can switch over to Active Directory when I am finished my development and ADAM is no longer desired.

The Active Directory Role Provider may be found here: http://adroleprovider.codeplex.com/releases/view/34407

I found instructions on Erlend’s site on how to construct an ADAM role provider, but no code. So I have written some code to do this, which you can find here. I downloaded the code from codeplex and added it to a separate project, then I added my own code to that project. Basically, this implements pretty much everything you need to install an Authorization Provider for ADAM that works with a user store also in the same ADAM instance. You cannot get this working otherwise.

Here is the section of my web config containing references to these providers:

<membership defaultProvider="AspNetActiveDirectoryMembershipProvider">
      <providers>
 <clear/>
        <add name="AspNetActiveDirectoryMembershipProvider" 
type="CT.ActiveDirectoryMembershipProvider" connectionStringName="ADService" 
connectionUsername="CN=MyAppAdmin,OU=Users,OU=Auth,O=App,DC=MEGACORP,DC=COM" 
connectionPassword="123456." connectionProtection="None" enableSearchMethods="true"/>
      </providers>
</membership>
<profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" connectionStringName="DEVELOPMENT" 
applicationName="/MegaCorp.App.Web" type="System.Web.Profile.SqlProfileProvider, 
System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
      </providers>
      <properties>
        <add name="FriendlyName"/>
        <add name="Firstname"/>
        <add name="Surname"/>
        <add name="Company"/>
        <add name="Phone"/>
        <add name="MobilePhone"/>
        <add name="Address"/>
      </properties>
</profile>
<roleManager enabled="true" cacheRolesInCookie="true" 
defaultProvider="RoleManagerAzManADAMProvider">
       <providers>
          <add connectionStringName="AzManADAMServer" applicationName="MegaCorp.App"
             name="RoleManagerAzManADAMProvider" type="CT.AzManRoleProvider" />
       </providers>
</roleManager>

<connectionStrings>
    <add name="ADService" connectionString="LDAP://localhost:389/OU=Users,OU=Auth,O=App,DC=MEGACORP,DC=COM"/>
    <add name="AzManADAMServer" connectionString="msldap://localhost:389/CN=AzManADAMStore,OU=Auth,O=App,DC=MEGACORP,DC=COM"/>
</connectionStrings>

Before I continue, I should mention that I slipped in the Sql Profile Provider. This is because I am developing a Silverlight 3 application, and the Silverlight Authentication service requires some of these fields to be supplied. So I have installed the aspnet database just so I can get access to the provider table. I also had to change the User Id in the Silverlight Authentication service from a Guid to a string so it could handle the entire user SID.

Now, I was able to run the ASP.Net Web Administration Tool and successfully add roles, add users, and then add users to roles. I did discover one bug in the Web Administration Tool that caused an exception when I clicked the IsActive check box. This exception is caused when the resultant user object is deserialised to be sent over the wire to the application. The good news is, by the time this has happened, all the work has been done, and the error appears to have no other consequences.

Therefore, I decided to swallow up the exception from within the Web Administration Tool. Hey, most of you don’t use the tool anyway, prefering to re-invent the entire application administration.

To do this, you need to go to manageUsers.aspx in C:\Windows\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles\Security\Users
or for 64-bit machines,
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\ASP.NETWebAdminFiles\Security\Users
and wrap a try/catch block around the code causing the exception.

public void EnabledChanged(object sender, EventArgs e) 
{
	CheckBox checkBox = (CheckBox) sender;
	GridViewRow item = (GridViewRow)checkBox.Parent.Parent;
	Label label = (Label) item.FindControl("UserNameLink");
	string userID = label.Text;
	MembershipUser user = (MembershipUser) CallWebAdminHelperMethod(true, "GetUser", new 
	object[] {userID, false /* isOnline */}, new Type[] {typeof(string),typeof(bool)});
	user.IsApproved = checkBox.Checked;

	string typeFullName = "System.Web.Security.MembershipUser, " + typeof
	(HttpContext).Assembly.GetName().ToString();;
	Type tempType = Type.GetType(typeFullName);

	try
	{
		CallWebAdminHelperMethod(true, "UpdateUser", new object[] {(MembershipUser) user}, new 
		Type[] {tempType});
	}
	catch
	{
		//catch any exception occuring here. In most cases this is pure evil.
	}
}

If you want to see the actual source code of the AzMan Role Provider I created, I have added it in below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Interop.Security.AzRoles;
using System.Web.Security;
using System.Diagnostics;
using System.Collections;

namespace CT
{
    public sealed class AzManRoleProvider : RoleProvider
    {
        public override bool IsUserInRole(string username, string roleName)
        {
            var users = GetUsersInRole(roleName);
            foreach (string user in users)
            {
                if (user.Equals(username, StringComparison.OrdinalIgnoreCase))
                    return true;
            }
            return false;
        }

        private string connectionStringName;
        public string ConnectionStringName
        {
            get
            {
                if (this.connectionStringName == null)
                {
                    this.connectionStringName = "msldap://localhost:389/CN=AzManADAMStore,OU=Auth,O=SCP,DC=MEGACORP";
                }
                return this.connectionStringName;
            }
            set
            {
                this.connectionStringName = value;
            }
        }

        public IAzApplication2 ConnectToAzManApplication()
        {
            var _azStore = new AzAuthorizationStoreClass();
            _azStore.Initialize(0, this.ConnectionStringName, null);
            var _azApp = _azStore.OpenApplication2(this.ApplicationName, null);
            return _azApp;
        }

        public override string[] GetRolesForUser(string username)
        {
            var _azApp = ConnectToAzManApplication();
            var user = Membership.GetUser(username);
            var context = _azApp.InitializeClientContextFromStringSid(user.ProviderUserKey.ToString(), 1, null);
            var roles = context.GetRoles("") as object[];
            return Array.ConvertAll(roles, new Converter<object, string>(AzManRoleProvider.GetRoleStringRepresentation));
        }

        public static string GetRoleStringRepresentation(object role)
        {
            return role.ToString();
        }

        public override void CreateRole(string roleName)
        {
            var _azApp = ConnectToAzManApplication();
            var task = _azApp.CreateTask(roleName, null);
            task.IsRoleDefinition = 1;
            task.Submit(0, null);

            var role = _azApp.CreateRole(roleName, null);
            role.AddTask(roleName, null);
            role.Submit(0, null);
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            var _azApp = ConnectToAzManApplication();
            _azApp.DeleteRole(roleName, null);
            _azApp.DeleteTask(roleName, null);
            return true;
        }

        public override bool RoleExists(string roleName)
        {
            var _azApp = ConnectToAzManApplication();
            foreach (IAzRole role in _azApp.Roles)
            {
                if (role.Name == roleName)
                {
                    return true;
                }
            }
            return false;
        }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            var _azApp = ConnectToAzManApplication();
            foreach (var userName in usernames)
            {
                foreach (var roleName in roleNames)
                {
                    var currentUser = Membership.GetUser(userName);
                    var role = _azApp.OpenRole(roleName, null);
                    role.AddMember(currentUser.ProviderUserKey.ToString(), null);
                    role.Submit(0, null);
                }
            }
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            var _azApp = ConnectToAzManApplication();
            foreach (var userName in usernames)
            {
                foreach (var roleName in roleNames)
                {
                    var currentUser = Membership.GetUser(userName);
                    var role = _azApp.OpenRole(roleName, null);
                    role.DeleteMember(currentUser.ProviderUserKey.ToString(), null);
                    role.Submit(0, null);
                }
            }
        }

        public override string[] GetAllRoles()
        {
            var _azApp = ConnectToAzManApplication();
            List<string> rolesList = new List<string>();
            foreach (IAzRole role in _azApp.Roles)
            {
                rolesList.Add(role.Name);
            }
            return rolesList.ToArray();
        }

        private string applicationName;
        public override string ApplicationName
        {
            get
            {
                if (applicationName == null) applicationName = "MegaCorp.App";
                return applicationName;
            }
            set
            {
                applicationName = value;
            }
        }

        public void CreateApplicationGroup(string groupName)
        {
            var _azApp = ConnectToAzManApplication();
            _azApp.CreateApplicationGroup(groupName, null);
        }


        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();

        }

        Converter<object, string> newConverter = new Converter<object, string>(Convert.ToString);

        public override string[] GetUsersInRole(string roleName)
        {
            List<string> userList = new List<string>();
            var _azApp = ConnectToAzManApplication();
            var role = _azApp.OpenRole(roleName, null);

            string[] members = Array.ConvertAll<object, string>((object[])role.Members, newConverter);
            foreach (string memberProviderKey in members)
            {
                System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(memberProviderKey);
                var user = Membership.GetUser(sid);
                userList.Add(user.UserName);
            }
            return userList.ToArray();
        }
    }
}

Note that you’ll need a reference to Microsoft.Interop.Security.AzRoles to be able to compile that code. On earlier systems, such as XP, you’ll need to download the Windows 2000 Authorization Manager runtime from here: http://www.microsoft.com/downloads/details.aspx?FamilyID=7edde11f-bcea-4773-a292-84525f23baf7&DisplayLang=en

This is actually referenced in the article: How To: Use ADAM for Roles in ASP.NET 2.0 found above. You need to install the Authorization Manager runtime, then find the assembly on your system, add it to the GAC, and reference the original assembly from within you web application.


How to create an HTML table with frozen headers and columns

May 30, 2009

I have moved this article to a new blog location at my new company web site. The article may be found here: How to create an HTML table with frozen headers and columns


How to Style the Ajax Control Toolkit Calendar Extender control

May 9, 2009

I have moved this article to a new blog location at my new company web site. The article may be found here: How to Style the Ajax Control Toolkit Calendar Extender control


How to add a close button to the Ajax Control Toolkit Calendar Extender control

May 9, 2009

In this series of educational articles, I have been explaining how to enhancing the Ajax Control Toolkit Calendar Extender control to support a number of different modes, such as Day, Month, Quarter, Year, Decade. I have also introduced implemented the InitialView property, which allows you to select an initial mode that you want the calendar to display in. These features may be used to reduce the number of clicks required to select a birthdate from 9 to 4, which is a productivity improvement for anyone seriously using the calendar for data entry purposes

These are the articles so far:

How to patch the Ajax Control Toolkit CalendarExtender to add Decade support and InitialView – Part 1 

How to patch the Ajax Control Toolkit Calendar Extender control to show a Quarter view

How to patch the Ajax Control Toolkit Calendar Extender control to show a Day, Month, MonthYearDecade, Quarter, YearDecade and Decade view

The code for the starting point for these modifications is found here:

http://cid-5e237543fffb2891.skydrive.live.com/self.aspx/Public/AjaxControlToolkit-Framework3.5SP1withDecadeYearQuarterMonthDayandInitialView.zip

Unzip this code and place it in your projects folder. All code here is supplied under the Microsoft Public Licence, found here: http://ajaxcontroltoolkit.codeplex.com/license

The code:

To start with, you’ll need a Close Button. The close button is 15 pixels by 15 pixels. I have created one based on the Internet Explorer X button used to stop web pages from executing. You can download my image by right clicking this image and saving it onto your local drive:

Close Button for Ajax Control Toolkit calendar extender control

This close button image is called close-button.gif (note that it’s a dash, not an underscore).

Copy this image into the Calendar folder in the Ajax Control Toolkit, and set it’s Build Action to Embedded Resource. This is important, as without it, the image is not contained within the Ajax Control Toolkit dll.

Adding the close button image

Adding the close button image

Next, you need to tell the compiler about the image by making it a Web Resource. This is done by adding an entry at the top of the CalendarExtender.cs file, as follows. Note that I am using S5/E5 to tag changes.

Original code:


#region [ Resources ]

[assembly: System.Web.UI.WebResource("AjaxControlToolkit.Calendar.CalendarBehavior.js", "text/javascript")]
[assembly: System.Web.UI.WebResource("AjaxControlToolkit.Calendar.Calendar.css", "text/css", PerformSubstitution = true)]
[assembly: System.Web.UI.WebResource("AjaxControlToolkit.Calendar.arrow-left.gif", "image/gif")]
[assembly: System.Web.UI.WebResource("AjaxControlToolkit.Calendar.arrow-right.gif", "image/gif")]
#endregion

Modified code:


#region [ Resources ]

[assembly: System.Web.UI.WebResource("AjaxControlToolkit.Calendar.CalendarBehavior.js", "text/javascript")]
[assembly: System.Web.UI.WebResource("AjaxControlToolkit.Calendar.Calendar.css", "text/css", PerformSubstitution = true)]
[assembly: System.Web.UI.WebResource("AjaxControlToolkit.Calendar.arrow-left.gif", "image/gif")]
[assembly: System.Web.UI.WebResource("AjaxControlToolkit.Calendar.arrow-right.gif", "image/gif")]
//S5
[assembly: System.Web.UI.WebResource("AjaxControlToolkit.Calendar.close-button.gif", "image/gif")]
//E5
endregion

Next, we want to add a property to the Calendar Extender to allow us to turn the close button display on or off – not everyone wants a close button on their calendar. Most people are probably content with clicking off the calendar. I will add a property called ShowCloseButton to the extender control. In the CalendarExtender.cs file, I copy the EnabledOnClient property and paste it to the location next to it. Then I rename the variables to be consistent with the property I want.

Code added under EnabledOnClient property:


//S5
[DefaultValue(false)]
[ExtenderControlProperty]
[ClientPropertyName("showCloseButton")]
public virtual bool ShowCloseButton
{
    get { return GetPropertyValue("ShowCloseButton", false); }
    set { SetPropertyValue("ShowCloseButton", value); }
}
//E5

The ClientPropertyName attribute contains the client-side javascript variable name. So next we go into the CalendarBehavior.js file and add in a couple of javascript variables. The first is the showCloseButton variable, shown above, and the second is the placeholder variable for the close button html content that will be created when the close button is required to be displayed. This code goes in the declarations section of the CalendarBehavior.js file. I put mine just below the declaration for this._nextArrow = null;


/*S5*/
this._showCloseButton = false;
this._closeButton = null;
/*E5*/

Add the getter and setter next. I put mine just below the set_enabled function block.


//S5
get_showCloseButton: function() {
    /// &amp;amp;amp;amp;lt;value type="Boolean"&amp;amp;amp;amp;gt;
    /// Whether this behavior is available for the current element
    /// &amp;amp;amp;amp;lt;/value&amp;amp;amp;amp;gt;

    return this._showCloseButton;
},
set_showCloseButton: function(value) {
    if (this._showCloseButton != value) {
        this._showCloseButton = value;
        this.invalidate();
        this.raisePropertyChanged("showCloseButton");
    }
},
//E5

The function that builds the calendar in the first place is called _buildHeader. This is where we need to add code to test if the close button is supposed to display, create the div that contains the image, and attach the event handlers. This is also where the stylesheet class is attached to the div. The image itself is referenced from that stylesheet class, called ajax__calendar_close.


/*S5 - because the close button is floated right, it needs to go before the nextArrow div as that is
also floated right, and right floating reverses the order of display*/
if (this._showCloseButton) {
    var closeButtonWrapper = $common.createElementFromTemplate({ nodeName: "div" }, this._header);
    this._closeButton = $common.createElementFromTemplate({
        nodeName: "div",
        properties: {
            id: id + "_closeButton",
            mode: "close"
        },
        events: this._cell$delegates,
        cssClasses: ["ajax__calendar_close"]
    }, closeButtonWrapper);
}
/*E5*/

 

 Note in that code the reference to the mode property. That is the string that gets passed into the _cell_onclick event handler. So on clicking the close button image, we want the calendar to execute the same code that is executed when the Escape button is clicked. So I had a look in the _button_onkeypress function and saw the code that is being executed when the Escape key is pressed. I will copy that code into the _cell_onclick function, and add a case for the ‘close’ mode, as follows:

Original code:


case "prev":
case "next":
    this._switchMonth(target.date);
    break;

Modified code:


case "prev":
case "next":
    this._switchMonth(target.date);
    break;
/*S5*/
case "close":
    e.stopPropagation();
    e.preventDefault();
    this.hide();
    break;
/*E5*/

Finally, you need to dispose of the close button content correctly. In the dispose function, add the following modifications:

Original code:

if (this._nextArrow) {
    $common.removeHandlers(this._nextArrow, this._cell$delegates);
    this._nextArrow = null;
}

Modified code:

if (this._nextArrow) {
    $common.removeHandlers(this._nextArrow, this._cell$delegates);
    this._nextArrow = null;
}
/*S5*/
if (this._showCloseButton &amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp; this._closeButton) {
    $common.removeHandlers(this._closeButton, this._cell$delegates);
    this._closeButton = null;
}
/*E5*/

Finally, you need to add the calendar extender css class for the close button. Open the Calendar.css file, and just below the entry for .ajax__calendar_next, add the following line:


/*S5*/
.ajax__calendar_close {cursor:pointer;width:15px;height:15px;float:right;background-repeat:no-repeat;background-position:50% 50%;background-image:url(&amp;amp;amp;amp;lt;%=WebResource("AjaxControlToolkit.Calendar.close-button.gif")%&amp;amp;amp;amp;gt;);}
/*E5*/

 

Run it up, add a calendar extender, set it’s ShowCloseButton property to true, and this is what you see:

Calendar Close Button Image

Calendar Close Button Image

Note that I have deliberatelychosen a non-intrusive close button, the same size as the prev and next buttons. The close button just needs to be there – it doesn’t need to out-weigh the other elements on the calendar. I used to have a bright red button, but that is so 20th century.

If you would like to see if you’ve got the code right, I have a completed version to compare with here:

AjaxControlToolkit3.5SP1withModesAndCloseButton.zip


Sharepoint, AjaxControlToolkit, ModalPopup and DocType problems

May 4, 2009

I am currently integrating a Sharepoint web site with an ASP.Net web site. A Sharepoint web site is essentially an ASP.Net web site too, and Microsoft have provided a way to integrate exiting web sites into that, essentially by inheriting a Sharepoint master page.

My ASP.Net web site uses the AjaxControlToolkit. The problem is, the AjaxControlToolkit by default uses the XHTML DocType. Sharepoint doesn’t actually have a DocType specified, which means it defaults to HTML 4.0 transitional. That mode is ok. There are a number of reasons why you might want to use HTML 4.0 transitional. Most of the component libraries out there still use the old DocTypes because they offered a richer set of functionality. Recently I used the Intersoft control suite. These operates very strangely under  XHTML, and in fact they don’t support that mode.

But back to Sharepoint and the AjaxControlToolkit. I was trying to use the modal popup extender, so that I can have one of my forms displayed on clicking a button on the page. Without the DocType of XHTML, every time I clicked on the button, it would display the bottom-right hand corner of the dialog in the upper left-hand corner of my form, effectively clipping the control and making the control otherwise useless.

There are workarounds. You can go into the Modal Popup Extender and set the X and Y co-ordinates. The problem with that is that often you don’t know the exact co-ordinates where you want the popup to be displayed. Part of the desire to use the modal popup is because it centres on the page and will move with the page when you scroll. It also repositions itself when you adjust the form.

The answer to this is to obtain a re-write of the getClientBounds javascript function that goes into the AjaxControlToolkit source code, common.js file. This re-write may be obtained from here: http://forums.asp.net/t/1002123.aspx?PageIndex=1 and was put together by Umer Farooq of Islamabad.

Here it is repeated below:


getClientBounds : function() {
        /// &amp;amp;lt;summary&amp;amp;gt;
        /// Gets the width and height of the browser client window (excluding scrollbars)
        /// &amp;amp;lt;/summary&amp;amp;gt;
        /// &amp;amp;lt;returns type="Sys.UI.Bounds"&amp;amp;gt;
        /// Browser's client width and height
        /// &amp;amp;lt;/returns&amp;amp;gt;

        var clientWidth;
        var clientHeight;
        switch(Sys.Browser.agent) {
            case Sys.Browser.InternetExplorer:
                if (document.documentElement &amp;amp;amp;&amp;amp;amp; document.documentElement.clientWidth)
                    clientWidth = document.documentElement.clientWidth;
                else if (document.body)
                    clientWidth = document.body.clientWidth;
                //clientWidth = document.documentElement.clientWidth;
                if (document.documentElement &amp;amp;amp;&amp;amp;amp; document.documentElement.clientHeight)
                    clientHeight = document.documentElement.clientHeight;
                else if (document.body)
                    clientHeight = document.body.clientHeight;
                //clientHeight = document.documentElement.clientHeight;               
                break;
            case Sys.Browser.Safari:
                clientWidth = window.innerWidth;
                clientHeight = window.innerHeight;
                break;
            case Sys.Browser.Opera:
                clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
                break;
            default:  // Sys.Browser.Firefox, etc.
                clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
                break;
        }
        return new Sys.UI.Bounds(0, 0, clientWidth, clientHeight);
    },

Basically, it works by detecting various instances of objects on the client in the Internet Explorer part of th code. If XHTML is present, document.documentElement.clientWidth exists, otherwise it will use the default document.body.clientWidth.

There is a second issue, that is to do with the positioning of the modal background. Basically, because the modal popup defaults to position:fixed, the background positions itself within the content part of the page. This is not desirable, as we want it to make the entire page inoperable while our dialog is showing. I actually don’t like the use of position:fixed, because it is unavailable in IE6. To solve this problem, simply find references to ‘fixed’ in the ModalPopupBehavior.js file in the AjaxControlToolkit and change them to ‘absolute’. You might want to alter the left and top values for the background element in this file too. I changed mine from zero (0) to minus 1 (-1).