Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for the ‘JQuery’ Category

Lazy Loading

Posted by Ramani Sandeep on December 11, 2009

Introduction

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program’s operation if properly and appropriately used. The opposite of lazy loading is Eager Loading.

Article – 1: jQuery Tabs and Lazy Loading by Malcolm Sheridan

In this article I will connect to the Northwind database using LINQ to SQL, and display customer and product information in separate tabs. I’ll also show you one way of lazy loading these tabs so the data is retrieved only once, not each time a tab is selected.

Read more

Article – 2: Lazy Loading jQuery Tabs with ASP.NET by Mikesdotnetting

This article looks at efficient use of jQuery tabs when displaying data. Specifically, it covers how to lazy-load data, so that it is only accessed and displayed if the tab is clicked.

Lazy Loading is a well-known design pattern that is intended to prevent redundant processing within your application. In the case of tabbed data, there seems little point retrieving and binding data that appears in a tabbed area that no one looks at. So, this examples covers how to defer data access and display until the user wants it – which is defined by them clicking the relevant tab.

Read more

Article – 3: Eager Loading and Lazy Loading in ADO.NET Data Services by Gil Fink

The default behavior of a data service’s .NET client is not to load the entities’ associated objects. When we request an entity we will get it from the service but its associated objects will not load up at all.

Lets say that I have two entities in my program

  • a course
  • a department

The associations between the entities are that a department can have a lot of courses and a course belongs to one department.

When I load a department it’s list of courses will be empty. trying to iterate the list of courses will give nothing because the courses will not load until we tell them to be loaded explicitly.

This is done by the LoadProperty method of the data service context.

Read more

 

I have a great learning experience thru this.

Now its your turn to have it.

Posted in ASP.NET, ASP.NET 3.5, ASP.NET Ajax, C# 3.0, JQuery, Linq | Tagged: , , , , , , , | Leave a Comment »

Hide/Change Sort expression link in gridview

Posted by Ramani Sandeep on November 27, 2009

Today I was reading www.asp.net forums for some Q/A  & I found one interesting Query regarding Gridview sorting. So I feel that let me share it with others also.

Query Posted by Kamran Shahid

I am using built in sorting in gridview. The links on the headers column shows like

javascript:__doPostBack(‘GridView1′,’Sort$au_fname’)

Is tehre any way I can change the display of that link like for example it may show # or au_fname only.

Solutions by Imran Baloch

With JQuery

<script language="javascript">
$(function(){
    $("a[href]").each(function(n){
        if(this.href.indexOf("GridView1")>-1)
        {
            var a=this.href;
            this.href="#";
            $(this).click(function(event){
                this.href=a;
            });
        }
    });
});
</script>

Without JQuery

<script language="javascript">
 var tags = document.getElementsByTagName('a');
 for (var i=0; i < tags.length; i++)
 {
      if(tags[i].href.indexOf("GridView1")>-1)
      {
            tags[i].custom1=tags[i].href;
            tags[i].href="#";
            tags[i].onclick=function(event){
                alert(this.custom1);
                thisthis.href=this.custom1;
            }
      }
 }
</script>  

Hope this will help !!!

Happy Programming

Posted in ASP.NET, ASP.NET 3.5, JQuery, JavaScript | Tagged: , , , | Leave a Comment »

Moving Values Between Select Boxes

Posted by Ramani Sandeep on November 2, 2009

These functions allowed you to do commonly-requested actions with select boxes.

For example, you can easily pass values between two select boxes. This makes a nice Windows-style interface for choosing components, adding and removing items from a list, etc. Options are re-ordered as they are added and removed from the lists.

Several other functions are included in the source that are not in the examples. This includes copying items in lists instead of moving them, copying/moving all items, and automatically selecting all items in a list.

read more

Other related articles 

Posted in JQuery, JavaScript | Tagged: , , | Leave a Comment »

Multiple File Upload using JQuery

Posted by Ramani Sandeep on October 28, 2009

Introduction

In this article I have explained how to upload multiple files using file upload control. I have used jQuery plugin for uploading multiple files.

I have also explained how to check for file type, file maximum size limit using jQuery & also using server side validation code.

Download the Following Files

Namespace used

using System.Security.Cryptography;
using System.Text;
using System.IO;

Step 1: Include the jQuery Files needed on the page.

