Update Panel .NET

Exploring Microsoft ASP.NET AJAX and jQuery

Archive for the ‘ASP.NET’ Category

Microsoft AJAX Library Preview 6 Available

leave a comment »

Written by tzkuei

October 19, 2009 at 8:59 am

ASP.NET AJAX Validator

with one comment

As promised weeks ago, here is my ASP.NET AJAX validation control “framework”.

To create your own AJAX validation control:

1. Create a new class which inherits UPDN.AjaxValidator:

public class YourValidator : UPDN.AjaxValidator { /*...*/ }

2. Provide a public static method to perform the validation, the signature of the method should be:

public static ValidationResult YourValidationMethod(string value)

3. Override OnServerValidate to call your public static validation method:

protected override bool OnServerValidate(string value)
{
    var result = YourValidationMethod(value);
    return result.IsValid;
}

4. Override GetScriptReferences to include your client-side script:

protected override void GetScriptReferences(ScriptReferenceCollection references)
{
    base.GetScriptReferences(references);
    references.Add(new ScriptReference("~/Scripts/YourValidator.js"));
}

5. Create the client-side control for your validation control, which inherits UPDN.AjaxValidator:

Type.registerNamespace("Example");
Example.YourValidator = function(element) {
    Example.YourValidator.initializeBase(this, [element]);
};
Example.YourValidator.prototype = {
    // Override validate to do pre-validation checks.
    validate: function(val, args, event) {
        Example.YourValidator.callBaseMethod(this, "validate", [val, args, event]);
    },
    // Override validated to do post-validation stuff.
    validated: function(result, event) {
        var val = this.get_element();
        // Do your custom validation message display stuff here!
    }
};
Example.YourValidator.registerClass("Example.YourValidator", UPDN.AjaxValidator);

6. Expose the YourValidationMethod method in YourValidator class as a “Page Method” in the code-behind:

[WebMethod]
public static ValidationResult YourValidationPageMethod(string domain)
{
    return YourValidator.YourValidationMethod(domain);
}

7. Add reference to your validation control in Web.config:

<pages>
    <controls>
    ...
        <add tagPrefix="example" namespace="Example"/>
    </controls>
</pages>

8. Add the validation control to your page, set the PageMethodName property to “YourValidationPageMethod”:

<example:YourValidator runat="server" ID="YourValidator1" ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Your error message" PageMethodName="YourValidationMethod" ProgressIndicatorCssClass="wait" />

Download the (VS.NET 2008) solution from my SkyDrive.

Written by tzkuei

September 11, 2009 at 1:02 pm

How to invoke ASP.NET Page Methods using jQuery

with one comment

Why do I want to invoke ASP.NET Page Methods using jQuery?

  • I do not want the ScriptManager to generate any proxy code in my page source, i.e. set EnablePageMethods to “false”.
  • I want to make the call synchronous! (N.B. You should avoid making synchronous calls!)

Show me the code:

$.ajax({
    async: true, /* set this to false to make a synchronous call */
    contentType: "application/json; charset=utf-8",
    data: Sys.Serialization.JavaScriptSerializer.serialize({ arg1, arg2, etc... }),
    dataType: "json",
    type: "post",
    url: "application_path/page.aspx/page_method_name",
    success: function(result) {
        // Insert your success handler code here.
    }
});

I am assuming the Microsoft AJAX Library is included on the page, and I am using Sys.Serialization.JavaScriptSerializer.serialize to prepare the page method call arguments into JSON.

Written by tzkuei

July 2, 2009 at 12:51 pm

Posted in ASP.NET, jQuery

jQuery (ASP.NET) Validator Callout Plugin

with 33 comments

This plugin enhances the presentation of ASP.NET validator controls, by displaying the validation error message inside a (popup) callout box, like this:

Screen capture of validator callout example

This plugin is similar to the ValidatorCallout extender in the ASP.NET AJAX Control Toolkit.

Download

Download the latest release from http://plugins.jquery.com/project/updnValidatorCallout

Usage

