A day with .Net

My day to day experince in .net

Archive for March, 2012

Load data dynamically on page scroll using jquery,ajax and asp.net.

Posted by vivekcek on March 11, 2012

Introduction

In Facebook you might saw status updates of your friends are dynamically loaded when you scroll the browser’s scroll bar. So in this article i am going to explain how we can achieve this using jQuery and Ajax.

Using the code

The solution includes 2 web forms(Default.aspx and AjaxProcess.aspx). The Default.aspx contain a Div with ID “myDiv“. Initially the Div contain some static data, then data is dynamically appended to the Div using jquery and ajax.

<div id="myDiv">
	<p>Static data initially rendered.</p>
</div>

The second Web Form AjaxProcess.aspx contains a web method GetData(), that is called using ajax to retrieve data.

[WebMethod]
    public static string GetData()
    {
        string resp = string.Empty;
        resp += "<p>This content is dynamically appended to the existing content on scrolling.</p>";
        return resp;
   }

Now we can add some jquery script in Default.aspx, that will be fired on page scroll and invoke the GetData()method.

 $(document).ready(function () {

            $(window).scroll(function () {
                if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                    sendData();
                }
            });

            function sendData() {
                $.ajax(
                 {
                     type: "POST",
                     url: "AjaxProcess.aspx/GetData",
                     data: "{}",
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     async: "true",
                     cache: "false",

                     success: function (msg) {
                         $("#myDiv").append(msg.d);
                     },

                     Error: function (x, e) {
                         alert("Some error");
                     }

                 });

            }

        });

Here, to check whether the scroll has moved at the bottom, the following condition is used.

 $(window).scroll(function () {
                if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                    sendData();
                }
            });

This condition will identify whether the scroll has moved at the bottom or not. If it has moved at the bottom, dynamic data will get loaded from the server and get appended to myDiv.

success: function (msg) {
                         $("#myDiv").append(msg.d);
                     },

Download Code

https://skydrive.live.com/redir.aspx?cid=12c9d813342f227a&resid=12C9D813342F227A!126&parid=12C9D813342F227A!120&authkey=!AJIbc1495KJup70

Posted in Jquery | Tagged: , , | 3 Comments »

Are you sure you want to navigate away from this page?

Posted by vivekcek on March 10, 2012

Do you want a message to show when the user try to close tab or leave your page like facebook.Just include this script in your page.

<script type="text/javascript">
window.onbeforeunload = function (event) {
var message = 'All changes will get lost!';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
}
</script>

Posted in Uncategorized | Tagged: , , | Leave a Comment »

Disable button on ajax post back.

Posted by vivekcek on March 8, 2012

Some times ajax post back can take time.Its a good practice not to allow user to click the button again before the post back is completed.This can be achieved by adding some code in HTML.

In this example my page contain a Script Manger,an update panel and a button inside it .In the buttons click event i simulated a long running process by calling a thread sleep.


protected void Button1_Click(object sender, EventArgs e)
 {
 System.Threading.Thread.Sleep(5000);
 }

Then added a script in HTML.That is fired when an ajax request is made.


<script type="text/javascript">
var page;
function pageLoad() {
page = Sys.WebForms.PageRequestManager.getInstance();
page.add_beginRequest(OnBeginRequest);
page.add_endRequest(OnEndRequest);
}
function OnBeginRequest(sender, args) {
$get(args._postBackElement.id).disabled = true;
}
function OnEndRequest(sender, args) {
$get(sender._postBackSettings.sourceElement.id).diabled = false;
}
</script>

OnBeginReques function find the control that caused the post back(button in our case) and disable that.OnEndRequest is fired after the post back is over and button is re enabled

Download code

https://skydrive.live.com/redir.aspx?cid=12c9d813342f227a&resid=12C9D813342F227A!125&parid=12C9D813342F227A!120&authkey=!ABW5jJ6aLndfff8

Posted in Uncategorized | Leave a Comment »

Asynchronous Logging ASP.NET

Posted by vivekcek on March 8, 2012

Hi Friends if you want to track who is using your website you can try out an asynchronous request logging using Task Parallel library.The library code is given below.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Text.RegularExpressions;

namespace TSecure
{

public class Logger
{

private static bool _denyBots = false;

private static void DenyAccess(HttpApplication app)
{
app.Response.StatusCode = 0x191;
app.Response.StatusDescription = "Access Denied";
app.Response.Write("401 Access Denied");
app.CompleteRequest();
}

private static bool IsCrawler(HttpRequest request)
{
bool isCrawler = request.Browser.Crawler;
if (!isCrawler)
{
Regex regEx = new Regex("Slurp|slurp|ask|Ask|Teoma|teoma");
isCrawler = regEx.Match(request.UserAgent).Success;
}
return isCrawler;
}

private static void _LogRequest(HttpApplication app)
{
HttpRequest request = app.Context.Request;

bool isCrawler = IsCrawler(request);
string userAgent = request.UserAgent;
string requestPath = request.Url.AbsolutePath;
string referer = (request.UrlReferrer != null) ? request.UrlReferrer.AbsolutePath : "";
string userIp = request.UserHostAddress;
string isCrawlerStr = isCrawler.ToString();
/*  @RemoteIp varchar(50),
@UserAgent varchar(2000) ,
@RequestPath varchar(2000),
@Referer varchar(2000),
@IsCrawler varchar(5) */
//Database code

if (isCrawler && _denyBots)
{
DenyAccess(app);
}

}

public static void LogRequest(HttpApplication app)
{
Task.Factory.StartNew(() => _LogRequest(app));
}

}
}

Now in the Global.asax file of your application,call library via the below code in Prerequisite event

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
TSecure.Logger.LogRequest(sender as HttpApplication);
}

Posted in Uncategorized | Tagged: , , | Leave a Comment »