Assuming you have downloaded these files, create a reference to these files in the <head> section of your page as shown below:

  <head id="Head1" runat="server">
        <title>Multiple File Upload using JQuery</title>
        <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
        <script src="Scripts/jquery.MultiFile.js" type="text/javascript">
        </script>
    </head>

Step 2: Add File Upload Control & Button on the Page.

 <asp:FileUpload ID="FileUpload1" runat="server" class="multi" accept="gif|jpeg|bmp|png|jpg"
        maxlength="5" />
    <br />
    <asp:Button ID="btnUpload" runat="server" Text="Upload All" OnClick="btnUpload_Click" />
    <br />
    <asp:Label ID="lblMsg" runat="server" Text="">\
    </asp:Label>
class=”multi” is used to specify that user can select multiple files.
maxlength property specify that user can upload maximum 5 files not more than that.
accept property used to restrict user to upload only certain type of file only.

Step 3: Double click on Upload Button & Write the code that is used to upload files.

 protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (ServerSideValidation() == true)
        {
            string SavePath, Msg = null;

            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    SavePath = ConfigurationManager.AppSettings["PatientPhotoImages"].ToString()
                        + GetUniqueKey() + GetFileExtension(hpf.FileName);
                    hpf.SaveAs(Server.MapPath(SavePath));
                    //SavePath can be saved in DB.
                    Msg += GetFileName(hpf.FileName.ToString()) + " , ";
                }
            }
            lblMsg.Text = Msg + " Uploaded Successfully.";
        }
    }

Step 4: Write the private function which helps to Upload files.

This function helps to extract file extension from the fileName.

 private string GetFileExtension(string FileName)
    {
        char saperator = '.';
        string[] temp = FileName.Split(saperator);

        return "." + temp[1].ToString();
    }

OR

private string GetFileExtension(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.Extension;
    }

This function helps to get Unique Key, which is used to save files on server with different name that does not collied with each other.

 private string GetUniqueKey()
    {
        int maxSize = 8;
        char[] chars = new char[62];
        string a;

        a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

        chars = a.ToCharArray();

        int size = maxSize;
        byte[] data = new byte[1];

        RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

        crypto.GetNonZeroBytes(data);
        size = maxSize;
        data = new byte[size];
        crypto.GetNonZeroBytes(data);
        StringBuilder result = new StringBuilder(size);

        foreach (byte b in data)
        {
            result.Append(chars[b % (chars.Length - 1)]);
        }

        return result.ToString();
    }

This function help to get Filename from the filepath.

 private string GetFileName(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.Name;
    }

Step 5: Add Server Side Validation Code

This is the function which is used to validate files that user wants to upload. If the client side validation does not work, this code will help us to identify the invalid files.

Validation rules like whether file type is correct or not, file size is valid or not.

If you do not want to validate the files on server side, you can ignore this code. But I prefer to use it.

 private bool ServerSideValidation()
    {
        string errorMsg = string.Empty, temp = null;
        bool errorFlag = true;

        // Get the HttpFileCollection
        HttpFileCollection hfc = Request.Files;
        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                temp = ValidateImage(hpf);
                if (temp != null)
                {
                    errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp;
                    temp = null;
                }
            }
        }

        if (errorMsg != "")
        {
            lblMsg.Text = errorMsg;
            errorFlag = false;
        }
        return errorFlag;
    }

This function used to check file type & file size. If file is invalid than it will return error message.

 private string ValidateImage(HttpPostedFile myFile)
    {
        string msg = null;
        int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileUploadSizeLimit"].ToString());
        //Check Length of File is Valid or Not.
        if (myFile.ContentLength > FileMaxSize)
        {
            msg = msg + "File Size is Too Large.";
        }
        //Check File Type is Valid or Not.
        if (!IsValidFile(myFile.FileName))
        {
            msg = msg + "Invalid File Type.";
        }
        return msg;
    }

This function is used to check whether the file that user want to upload is valid file type or not.

private bool IsValidFile(string filePath)
    {
        bool isValid = false;

        string[] fileExtensions = { ".bmp", ".jpg", ".png", ".gif", ".jpeg", ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };

        for (int i = 0; i < fileExtensions.Length; i++)
        {
            if (filePath.Contains(fileExtensions[i]))
            {
                isValid = true; break;
            }
        }
        return isValid;
    }

Conclusion:

This code is complete solution that helps to upload multiple file using File Upload with jQuery plugin. I was always in a need of such code in my route work so I decided to write the code that helps others also.

