« Example: Call Private Method w/ Reflection | Main | SmartPart and AjaxBasePart get Together »

AjaxBasePart: Easy ASP.NET 2.0 AJAX Extensions 1.0 and Office SharePoint Server 2007

I have noticed quite a few posts/projects out there that focus on using ASP.NET AJAX within custom MOSS web parts.  Mike Ammerlaan has a great post on some of the background around AJAX and MOSS

This post describes what my team and I have been using for the past couple of months. It is a simple base class called AjaxBasePart.

Background:
I developed a .NET class in early November that allowed my team to take advantage of the MS AJAX Extensions from custom MOSS web parts.  There were a number of problems that I did not resolve on my own though.

For the next month or so I worked on and off with the AJAX Extensions and MOSS product teams and with our powers combined we were able to come up with the AjaxBasePart class that custom MOSS web parts can derive from and fully enables all AJAX Extensions functionality within MOSS.

Very Simple Setup:
There is no need to modify master pages after the AJAX Extensions have been installed and the web.config is setup your web parts will manage the registration of a shared ScriptManager or in the case that one exists use that. If I'm missing anything please notify me in the comments and I will update.

  1. Download and install ASP.NET 2.0 AJAX Extensions 1.0
  2. Configure your MOSS web.config to support ASP.NET AJAX 1.0
    Mike's post covers most of the configuration you need to support AjaxBasePart within your own MOSS environment. I've listed below a couple of points that you should be aware of when reading his article if you are using the AjaxBasePart
    • You can skip the "Adding a ScriptManager into a SharePoint MasterPage" section. No modification of the .master page is necessary with AjaxBasePart
    • Leave the EnsureUpdatePanelFixups method out of your custom web parts, that is handled by the AjaxBasePart.
  3. Add the AjaxBasePart class (at the end of this post) to your solution and derive all custom web parts from CapDes.SharePoint.AjaxBasePart instead of Microsoft.SharePoint.WebPartPages.WebPart.

Support:
If you are looking for support I will do my best to assist via the comments on this post.  This is in no way supported by Microsoft.

Credits:
The following Microsoft employees assisted me in the development of the AjaxBasePart.  Thanks guys!

Bonus:
You will also notice a public RegisterError method on the AjaxBasePart.  I find it to be a clean way to show users web part related error messages in a common way.

To use all you need to do is; from your custom web part call the RegisterError message and pass the string that you would like displayed to the user.

base.RegisterError("Some error message.");

Code:

using System;

using System.Xml.Serialization;

using System.Web.UI.WebControls;

using System.Web.UI;

using System.Drawing;

using System.Web;

using Microsoft.SharePoint.Utilities;

using Microsoft.SharePoint.WebPartPages;

 

namespace CapDes.SharePoint

{

   /// <summary>

   /// AjaxBasePart allows Microsoft ASP.NET AJAX Extensions to work within Microsoft Office SharePoint Server 2007 webparts.

   /// </summary>

   [XmlRoot(Namespace = "CapDes.SharePoint.AjaxBasePart")]

   [CLSCompliant(false)]

   public abstract class AjaxBasePart : WebPart

   {

        private string _ValidationGroupId;

        private ValidationSummary _ErrorContainer;

        private ScriptManager _AjaxManager;

 

        /// <summary>

        /// Exposes the Page's script manager. The value is not set until after OnInit

        /// </summary>

        [WebPartStorage(Storage.None)]

        public ScriptManager AjaxManager

        {

            get { return _AjaxManager; }

            set { _AjaxManager = value; }

        }

 

        /// <summary>

        /// Oninit fires before page load. Modifications to the page that are necessary to support Ajax are done here.

        /// </summary>

        protected override void OnInit(EventArgs e)

