Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

Sunday, April 1, 2012

Implementing a Client Session Timeout for intensive data access

Often there is a scenario where the user displays a live page that polls the data from server every few seconds to update some contents on page. In case, the user leaves for hours without shutting down the browser. As a result, the page keeps on sending requests, generating a significant—and useless—workload for the server.
On the server, there's session timeout, but in AJAX there's also the client session that matters. To detect the end of a client session, you need to check whether there was user activity such as clicking and tapping for a given amount of time.To detect the end of a session based on a timer, set up a client timer that expires after a specified number of seconds, stops the ongoing task, and pops up an alert box. If the user responds to the prompt, processing resumes as usual. This example update the datetime every 3 seconds and then show confirm dialog box every 10 seconds to ask the user.

Client Session Timeout

Tuesday, January 3, 2012

How to show Modal Dialog Box with Asp.Net Ajax

With Microsoft® ASP.NET AJAX, dialog boxes are especially important for displaying context-sensitive information without a page reload or new page. It is therefore important to devise a different implementation of dialog boxes that are as effective as modal popups but hassle-free for users.
The ModalPopup extender takes the markup generated by a server-side ASP.NET panel and shows or hides it as the user clicks on an associated HTML element. Initially styled as hidden, the dialog box is downloaded onto the client when the page is loaded and then shown or hidden on demand.
The following example show Modal Dialog popup to edit the customer information as below :

Modal Dialog with Asp.net Ajax
First of all, you need to add AjaxControlToolKit.dll to References like look:









Here is Stylesheet and Javascript to add <head> tag.
<style type="text/css">
    .modalPopup
    {
        background-color: #ffffdd;
        border-width: 3px;
        border-style: solid;
        border-color: Gray;
        padding: 3px;
        width: 350px;
    }
    .modalBackground
    {
        background-color: Gray;
        filter: alpha(opacity=70);
        opacity: 0.7;
    }
</style>
<script type="text/javascript">
    function ok(sender, e) {
        $find('ModalPopupExtender1').hide();
        __doPostBack('editBox_OK', e);
    }
    function cancel(sender, e) {
        $find('ModalPopupExtender1').hide();
    }
    function pageLoad(sender, args) {
        //Note that the OnKeyPress event handler will not work unless you register it with the Microsoft AJAX Library. The best place to run this registration code is the pageLoad function, like so:
        
        $addHandler(document, "keydown", onKeyDown);
        $find("ModalPopupExtender1").add_showing(onModalShowing);
    }
    function onModalShowing(sender, args) {
        $get("pnlEditCustomer").style.backgroundColor = "yellow";
    }
    function onKeyDown(args) {
        //Closing the Popup Using the Esc Key
        if (args.keyCode == Sys.UI.Key.esc) {
            $find('ModalPopupExtender1').hide();
        }
    } 
</script>
Here is server controls in .aspx page.
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"/>
    <div>
        <!--Using Partial Rendering to Update the Customer View -->
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <table>
                    <tr>
                        <td><b>Customer ID:</b></td>
                        <td><asp:Label runat="server" ID="lblCustomerID" Text="C00001"/></td>
                    </tr>
                    <tr>
                        <td><b>Company Name:</b></td>
                        <td><asp:Label runat="server" ID="lblCompanyName" Text="Eastern Connection"/></td>
                    </tr>
                    <tr>
                        <td><b>Contact Name:</b></td>
                        <td><asp:Label runat="server" ID="lblContactName" Text="Ann Devon"/></td>
                    </tr>
                    <tr>
                        <td><b>Country:</b></td>   
                        <td><asp:Label runat="server" ID="lblCountry" Text="Germany"/></td>
                    </tr>
                     <tr>
                        <td>
                            <asp:Button runat="server" ID="btnEditText" Text="Edit text" OnClick="btnEditText_Click" />
                        </td>
                        <td>
                        </td>
                    </tr>
                </table>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="editBox_OK"/>
            </Triggers>
        </asp:UpdatePanel>
    </div>
    <div>
        <asp:Button runat="server" ID="hiddenTargetControlForModalPopup" Style="display: none" />
        <asp:UpdatePanel runat="server" ID="DialogBoxUpdatePanel" UpdateMode="Conditional">
            <ContentTemplate>
                
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    <div>
         <!-- Dialog box:: Edit customer info -->
         <!--The Content of a Modal Popup Supports Partial Rendering -->
        <asp:Panel ID="pnlEditCustomer" runat="server" CssClass="modalPopup" style="display:block;">
            <div style="margin:10px">
            <asp:UpdatePanel runat="server" ID="ModalPanel1" RenderMode="Inline" UpdateMode="Conditional"> 
                <ContentTemplate>
                <table>            
                    <tr>
                        <td><b>Customer ID:</b></td>
                        <td><asp:Label runat="server" id="editCustomerID" />
                        </td>
                    </tr>            
                    <tr>
                        <td><b>Company Name:</b></td>
                        <td><asp:TextBox runat="server" id="editTxtCompanyName" /></td>
                    </tr>
                    <tr>
                        <td><b>Contact Name:</b></td>
                        <td><asp:TextBox runat="server" id="editTxtContactName" /></td>
                    </tr>
                    <tr>
                        <td><b>Country:</b></td>
                        <td><asp:TextBox runat="server" id="editTxtCountry" /></td>
                    </tr>
                </table>   
                <hr />
                <asp:Button ID="btnApply" runat="server" Text="Apply" width="50px" OnClick="btnApply_Click"/>
                </ContentTemplate>
                </asp:UpdatePanel>              
                <asp:Button ID="editBox_OK" runat="server" Text="OK" width="50px" 
                    onclick="editBox_OK_Click"/>
                <asp:Button ID="editBox_Cancel" runat="server" Text="Cancel" width="50px" />
            </div>
        </asp:Panel>
    </div>
    <div>
        <asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server"  
            TargetControlID="hiddenTargetControlForModalPopup"
            PopupControlID="pnlEditCustomer"
            BackgroundCssClass="modalBackground"
            DropShadow="false"
            OkControlID="editBox_OK"
            OnOkScript="ok()"
            OnCancelScript="cancel()"
            CancelControlID="editBox_Cancel" /> 
    </div>
