|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionThere's a lot of different aspects in creating a custom ASP.NET web control. The user of the control should only need to place the control on the page, and after that the control should be self sustained. In other words, register client-side scripts, client-side CSS, and client-side images. This article will guide you in creating a custom control that uses web resources for scripts, CSS, and images, and show you how to init JavaScript code for each control on the page. We'll cover the basics of using classes that implements the Using the codeThe first thing that we need to do is create all the web resources. We place all the resources in different folders (css, js, img). Select the content in each folder and right click / Properties. Set the build action to Embedded Resource for all of these files. The next thing is to register the resources in the AssemblyInfo.cs: //Cropping logic
[assembly: WebResource("Anders.Web.Controls.js.cropper.js", "text/javascript")]
//Script lib
[assembly: WebResource("Anders.Web.Controls.js.lib.builder.js", "text/javascript")]
[assembly: WebResource("Anders.Web.Controls.js.lib.dragdrop.js", "text/javascript")]
[assembly: WebResource("Anders.Web.Controls.js.lib.effects.js", "text/javascript")]
[assembly: WebResource("Anders.Web.Controls.js.lib.prototype.js", "text/javascript")]
[assembly: WebResource("Anders.Web.Controls.css.cropper.css",
"text/css", PerformSubstitution = true)]
[assembly: WebResource("Anders.Web.Controls.img.marqueeHoriz.gif", "image/gif")]
[assembly: WebResource("Anders.Web.Controls.img.marqueeVert.gif", "image/gif")]
Note that we have used the background: transparent url('<%=WebResource(
"Anders.Web.Controls.img.marqueeHoriz.gif")%>') repeat-x 0 0;
The next step is to create the cropper control class and let it inherit from I also inherit from Let’s add all the different controls that will be our control. private Image image = new Image();
private HiddenField cropCords = new HiddenField();
private CropAreaCordinates cropArea = new CropAreaCordinates();
protected override void CreateChildControls()
{
EnsureChildControls();
CheckForHandler();
image.ID = "cropImage";
cropCords.ID = "cords";
Controls.Add(cropCords);
Controls.Add(image);
base.CreateChildControls();
}
The image will be the main user interface for the cropper, and the hidden field will store all of the cropping coordinates so that the user can postback them right back to the control. We also need to set the IDs of the child controls since these will not get auto-generated. The IDs will inherit the parent ID as prefix. Our control implements the public bool LoadPostData(string postDataKey,
System.Collections.Specialized.NameValueCollection postCollection)
{
string v = postCollection[postDataKey + "$cords"];
if (!string.IsNullOrEmpty(v))
{
string[] values = v.Split(';');
cropArea.X = int.Parse(values[0]);
cropArea.Y = int.Parse(values[1]);
cropArea.Width = int.Parse(values[2]);
cropArea.Height = int.Parse(values[3]);
//This values are not saved in client hiddenfield,
//we retrive them from viewstate instead
cropArea.MinWidth = MinWidth;
cropArea.MinHeight = MinHeight;
return true;
}
else
return false;
}
We only parse the hidden field values that will be used later on. Now, it’s time for the initialization of the client-side scripts and properties. This is done in the protected override void OnPreRender(EventArgs e)
{
if (CropEnabled)
{
InitClientCrop();
InitImages();
float h = (float)CroppedImageHeight / (float)CroppedImageWidth;
IFormatProvider culture = new CultureInfo("en-US", true);
string height = h.ToString(culture);
image.Attributes["onload"] = string.Format("InitCrop(this.id,
{0},{1},{2},{3},{4},{5}, '{6}', {7}, {8}, {9});",
AllowQualityLoss ? 0 : cropArea.MinWidth,
AllowQualityLoss ? 0 : cropArea.MinHeight,
cropArea.X,
cropArea.Y,
cropArea.Width,
cropArea.Height,
cropCords.ClientID,
CaptureKeys.ToString().ToLower(),
MaintainAspectRatio ? 1 : 0,
MaintainAspectRatio ? height : "0"
);
image.ImageUrl = string.Format("{0}?cropCacheId={1}", httpHandlerPath, CacheKey);
cropCords.Value = string.Format("{0};{1};{2};{3}", cropArea.X,
cropArea.Y, cropArea.Width, cropArea.Height);
Page.RegisterRequiresPostBack(this);
}
else
image.Attributes.Remove("onload");
base.OnPreRender(e);
}
First, we init the client-side scripts in the We want this control to work with several instances on the same page. To make this happen, we need to fire the init script for each control. This is done using the The init script will instantiate the cropper JavaScript class and give it all its properties. Note that we also set the path of the image and that we supply the cache ID in the path, we’ll get back to this. Remember that the class implements The script resource register process is like this: first, we get the relative path to the resource like this: string protoTypePath = this.Page.ClientScript.GetWebResourceUrl(typeof(ImageCropper),
"Anders.Web.Controls.js.lib.prototype.js");
Then, we register it on the page using the this.Page.ClientScript.RegisterClientScriptInclude("prototype.js", protoTypePath);
We also need to register the CSS resource on the page. There is no built-in method for this, so it’s a bit of plumbing. if (Page.Header.FindControl("cropCss") == null)
{
HtmlGenericControl cssMetaData = new HtmlGenericControl("link");
cssMetaData.ID = "cropCss";
cssMetaData.Attributes.Add("rel", "stylesheet");
cssMetaData.Attributes.Add("href",
Page.ClientScript.GetWebResourceUrl(typeof(ImageCropper),
"Anders.Web.Controls.css.cropper.css"));
cssMetaData.Attributes.Add("type", "text/css");
cssMetaData.Attributes.Add("media", "screen");
Page.Header.Controls.Add(cssMetaData);
}
Since there can be more then one control, we need to check if any other control already has registered the CSS. This is done using the After the scripts have been registered, we need to render the client-side image that will be presented to the user. private void CreateImage()
{
ImageManager imageManager = new ImageManager();
CropData cropData = imageManager.GetImageCropperDisplayImage(CroppedImageWidth,
CroppedImageHeight, SourceImage, JpegQuality);
cropArea = cropData.CropAreaCordinates;
//Min width and min height is not sent to client's hiddenfield
//so we need to save this in viewstate.
MinWidth = cropArea.MinWidth;
MinHeight = cropArea.MinHeight;
//Saves buffer to cache
SetBuffer(string.Empty, cropData.Buffer);
}
I will not go into the details on how the images are handled, you can check out the Last but not least, we save the buffer to the cache. The cache code is a pretty big part of this control, but I will not go into details. All you need to know is that I store a GUID in the control’s view state and that I use this GUID as a cache key. The Application layer also takes care of the logic for cropping the image. So now, we have registered all the scripts and resources, we have also created a server-side image. But, how do we present the image to the client? We could let the user of the control create an ASPX page that will return an image. But, remember that the idea of this control was that we only wanted the user to drag one control onto the page and it should do all the magic itself? To force the user to create an ASPX page does not match that profile. So, the solution is the You can register any HTTPHandler and reference it to a path in the web.config. <add path="CropImage.axd" verb="*"
type="Anders.Web.Controls.ImageCropperHttpHandler" validate="false" />
When ASP.NET gets a request for the specific path, in this case, "CropImage.axd", it will instantiate the class defined in the The only requirement of a HTTPHandler class is that it implements the public class ImageCropperHttpHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
string cacheId = context.Request.QueryString["cropCacheId"];
byte[] buffer = context.Cache[cacheId] as byte[];
context.Response.ContentType = "image/jpeg";
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
}
The The All this method does is to parse the The only downside of using HTTPHandlers is that they require you to register data in the web.config. So we add a method to validate that the user of the control has done just that. private void CheckForHandler()
{
if (httpHandlerPath == null)
{
HttpHandlersSection handlerSection =
WebConfigurationManager.GetWebApplicationSection("system.web/httpHandlers")
as HttpHandlersSection;
bool foundHandler = false;
Type type = typeof(ImageCropperHttpHandler);
string handlerName = type.ToString();
string fullHandlerName = type.AssemblyQualifiedName;
foreach (HttpHandlerAction action in handlerSection.Handlers)
if (action.Type == handlerName || action.Type == fullHandlerName)
{
foundHandler = true;
httpHandlerPath = action.Path.StartsWith("~") ?
string.Empty : "~/" + action.Path;
break;
}
if (!foundHandler)
throw new ApplicationException(string.Format("The HttpHandler {0} is" +
" not registered in the web.config", handlerName));
}
}
This method is called from the One last note, all the properties for this control uses the view state. I’ve seen lots of articles where people have used standard properties. This may work if you set the properties each time you load the page. But, this is not how the standard .NET controls work. You should always implement properties using the view state, it’s not up to you to decide if a user of your control likes or dislikes view state. If he/she does not want to use view state, it’s just a matter of turning it off. History
|
||||||||||||||||||||||