        {

            base.OnInit(e);

 

            //get the existing ScriptManager if it exists on the page

            _AjaxManager = ScriptManager.GetCurrent(this.Page);

 

            if (_AjaxManager == null)

            {

               //create new ScriptManager and EnablePartialRendering

               _AjaxManager = new ScriptManager();

               _AjaxManager.EnablePartialRendering = true;

 

               // Fix problem with postbacks and form actions (DevDiv 55525)

               Page.ClientScript.RegisterStartupScript(typeof(AjaxBasePart), this.ID, "_spOriginalFormAction = document.forms[0].action;", true);

 

               //tag:"form" att:"onsubmit" val:"return _spFormOnSubmitWrapper()" blocks async postbacks after the first one

               //not calling "_spFormOnSubmitWrapper()" breaks all postbacks

               //returning true all the time, somewhat defeats the purpose of the _spFormOnSubmitWrapper() which is to block repetitive postbacks, but it allows MS AJAX Extensions to work properly

               //its a hack that hopefully has minimal effect

               if (this.Page.Form != null)

               {

                    string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];

                    if (!string.IsNullOrEmpty(formOnSubmitAtt) && formOnSubmitAtt == "return _spFormOnSubmitWrapper();")

                    {

                        this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";

                    }

 

                    //add the ScriptManager as the first control in the Page.Form

                    //I don't think this actually matters, but I did it to be consistent with how you are supposed to place the ScriptManager when used declaritevly

                    this.Page.Form.Controls.AddAt(0, _AjaxManager);

               }

            }

        }

 

        /// <summary>

        /// Needs to be called to ensure that the ValidationSummary control is registered on the page.  Any child web parts will need to have base.CreateChildControls() at the top of their own CreateChildControls override.

        /// </summary>

        protected override void CreateChildControls()

        {

            base.CreateChildControls();

 

            if (!this.Controls.Contains(_ErrorContainer))

            {

               _ValidationGroupId = Guid.NewGuid().ToString();

 

               _ErrorContainer = new ValidationSummary();

               _ErrorContainer.ID = "_ErrorContainer";

               _ErrorContainer.ValidationGroup = _ValidationGroupId;

               _ErrorContainer.BorderStyle = BorderStyle.Solid;

               _ErrorContainer.BorderWidth = Unit.Pixel(3);

               _ErrorContainer.BorderColor = Color.Red;

               this.Controls.Add(_ErrorContainer);

            }

        }

 

        /// <summary>

        /// Used to provide a common way to display errors to the user of the current web part.

        /// </summary>

        /// <param name="message">Description of the error that occured.</param>

        public void RegisterError(string message)

        {

            if (this.Controls.Contains(_ErrorContainer))

            {

               //this way of generating a unique control id is used in some of the OOB web parts

               int uniqueCounter;

               if (HttpContext.Current.Items["GetUniqueControlId"] != null)

               {

                    uniqueCounter = (int)HttpContext.Current.Items["GetUniqueControlId"];

               }

               else

               {

                    uniqueCounter = 0;

               }

               uniqueCounter++;

               HttpContext.Current.Items["GetUniqueControlId"] = uniqueCounter;

 

               //create a custom validator to register the current error message with the ValidationSummary control

               CustomValidator cv = new CustomValidator();

               cv.ID = string.Concat("_Error_", uniqueCounter);

               cv.ValidationGroup = _ValidationGroupId;

               cv.Display = ValidatorDisplay.None;

               cv.IsValid = false;

               cv.ErrorMessage = message;

 

               this.Controls.Add(cv);

            }

            else

            {

               //if RegisterError is called before the CreateChildControls override in AjaxBasePart then transfer the user to an error page using the SPUtility

               SPUtility.TransferToErrorPage("The CreateChildControls function of the AjaxBasePart has not been called.  You probably need to add \"base.CreateChildControls()\" to the top of your CreateChildControls override.");

            }

        }

   }

}

TrackBack

TrackBack URL for this entry:
http://www.capdes.com/mt/mt-tb.cgi/10

Listed below are links to weblogs that reference AjaxBasePart: Easy ASP.NET 2.0 AJAX Extensions 1.0 and Office SharePoint Server 2007:

» ajax and sharepoint sittin' in a tree from Method ~ of ~ failed
ajax and sharepoint sittin' in a tree [Read More]

» ASP.NET AJAX and SharePoint from ASP.NET AJAX Team Blogs
One of the questions I was recently asked at a user group meeting in Europe was whether it was possible [Read More]

» ASP.NET AJAX and SharePoint from The estatic reading list
One of the questions I was recently asked at a user group meeting in Europe was whether it was possible [Read More]

» ASP.NET AJAX and SharePoint from Top ASP.NET Items
One of the questions I was recently asked at a user group meeting in Europe was whether it was possible [Read More]

» ASP.NET AJAX and SharePoint from 郑军的博客
One of the questions I was recently asked at a user group meeting in Europe was whether it was possible [Read More]