</form>
Add the following to code-behind.
protected void btnEditText_Click(object sender, EventArgs e)
{
    // Initialize the controls in the panel used as the UI of the dialog box
    InitDialog();

    // The panel markup has been served already to the page. To edit it, 
    // you need to a) wrap the panel's content in an UpdatePanel region and 
    // b) update the panel once you made any changes
    ModalPanel1.Update();

    // Order to inject the script to show the dialog as the page loads up 
    // in the browser.
    ModalPopupExtender1.Show();
}
protected void InitDialog()
{
    editCustomerID.Text = lblCustomerID.Text;
    editTxtCompanyName.Text = lblCompanyName.Text;
    editTxtContactName.Text = lblContactName.Text;
    editTxtCountry.Text = lblCountry.Text;
    SetFocus("editTxtCompanyName");
}
protected void btnApply_Click(object sender, EventArgs e)
{
    // Edit the server controls in the modal panel. Because the 
    // call occurs over a partial rendering call, any updates
    // will be automatically reflected by the client UI.
    if (editTxtCountry.Text == "Germany")
        editTxtCountry.Text = "Cuba";
    else
        editTxtCountry.Text = "USA";
}
protected void editBox_OK_Click(object sender, EventArgs e)
{
    // Save to the database
    // Refresh the UI
    lblCompanyName.Text = editTxtCompanyName.Text;
    lblContactName.Text = editTxtContactName.Text;
    lblCountry.Text = editTxtCountry.Text;
} 
That's it. Develope on the trend!

Reference : http://msdn.microsoft.com/en-us/magazine/cc164247.aspx

ModalPopup Demonstration : 
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ModalPopup/ModalPopup.aspx

Note : Don't forget to add EnableEventValidation="false" to the 'page' directive.

Thursday, December 22, 2011

$(document).ready() vs pageLoad() vs Application.Init

jQuery’s $(document).ready()

    * Ideal for onetime initialization.
    * Optimization black magic; may run slightly earlier than pageLoad().
    * Does not re-attach functionality to elements affected by partial postbacks.

ASP.NET AJAX’s pageLoad()

    * Unsuitable for onetime initialization if used with UpdatePanels.
    * Slightly less optimized in some browsers, but consistent.
    * Perfect for re-attaching functionality to elements within UpdatePanels.

ASP.NET AJAX’s Application.Init

    * Useful for onetime initialization if only ASP.NET AJAX is available.
    * More work required to wire the event up.
    * Exposes you to the “sys is undefined” error if you aren’t careful. For this error, see this post
       http://www.aspmemo.net/2011/12/how-to-solve-sys-is-undefined-error.html


Original Post : http://encosia.com/document-ready-and-pageload-are-not-the-same/

What is AJAX?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.
AJAX is not a new programming language, but a new way to use existing standards.

AJAX is the art of exchanging data with a server.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes and update parts of a web page, without reloading the whole page.

Note : Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

Useful Link : http://www.w3schools.com/ajax/ajax_intro.asp

Tuesday, December 20, 2011

JQuery : Using events to take effect when the user interacts with the browser

For every onxxx event available, like onclick, onchange, onsubmit, there is a jQuery equivalent. Some other events, like ready and hover, are provided as convenient methods for certain tasks.