Simply call jQuery.updnValidatorCallout.attachAll() to attach the plugin to all validators on your page.

For example:

jQuery(document).ready(function($) {
    $.updnValidatorCallout.attachAll();
});

You can style the callout box and pointer by specifying the ”calloutCssClass” and “pointerCssClass” options:

jQuery(document).ready(function($) {
    $.updnWatermark.attachAll({
        calloutCssClass: "myValidatorCallout",
        pointerCssClass: "myValidatorCalloutPointer",
    );
});

You can also style the input element and all associated labels that are in error state by specifying the “errorInputCssClass” and “errorLabelCssClass” options:

jQuery(document).ready(function($) {
    $.updnWatermark.attachAll({
        calloutCssClass: "myValidatorCallout",
        pointerCssClass: "myValidatorCalloutPointer",
        errorInputCssClass: "myValidationErrorInput",
        errorLabelCssClass: "myValidationErrorLabel" }
    );
});

Alternatively, you can simply style the default CSS classes provided by the plugin: 

.updnValidatorCallout
{
    background-color: #fcc;
    color: #900;
    padding: 5px;
    margin: -5px 0 0 10px;
    position: relative;
}
.updnValidatorCalloutPointer
{
    position: absolute;
    left: 0;
    top: 7px;
    margin: 0 0 0 -10px;
    width: 0;
    height: 0;
    border-top: 7px solid transparent;
    border-bottom: 7px solid transparent;
    border-right: 10px solid #fcc;
    border-left: 0;
}
.updnValidationErrorInput
{
    background-color: #fcc;
}
.updnValidationErrorLabel
{
    color: #900;
}

N.B. For the triangular pointer, I used a pure CSS solution as detailed in this article.

Written by tzkuei

April 19, 2009 at 9:34 pm

Posted in ASP.NET, CSS, DOM, HTML, JavaScript, jQuery

No connection could be made because the target machine actively refused it

with 6 comments

I was building a simple feedback form for a website using Visual Studio 2008 on Windows Vista (Ultimate).  The code-behind used System.Net.Mail.SmtpClient to send e-mails, but when I started the page, I got this exception:

[SocketException (0x274d): No connection could be made because the target machine actively refused it 127.0.0.1:25]
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239
System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224

[WebException: Unable to connect to the remote server]
System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) +5420699
System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) +202
System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) +21
System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +332
System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) +160
System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) +159
System.Net.Mail.SmtpClient.GetConnection() +35
System.Net.Mail.SmtpClient.Send(MailMessage message) +1213

[SmtpException: Failure sending mail.]
System.Net.Mail.SmtpClient.Send(MailMessage message) +1531
PriceInvaders.Web.ContactUs.btnSubmit_Click(Object sender, EventArgs e) in C:\Projects\priceinvaders.co.uk\PriceInvaders\PriceInvaders.Web\ContactUs.aspx.cs:41
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +107
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3436

Subsequently I found out that the SMTP service is not included in Windows Vista!

Anyway, if all you require is to check if the emails are being generated correctly, you can configure ASP.NET to store e-mails in a pickup directory.  To set it up, first create the pickup directory say in “C:\InetPub\MailRoot\Pickup”, then open Internet Information Services (IIS) Manager, in the ASP.NET area double click on “SMTP E-mail”.

SMTP E-mail settings

Select the “Store e-mail in pickup directory:” option and browse to “C:\InetPub\MailRoot\Pickup” then click “Apply” in the “Actions” pane. From now on, all emails created using Sys.Net.Mail.SmtpClient will be stored in the pickup directory. You can open the .eml files in Notepad or Windows Live Mail.

Written by tzkuei

January 4, 2009 at 6:22 pm

Posted in ASP.NET

Tagged with

Image Corners Extender Control

with one comment

The prevalent use of styled borders (e.g. rounded corners) by our designers have caused much debate amongst the developers as to which technique should be employed to achieve the desired result.  The Backgrounds and Borders Module in CSS Level 3 would be ideal, but we have to wait until that becomes ubiquitous.