» Ajax , ajax et SharePoint from The Mit's Blog
Tiens, un sujet désormais bien à la mode. Je ne pense pas vous apprendre que Scott Guthrie vient justement [Read More]

» SmartPart for SharePoint - ASP.NET AJAX Support from Community Blogs
There has been a lot of buzz around SharePoint support for ASP.NET AJAX the last couple of days, resulting [Read More]

» ASP.NET AJAX Integration with SharePoint from Public Sector Developer Weblog
ASP.NET AJAX integration with Office SharePoint Server 2007 and Windows SharePoint Services 3.0 has been [Read More]

» SmartPart Update (Beta) Released with ASP.NET AJAX Support from Public Sector Developer Weblog
Wow, Jan has released an update to his SmartPart that provides support for ASP.NET AJAX . In his implementation, [Read More]

» SharePoint and ASP.NET AJAX from Andrew Coates ::: MSFT
I had some great questions after my session at the ISV Innovation Day in Melbourne yesterday. One was [Read More]

» ASP.NET AJAX and SharePoint from .NET and gremlins inside
One of the questions I was recently asked at a user group meeting in Europe was whether it was possible [Read More]

» SmartPart for SharePoint: now with AJAX support from David Boschmans Weblog
During last TechEd in Barcelona , Jan and Patrick delivered a session " Building Web Parts the Smart [Read More]

» 本(两?)周ASP.NET英文技术文章推荐[02/11 - 02/24] from Dflying Chen
摘要给各位朋友拜个晚年,下面是两周的推荐,共有9篇文章:ASP.NETAJAX和SharePoint用C#编写Vista的Gadget.NETFramework编年史你还在手工编写添... [Read More]

» ASP.NET AJAX和SharePoint from Joycode@Ab110.com
【原文地址】 ASP.NET AJAX and SharePoint 【原文发表日期】 Tuesday, February 20, 2007 11:45 PM 最近在欧洲的一个用户组织会议上我被问到的一个问题是,是否能够在SharePoint [Read More]

» ASP.NET AJAX和SharePoint from 烟雨客
ASP.NETAJAX和SharePoint 【原文地址】ASP.NETAJAXandSharePoint【原文发表日期】Tuesday,February20,200711:45... [Read More]

» Using a SPGridView inside an ASP.net Ajax UpdatePanel from Share This Point
Using a SPGridView inside an ASP.net Ajax UpdatePanel [Read More]

» Integrating SharePoint with other portals and web applications from Jose Barreto's Blog
Introduction Maybe you’re lucky enough to work for a company that has standardized on SharePoint portals [Read More]

» Integrating ASP.NET AJAX with MOSS!! from Neven Magdy's Blog
Mike posted a very very nice article about how to integrate AJAX with MOSS . step by step how to install... [Read More]

» SmartPart for SharePoint - ASP.NET AJAX Support from Aggregated Blogs
There has been a lot of buzz around SharePoint support for ASP.NET AJAX the last couple of days, resulting [Read More]

» AJAX and MOSS from My Two Bits
I've heard a few of you ask about AJAX in MOSS 2007. Yeah, OOB MOSS doesn't support the ASP.NET AJAX [Read More]

» Control System Design from Control System Design
GetDesignTimeHtml() method, which is called each time your control needs to be repres [Read More]

» Integrating SharePoint with other portals and applications from Community
As more and more companies get past the pilot stage with their SharePoint 2007 deployments and start [Read More]

» Integrating SharePoint with other portals and applications from Mirrored Feeds
As more and more companies get past the pilot stage with their SharePoint 2007 deployments and start [Read More]

» quick payday from quick paydays
Hope this information helps, I would be happy to answer questions via the site forums. [Read More]

» Kicrosoft Sharepoint from Kicrosoft Sharepoint
en-us sharepointserver FX33.aspx Are you finding every computer [Read More]

» Can’t Africans abroad transfer skills from african art body
Can’t Africans abroad transfer skills online?New Vision, Uganda -Apr 10, 2007To be sure, a few richer clinics in African countries like South [Read More]

» Ribfest shirts held dear to from Neat public string bikini pics pictures
Ribfest shirts held dear to many heartsChicago Daily Herald, IL -Jul 2, 2007“I like that hot-pink shirt,” said Ann Marie Siwik, a [Read More]