Hope this will help !!!
Jay Ganesh

Posted in ASP.NET, JQuery | Tagged: , , , , | 2 Comments »

Ebook : 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls

Posted by Ramani Sandeep on October 14, 2009

hi readers ,

here is a very useful book that explore the jQuery usage with ASP.NET Controls. This is very handy book for the web developer who uses jQuery along with ASP.NET.

It helps to enhance your web experience & better understand how/where/when to use jQuery with ASP.NET Controls.

read more : here

read the content : here

Posted in ASP.NET, ASP.NET 3.5, JQuery | Tagged: , , , | Leave a Comment »

Page Peel with Jquery

Posted by Ramani Sandeep on September 24, 2009

Article 1 : Simple Page Peel Effect with jQuery & CSS

You have probably seen these forms of advertisings where you can peel a corner of a website and see a message underneath. It seems most are flash driven, but I decided to try it out using some simple lines of jQuery.

1. HTML – Page Peel Wireframe

The “pageflip” div will act as the container, mainly used to establish the relative positioning. Then nest the image and the span class of “msg_block” wrapped in an <a> tag. Note – If you don’t have any conflicting absolute/relative positioning properties, you technically don’t need the “pageflip” container at all.

Read more…

Article 2 : Page Peel with Jquery Plugin

A jquery plugin to implement a page peel effect to place ads on your site.

If you haven’t seen it by now, check out the demo.

Now, the one contained inside of the box has its limitations. You have to have enough room to display the full page out (this one’s set up as 500×500). Also, I’ve set the bottom padding of this box to 105px so I don’t cover any content. You could also indent the content 105px or just cover your content. Whatever floats your boat.

Read more…

Hope this will help you!!!

Posted in Css, JQuery | Tagged: , , , | Leave a Comment »

Processing.js

Posted by Ramani Sandeep on September 8, 2009

Today when i am reading Linq articles on Scott Hanselman blog, i found one very useful information. so i feel that let me write about it so reader of my blog also get benefit from that.

I was reading Article Titled : LINQ to Regular Expressions and Processing in Javascript

In this article I read about ‘Processing’ in Javascript that is open-source Java-based visualization language. And i feel this is really great stuff !!! so I am sharing some information regarding it that i have read from http://processingjs.org.

Processing.js is an open programming language for people who want to program images, animation, and interactions for the web without using Flash or Java applets.

Processing.js uses Javascript to draw shapes and manipulate images on the HTML5 Canvas element. The code is light-weight, simple to learn and makes an ideal tool for visualizing data, creating user-interfaces and developing web-based games.

Processing.js runs in FireFox, Safari, Opera, Chrome and will also work with Internet Explorer, using Explorer Canvas.

The Processing language was created by Ben Fry and Casey Reas. It evolved from ideas explored in the Aesthetics and Computation Group at the MIT Media Lab and was originally intended to be used in a Java run-time environment.

In the Summer of 2008, John Resig ported the 2D context of Processing to Javascript for use in web pages. Much like the native language, Processing.js is a community-driven project, and continues to grow as browser technology advances.

Click here for more info…

Posted in JQuery, JavaScript | Tagged: , , , | Leave a Comment »

Using jQuery to directly call ASP.NET AJAX page methods

Posted by Ramani Sandeep on September 3, 2009

Here I am looking to explain how to call page methods using jQuery.

Step 1: Define your Page Methods in code behind:

[WebMethod]
    public static int MyMethod1()
    {
        return 13;
    }
    [WebMethod()]
    public static string MyMethod2(string a, int b)
    {
        return a + " –> " + b.ToString();
    }

Step 2: Include the jQuery Library on Default.aspx page:

<script src="Js/jquery.min.js" type="text/javascript"></script>

If you do not have jQuery file in Js folder then use following:

<script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">

Step 3: Now Write the code to Call Page method:

<script type="text/javascript">
        function PageMethod(fn, paramArray, successFn, errorFn)
        {
            var pagePath = window.location.pathname;
            //Create list of parameters in the form : {"paramName1":"paramValue1","paramName2":"paramValue2"}
            var paramList = ”;
            if (paramArray.length > 0)
            {
                for (var i=0; i<paramArray.length; i+=2)
                {
                    if (paramList.length > 0)
                        paramList += ‘,’;
                    paramList += ‘"’ + paramArray[i] + ‘":"’ + paramArray[i+1] + ‘"’;
                }
            }
            paramList = ‘{‘ + paramList + ‘}’;
            //Call the page method
            $.ajax({
                type: "POST",
                url: pagePath + "/" + fn,
                contentType: "application/json; charset=utf-8",
                data: paramList,
                dataType: "json",
                success: successFn,
                error: errorFn
            });
        }
        function AjaxSucceeded (result)
        {
            alert(result.d);
            $("#Result").text("Result : " + result.d);
        }
        function AjaxFailed (result)
        {
            alert("Error on Page");
        }
        function CallPageMethod1()
        {
            PageMethod("MyMethod1", [], AjaxSucceeded, AjaxFailed);
            return false;
        }
         function CallPageMethod2()
        {
            PageMethod("MyMethod2",["a", "value", "b", 2], AjaxSucceeded, AjaxFailed);
            return false;
        }
    </script>

Step 4: To Test your code use following html on default.aspx:

<form id="form1" runat="server">
        <h1>
            Using jQuery To Call ASP.NET Page Methods and Web Services</h1>
        <div>
<asp:Button ID="Button1" runat="server" Text="With No Parameter" OnClientClick="return CallPageMethod1();" />
   <asp:Button ID="Button2" runat="server" Text="With Parameter" OnClientClick="return CallPageMethod2();" />
        </div>
        <div id="Result">
        </div>
    </form>

jQuery makes an AJAX call to the MyMethod1 & MyMethod2 page method and replaces the div’s text with its result.

Very Simple!!!

Hope You will also get benefit from this.

Jai Ganesh

Related Post:

http://ramanisandeep.wordpress.com/2009/09/22/calling-web-service-methods-using-asp-net-ajax/

Posted in ASP.NET Ajax, JQuery, Web Services | Tagged: , , , , , , | 1 Comment »

jQuery Tutorials ( Learn – Practice – Expert )

Posted by Ramani Sandeep on August 31, 2009

Article 1: Using jQuery With ASP.NET

This article has everything that is needed by programmer who want to start learning jQuery.

It includes the following topics:

  • Using jQuery in ASP.NET Page
  • jQuery Selectors
  • jQuery Chainability
  • jQuery Object Accessors
  • jQuery Events
  • Ajax using jQuery and ASP.NET
  • jQuery Ajax with JSON data
  • Effects with jQuery

Read Full Article: click here…

Article 2: Using jQuery to consume ASP.NET web services

First, It’ll cover the two requirements necessary when calling an ASMX web service that’s being JSON serialized by the ASP.NET AJAX extensions.
Then, It’ll show you how to do this with jQuery.
Finally, I’ll update the deferred content loading example accordingly.

Read Full Article: click here



Article 3: ON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks

Recently some reports have been issued by security researchers describing ways hackers can use the JSON wire format used by most popular AJAX frameworks to try and exploit cross domain scripts within browsers.  Specifically, these attacks use HTTP GET requests invoked via an HTML <script src=""> include element to circumvent the "same origin policy" enforced by browsers (which limits JavaScript objects like XmlHttpRequest to only calling URLs on the same domain that the page was loaded from), and then look for ways to exploit the JSON payload content.

Read Full article: click here

Posted in ASP.NET Ajax, JQuery | Tagged: , , , , , , | Leave a Comment »

JSON.Net

Posted by Ramani Sandeep on August 31, 2009

The Json.NET library makes working with JavaScript and JSON formatted data in .NET simple. Quickly read and write JSON using the JsonReader and JsonWriter or serialize your .NET objects with a single method call using the JsonSerializer.

Features

  • LINQ to JSON
  • The JsonSerializer for quickly converting your .NET objects to JSON and back again
  • Json.NET can optionally produce well formatted, indented JSON for debugging or display
  • Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized
  • Ability to convert JSON to and from XML
  • Supports multiple platforms: .NET, Silverlight and the Compact Framework

The JSON serializer is a good choice when the JSON you are reading or writing maps closely to a .NET class. The serializer automatically reads and writes JSON for the class.

For situations where you are only interested in getting values from JSON, don’t have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects then LINQ to JSON is what you should use. LINQ to JSON allows you to easily read, create and modify JSON in .NET.

Json.NET CodePlex Project

Json.NET Download

Posted in ASP.NET Ajax, JQuery, JavaScript, Linq | Tagged: , , | Leave a Comment »