In this post, I present to you an extender control I created to add image corners to <asp:Panel> controls.  The extender works by injecting additional <div> elements into the DOM and style each with a background image.

Below is the source code for the server-side extender control:

using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
[assembly: WebResource("UPDN.ImageCornersBehavior.js", "text/javascript")]
namespace UPDN
{
    ///

    /// Summary description for ImageCornersExtender
    ///

    [TargetControlType(typeof(Panel))]
    public class ImageCornersExtender : ExtenderControl
    {
        public string TopBorderImageUrl { get; set; }
        public string RightBorderImageUrl { get; set; }
        public string BottomBorderImageUrl { get; set; }
        public string LeftBorderImageUrl { get; set; }
        public string TopLeftCornerImageUrl { get; set; }
        public string TopRightCornerImageUrl { get; set; }
        public string BottomLeftCornerImageUrl { get; set; }
        public string BottomRightCornerImageUrl { get; set; }
        public string MiddleImageUrl { get; set; }
        protected override IEnumerable GetScriptDescriptors(Control targetControl)
        {
            var descriptor = new ScriptControlDescriptor(“UPDN.ImageCornersBehavior”, targetControl.ClientID);
            var imageUrls = new Dictionary();
            if (!string.IsNullOrEmpty(TopBorderImageUrl))
                imageUrls.Add(“t”, TopBorderImageUrl);
            if (!string.IsNullOrEmpty(RightBorderImageUrl))
                imageUrls.Add(“r”, RightBorderImageUrl);
            if (!string.IsNullOrEmpty(BottomBorderImageUrl))
                imageUrls.Add(“b”, BottomBorderImageUrl);
            if (!string.IsNullOrEmpty(LeftBorderImageUrl))
                imageUrls.Add(“l”, LeftBorderImageUrl);
            if (!string.IsNullOrEmpty(TopLeftCornerImageUrl))
                imageUrls.Add(“tl”, TopLeftCornerImageUrl);
            if (!string.IsNullOrEmpty(TopRightCornerImageUrl))
                imageUrls.Add(“tr”, TopRightCornerImageUrl);
            if (!string.IsNullOrEmpty(BottomLeftCornerImageUrl))
                imageUrls.Add(“bl”, BottomLeftCornerImageUrl);
            if (!string.IsNullOrEmpty(BottomRightCornerImageUrl))
                imageUrls.Add(“br”, BottomRightCornerImageUrl);
            if (!string.IsNullOrEmpty(MiddleImageUrl))
                imageUrls.Add(“m”, MiddleImageUrl);
            descriptor.AddProperty(“imageUrls”, imageUrls);
            yield return descriptor;
        }
        protected override IEnumerable GetScriptReferences()
        {
            yield return new ScriptReference(“UPDN.ImageCornersBehavior.js”, this.GetType().Assembly.FullName);
        }
    }
}

And the source code for the client-side behavior:

Type.registerNamespace("UPDN");
UPDN.ImageCornersBehavior = function(element) {
    UPDN.ImageCornersBehavior.initializeBase(this, [element]);
    // keys: t, l, b, r, tl, tr, bl, br
    this._imageUrls = null;
}
UPDN.ImageCornersBehavior.prototype = {
    initialize: function() {
        UPDN.ImageCornersBehavior.callBaseMethod(this, "initialize");
        var el = this.get_element();
        var imagesUrls = this.get_imageUrls();
        var containers = [];
        // create border elements
        if (imagesUrls["t"]) {
            var t = document.createElement("div");
            t.style.background = "url(" + imagesUrls["t"] + ") repeat-x top left";
            containers.push(t);
        }
        if (imagesUrls["r"]) {
            var r = document.createElement("div");
            r.style.background = "url(" + imagesUrls["r"] + ") repeat-y top right";
            containers.push(r);
        }
        if (imagesUrls["b"]) {
            var b = document.createElement("div");
            b.style.background = "url(" + imagesUrls["b"] + ") repeat-x bottom left";
            containers.push(b);
        }
        if (imagesUrls["l"]) {
            var l = document.createElement("div");
            l.style.background = "url(" + imagesUrls["l"] + ") repeat-y top left";
            containers.push(l);
        }
        if (imagesUrls["tl"]) {
            var tl = document.createElement("div");
            tl.style.background = "url(" + imagesUrls["tl"] + ") no-repeat top left";
            containers.push(tl);
        }
        if (imagesUrls["tr"]) {
            var tr = document.createElement("div");
            tr.style.background = "url(" + imagesUrls["tr"] + ") no-repeat top right";
            containers.push(tr);
        }
        if (imagesUrls["bl"]) {
            var bl = document.createElement("div");
            bl.style.background = "url(" + imagesUrls["bl"] + ") no-repeat bottom left";
            containers.push(bl);
        }
        if (imagesUrls["br"]) {
            var br = document.createElement("div");
            br.style.background = "url(" + imagesUrls["br"] + ") no-repeat bottom right";
            containers.push(br);
        }
        if (containers.length > 0) {
            // create content container
            var m = document.createElement("div");
            m.className = "content";
            // move child elements of target element into content container
            this._moveChildren(el, m);
            // set middle image as background of target element
            if (imagesUrls["m"]) {
                el.style.background = "url(" + imagesUrls["m"] + ") repeat top left";
            }
            containers.push(m);
            // inject containers into DOM
            el.appendChild(containers[0]);
            for (var i = 1; i < containers.length; i++) {
                containers[i - 1].appendChild(containers[i]);
            }
        }
    },
    dispose: function() {
        //Add custom dispose actions here
        UPDN.ImageCornersBehavior.callBaseMethod(this, "dispose");
    },
    _moveChildren: function(srcEl, destEl) {
        while (srcEl.hasChildNodes()) {
            var child = srcEl.childNodes[0];
            destEl.appendChild(child);
        }
    },
    get_imageUrls: function() {
        return this._imageUrls;
    },
    set_imageUrls: function(value) {
        this._imageUrls = value;
    }
}
UPDN.ImageCornersBehavior.registerClass("UPDN.ImageCornersBehavior", Sys.UI.Behavior);

To use the extender, place an <asp:Panel> control on the page:

<asp:Panel ID="Panel1" runat="server" CssClass="box1">
    This box is styled using 8 images. Lorem ipsum no etiam perfecto his, per adhuc maiorum epicurei eu. Laoreet signiferumque in mel, ne vel dicat percipit instructior. An eum veniam decore perpetua, nam laudem praesent at. Exerci accumsan contentiones est ei, appetere gloriatur et qui, ea suscipit senserit consectetuer mei.
</asp:Panel>

Then add the extender, set the TargetControlID to the ID of the <asp:Panel> control, and specify the images required to achieve your design. For this panel, I require eight images, four for the borders and four for the corners:

b bl br l r t tl tr
<updn:ImageCornersExtender ID="ImageCornersExtender1" runat="server"
    TargetControlID="Panel1"
    TopBorderImageUrl="img/box1/t.gif"
    RightBorderImageUrl="img/box1/r.gif"
    BottomBorderImageUrl="img/box1/b.gif"
    LeftBorderImageUrl="img/box1/l.gif"
    TopLeftCornerImageUrl="img/box1/tl.gif"
    TopRightCornerImageUrl="img/box1/tr.gif"
    BottomLeftCornerImageUrl="img/box1/bl.gif"
    BottomRightCornerImageUrl="img/box1/br.gif"
/>

Here is how the complete example looks like:

Image borders examples

Download the source code and example from my SkyDrive.

Written by tzkuei

November 25, 2008 at 11:04 am

Latest ASP.NET preview available to download

leave a comment »

The latest release of ASP.NET preview is available on CodePlex!

This release include:

  • ASP.NET AJAX 4.0 Preview 3
  • ASP.NET Dynamic Data 4.0 Preview 1
  • ASP.NET MVC Beta Source Code Release

This release showcases features that may be included in ASP.NET 4.0!

Written by tzkuei

October 28, 2008 at 4:39 pm

Posted in ASP.NET

Tagged with , , ,