Here is CSS and script to put <head> tag.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<style type="text/css">
     .highlight { border: 5px dotted #eee;}
</style>
<script type="text/javascript">
    $(document).ready(function () {
        //go here the following example scripts
    });
</script>

Add the following to <body> tags.
<a name="top" href="#bottom">Go to bottom</a>
<form id="form">
    Form 1
    <input type="text" value="XXX"/>
</form>
<form>
    Form 2
    <input type="text" value="YYY"/>
</form>
<a id="reset" href="#">Reset!</a>
<br />
<a id="clickme" href="http://www.aspmemo.net">Click Me!</a>
<p>This is probably the most common mishap. The remedy is simple--yank! It's most easily done
with two people. One to restrain the bird and the <a href="#"> This is a link. Hover me to
highlight the parent paragraph.</a> other to pull the feather. Use pliers, or a hemostat. Tweezers won't
work on primaries.</p>
<p>This is probably the most common mishap. The remedy is simple--yank! It's most easily done
with two people. One to restrain the bird and the <a href="#"> This is a link. Hover me to
highlight the parent paragraph.</a> other to pull the feather. Use pliers, or a hemostat. Tweezers won't
work on primaries.</p>
<a name="bottom" href="#top">Go to top</a>

One task you often face is to call methods on DOM elements that are not covered by jQuery. Think of a form you would like to reset after you submitted it successfully via AJAX.

$(document).ready(function() {
   // use this to reset a single form
   $("#reset").click(function() {
     $("form")[0].reset();
   });
 });
This code selects the first form element and calls reset() on it. In case you had more than one form, you could also do this:

 $(document).ready(function() {
   // use this to reset several forms at once
   $("#reset").click(function() {
     $("form").each(function() {
       this.reset();
     });
   });
 });
This would select all forms within your document, iterate over them and call reset() for each. Note that in an .each() function, this refers to the actual element. Also note that, since the reset() function belongs to the form element and not to the jQuery object, we cannot simply call $("form").reset() to reset all the forms on the page.
The [expression] syntax is taken from XPath and can be used to filter by attributes. Maybe you want to select all anchors that have a name attribute:

$(document).ready(function() {
   $("a[name]").css("background", "#eee" );
 });
This adds a background color to all anchor elements with a name attribute.

More often than selecting anchors by name, you might need to select anchors by their "href" attribute. This can be a problem as browsers behave quite inconsistently when returning what they think the "href" value is. To match only a part of the value, we can use the contains select "*=" instead of an equals ("="):

 $(document).ready(function() {
   $("a[href*='aspmemo']").click(function() {
        alert('Bye JQuery!');
   });
 });
For all hovered anchor elements, the parent paragraph is searched and a class "highlight" added and removed. In addition, you can also select parent elements (also known as ancestors for those more familiar with XPath). Maybe you want to highlight the paragraph that is the parent of the link the user hovers. Try this:

 $(document).ready(function(){
   $("a").hover(function(){
     $(this).parents("p").addClass("highlight");
   },function(){
     $(this).parents("p").removeClass("highlight");
   });
 });
For all hovered anchor elements, the parent paragraph is searched and a class "highlight" added and removed.

Lets shop here. See you.

Useful link : http://www.w3schools.com/jquery/jquery_ref_events.asp

Sunday, December 18, 2011

How to solve "sys is undefined" error while using asp.net ajax update panel.

We have the error "sys is undefined" often when we use asp.net ajax update panel in our ajax enable web site.
The best remedy for this problem is to add the script to the ScriptManager’s Scripts collection and then call our wireups in a Sys.Application.init event handler. It is pretty good practice to separate .js file from source as much as we can.

In .aspx file,
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"
    EnablePartialRendering="true" EnablePageMethods="true">
        <Scripts>
            <asp:ScriptReference Path="Init.js" />
        </Scripts>
    </asp:ScriptManager>
    <br />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
           <%-- your code go here --%>
        </ContentTemplate>
    </asp:UpdatePanel>
</form>

In Init.js file,

//Attach delegate functions to the init event to complete tasks that must
//be performed before objects are created. The add_init accessor binds a
//delegate function to the init event.
Sys.Application.add_init(AppInit);
function AppInit(sender) {  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(End);
}

//The endRequest event is raised after an asynchronous postback is finished
//and control has been returned to the browser. You can use this event to
//provide a notification to users or to log errors.
function End(sender, args) { }

Monday, December 5, 2011

$get and $find ASP.NET AJAX Shortcut Functions

Sys.UI.DomElement $get Method

Provides a shortcut to the getElementById method of the Sys.UI.DomElement class. This member is static and can be invoked without creating an instance of the class. The $get shortcut function points to the Sys.UI.DomElement.getElementById JavaScript function which is defined as part of the ASP.NET AJAX client side library (which means you will need to include a ScriptManager on the page to be able to use it).

<script type="text/javascript">
function changeColor(color)
{
// fetch the div
var div = $get('<%= label1.ClientID %>');
// set the color to the provided value
div.style.color = color;
}
</script>


Sys.Application $find Method

Provides a shortcut to the findComponent method of the Sys.Application class. This member is static and can be invoked without creating an instance of the class. Use $find to Fetch an AjaxControlToolkit Extender Behavior as well.

<script type="text/javascript">
function checkComponent()
{
if (!($find('MyComponent', div1))) {
div1.innerHTML = 'MyComponent is not available.';
}
</script>

That's it. Well done!