» American Tourism Society Board Elects from michael jordan video highlight
American Tourism Society Board Elects David Parry as Chairman of ...Forimmediaterelease.net (Press Release), HI -16 hours agoThe newly elected ATS leaders succeed [Read More]

» MDA helps man to deliver from birthday free glitter graphic happy myspace
MDA helps man to deliver baby son in car over the cellphoneJerusalem Post, Israel -Sep 5, 2007The baby should be placed in [Read More]

» Mission Aviation Fellowship Playing Vital from herbert spencer theory of social change
Mission Aviation Fellowship Playing Vital Role in Bangladesh ...NewsBlaze, CA -20 hours agoAn aerial view from an MAF aircraft shows the devastation [Read More]

» Nigeria: World Champions! (AllAfrica.com) from bd company pthc
IN only the fourth FIFA U-17 World Cup final to go to penalty kicks, Nigeria's Golden Eaglets kept their cool [Read More]

» Torrance police rescue infant locked from department mervyns online store
Torrance police rescue infant locked in van while mom shoppedFort Wayne Journal Gazette, IN -23 hours agoShoppers called police at 6:35 pm [Read More]

» For Nurses, It's Black and from discount uniform and scrubs
For Nurses, It's Black and WhiteThe Ledger, FL -Mar 30, 2007"We've been selling a lot of black and white," said Patti Tutwiler, [Read More]

» Organ donor's parents meet recipient's from denise milani video
CRESTVIEW — Shane Moody enjoyed performing in dramas. Eddie Merritt has never been in a play. Shane liked to knit. [Read More]

» Troubleshooter: the cloudy LCD - from Top quality kdl sony xbr2
The most recent case of this to cross Troubleshooter's desk was Graham Thompson, who had not one but two Bravia [Read More]

» Lagat grabs unique double for from afrika wrestler vs men
Lagat grabs unique double for USCNN International -30 minutes agoOSAKA, Japan (AP) -- Kenyan-born Bernard Lagat of the United States completed [Read More]

» Ron Miller returns to coaching from mobile home retirement community
By Thomas Pope Ron Miller could have chosen to spend his retirement at a home he owns in Long Beach, [Read More]

» Missing Mount Angel man found from battery car powered
Linvill said he stayed with his vehicle and conserved fuel and battery power, Lumley said. Linvill ran his engine and [Read More]

» Buffalo Announces First External Blu-ray from dvd solution storage
SlashGearBuffalo Announces First External Blu-ray HD DVD Player of Its KindReuters -23 hours ago...storage and memory solutions today announced the MediaStation [Read More]

» Review: Clear Harmony Noise Canceling from Top quality bose earphones review
... the Clear Harmony Linx Audio Headphones by AblePlanet compare favorably to the competition, that being ‘BOSE’ in both price [Read More]

» Microsogt Sharepoint from Microsogt Sharepoint
sharepoint Provides types and members for working with a top-level [Read More]

» Interview: Mizuguchi Talks Rez HD from buy play wii
In general, maybe not this game, but what do you think about making games for the Wii? Wii is [Read More]

» Web Parts & AJAX from Vu's Technical Notepad
A few good blog entries that talk about SharePoint web parts and AJAX: http://sharethispoint.com/archive/2007/02/28/Using-a-SPGridView-inside-an-ASP.net-Ajax-UpdatePanel.aspx [Read More]

» Web Parts & AJAX from Noticias externas
A few good blog entries that talk about SharePoint web parts and AJAX: http://sharethispoint.com/archive [Read More]

» Fifa 08 Wii from Fifa 08 Wii
We tried sticking the Wii Remote to the bottom of a sock. For [Read More]

» penis enlargement from penis enlargement
As the world wide web continues to grow pass webpages, we will attempt to bring them to you. [Read More]

» Pilot Headphones from Pilot Headphones
Solitude headphones are almost as good as the Bose noise cancelling headph [Read More]

» nintendo wii usb connector driver downloads from direcss nintendo wii
super mario galaxy nintendo games super mario galaxy hints [Read More]

About

View Eric Schoonover's profile on LinkedIn
 

Follow me on Twitter
 
© Copyright 2007, Eric Schoonover

Search

Post Info

This page contains a single entry from the blog posted on February 19, 2007 9:38 PM.

The previous post in this blog was Example: Call Private Method w/ Reflection.

The next post in this blog is SmartPart and AjaxBasePart get Together.

Many more can be found on the main index page or by looking through the archives.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.