Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for the ‘JavaScript’ Category

Check File type at client side – jQuery

Posted by Ramani Sandeep on February 4, 2011

Whenever we use fileupload control on web pages , the common requirement is to validate its file type and size.

we usually find it difficult to validate file size on client side rather than at server side. As of now there is no alternative script found that can achieve this. There are certain alternatives to achieve above validation on client side but that are not browser compatible & as security level changes in browser it stop functioning, so we still not at that level of trust that we can check file size at client side using jQuery/javascript.

Although it is possible to validate filetype using jquery/javascript and i m looking to do some coding for you to achieve the same. i hope this will help some developers to validate file type at client side rather than checking it on server.

Here is the javascript code that achieve above functionality :


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

    <script type="text/javascript" language="javascript">

        function FileTypeValidate() {

            //get filepath from fileupload control on the page
            var fileUpload = $('#<%=FileUpload1.ClientID %>').val();

            //extracting part of the filename from dot
            var extension = fileUpload.substring(fileUpload.lastIndexOf('.'));

            //valid file type - static
            var ValidFileType = ".jpg , .png , .bmp";
            //or fetch it from config file for flexibility ,
	    //we can save valid file type list in web.config also & fetch it during validation process
            var ValidFileTypeConfig = '<%=ConfigurationManager.AppSettings["ValidFileType"].ToString() %>';

            //check whether user has selected file or not
            if (fileUpload.length > 0) {

                //check file is of valid type or not
                if (ValidFileType.toLowerCase().indexOf(extension) < 0) {
                    alert("please select valid file type...");
                }
                else {
                    alert("file type is valid...");
                    return true;
                }
            }
            else {
                alert("please select file for upload...");
            }
            return false;
        }
    </script>

Above code explain itself a lot so no need to discuss further on it.

Here is the html markup that shows controls on the page :


    <form id="form1" runat="server">
     <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Upload" OnClientClick="return FileTypeValidate();" />
     </div>
    </form>

This is very simple but very common scenario for the web applications & very effective if managed properly…

Thats it, hope this will help !!!

Jay Ganesh

About these ads

Posted in CodeProject, JavaScript, JQuery | Tagged: , , , | 1 Comment »

Best Practices for Speeding Up Your Web Site

Posted by Ramani Sandeep on January 30, 2010

The Exceptional Performance team has identified a number of best practices for making web pages fast. The list includes 34 best practices divided into 7 categories.

1) Content

  • Minimize HTTP Requests
  • Reduce DNS Lookups
  • Avoid Redirects
  • Make Ajax Cacheable
  • Post-load Components
  • Preload Components
  • Reduce the Number of DOM Elements
  • Split Components Across Domains
  • Minimize the Number of iframes

2) Server

  • Use a Content Delivery Network
  • Add an Expires or a Cache-Control Header
  • Gzip Components
  • Configure ETags
  • Flush the Buffer Early
  • Use GET for AJAX Requests

3) CSS

  • Put Stylesheets at the Top
  • Avoid CSS Expressions
  • Choose <link> over @import
  • Avoid Filters

4) Javascript

  • Put Scripts at the Bottom
  • Make JavaScript and CSS External
  • Minify JavaScript and CSS
  • Remove Duplicate Scripts
  • Minimize DOM Access
  • Develop Smart Event Handlers

5) Cookie

  • Reduce Cookie Size
  • Use Cookie-free Domains for Components

6) Images

  • Optimize Images
  • Optimize CSS Sprites
  • Don’t Scale Images in HTML
  • Make favicon.ico Small and Cacheable

7) Mobile

  • Keep Components under 25K
  • Pack Components into a Multipart Document

           Read more

Posted in ASP.NET, ASP.NET 3.5, ASP.NET 4.0, ASP.NET Ajax, Css, JavaScript, Performance | Tagged: , | Leave a Comment »

MultiSelect Dropdown in ASP.NET

Posted by Ramani Sandeep on January 29, 2010

In this article, I will show you a different way of doing a multi-select in an ASP.NET page. I will keep this article short and sweet so you can just use the code in your applications.

We are going to put our CheckBoxList ASP.NET control inside an HTML div object. I have also added code to support changing the background color of the selected row.

Read more

Shout it

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

How to dynamically adjust an iframe’s height?

Posted by Ramani Sandeep on December 16, 2009

Last day when I was using iframe in one of my project , i came across one problem & I have solved it now.

so I think why not to share with you all. I was looking to display content of the other aspx page inside iframe but i wasnt able to adjust the height of the iframe. so try out this solution to resolve it.

Insert iframe on page

   <iframe scrolling='no' frameborder='0' id='frmid' src=’getad.aspx'
            onload='javascript:resizeIframe(this);'>
   </iframe>

Use this javascript to resize iframe based on the height & width of child page

<script language="javascript" type="text/javascript">
 function resizeIframe(obj)
 {
   obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
   obj.style.width = obj.contentWindow.document.body.scrollWidth + 'px';                        
 }
 </script>

What does this code do? When the body of the parent frame loads, it looks up the document element “childframe” which corresponds to the iframe. Then the page calls a function resizeFrame(). The function sets the height of the frame to be the scrollHeight, which effectively removes the scrollbar.

Hope this will help !!!

kick it on DotNetKicks.com

Shout it

Posted in Css, JavaScript | Tagged: , , , | 32 Comments »

CodeRun Web Toolkit: C# to JavaScript web framework

Posted by Ramani Sandeep on December 3, 2009

What is CodeRun Web Toolkit?

CodeRun Web Toolkit (CWT) is a complete framework for creating Rich Internet Applications with C#. CWT provides the following components:

  • C# to JavaScript converter
  • C# to JavaScript remoting handler
  • Rich UI library, loosely modeled after WPF (Windows Presentation Foundation)

You can use CodeRun Web Toolkit to:

  • Implement client side scripts for existing ASP.NET applications with C#
  • Work with external JavaScript libraries (such as YUI) in C#.
  • Develop compelling and optimized AJAX Applications in C#

CodeRun Web Toolkit Added Features

Language Features

  • Namespaces
  • Classes
  • Interfaces
  • Properties
  • Events
  • Method Overloads
  • Polymorphism
  • Extension Methods
  • Delegates
  • Indexers
  • Generics
  • LINQ
  • Reflection and Attributes
  • Object Initializers

Productivity Features (in Visual Studio)

  • Compilation Error Reporting
  • Code Coloring
  • Code Refactoring
  • Performance Profiling

Toolkit Features

  • Ajax as method calls
  • Rich UI Library

Simple code example

The following example demonstrates how to write a simple C# method and use CodeRun Web Toolkit to convert it to JavaScript:

//Demonstrates how to execute a C# class at the browser
namespace CWT_Samples
{
  public partial class SimpleExample : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
     {
       this.RegisterRunAtClientScripts(SimpleExample_Client.Main, head, body);
     }
   }

  //The following class will be converted to JavaScript
  [RunAtClient]
  public class SimpleExample_Client
  {
     public static void Main()
     {
        var window = HtmlDom.Window;
        window.alert("Hello from C#!");
     }
  }
}

for more information – click here

Posted in C# 2.0, JavaScript | Tagged: , , | 1 Comment »

Hide/Change Sort expression link in gridview

Posted by Ramani Sandeep on November 27, 2009

Today I was reading http://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, JavaScript, JQuery | Tagged: , , , | Leave a Comment »

Color Picker

Posted by Ramani Sandeep on November 6, 2009

There are lots of way show color picker on web site. Today I was search for such color picker which I want to use it in one of my website.

I have searched a lot of color picker that can be useful, so here I m writing about it.

ColorPicker AJAX Extender

ColorPicker is an ASP.NET AJAX extender that can be attached to any ASP.NET TextBox control. It provides client-side color-picking functionality with UI in a popup control. You can interact with the ColorPicker by clicking on a colored area to set a color. It requires a binary reference to the ASP.NET AJAX Control Toolkit.

ColorPicker extender is multi-browser compatible: it works with IE 6/7/8, Firefox, Safari and Goggle Chrome. ColorPicker is built on top of ASP.NET AJAX Control Toolkit and internally utilizes a Popup extender. ColorPicker is compatible with the UpdatePanel: can be placed inside the UpdatePanel.

ColorPicker is included in Ajax Control Toolkit since Release 30512. For those who use previous release of Ajax Control Toolkit this ColorPicker project will continue to evolve and stay in sync with the Ajax Control Toolkit.

Read more…

Color Picker using javascript

This widget is used to select a color, in hexadecimal #RRGGBB form. It uses a color "swatch" to display the standard 216-color web-safe palette. The user can then click on a color to select it.

This script is very simple to implement, and can add a lot of style to your page that requires color values!

Because of the size of the table, this color picker may be slow on lower-end machines. Consider your target users when deciding whether or not it operates fast enough.

Read more…

Posted in ASP.NET, ASP.NET 3.5, ASP.NET Ajax, 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 JavaScript, 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 JavaScript, 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, JavaScript, JQuery, Linq | Tagged: , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 124 other followers