How can we force clients to refresh JavaScript files?


Q: How can we force web clients to refresh or load latest version javascript files from the web server.

This is the problem most of the web developers facing after deploying their newer versions of javascript files.

We normally ask the customer to hit Ctrl + F5 to ensure that all the latest javascript files loaded from server not from the cache.

But we can solve this in different ways as follows

Solution 1: If you are maintaining javascript versioning

If you are using javascript versions, it’s easy to solve the issue. i.e we just need to add the version to javascript file path as follows

<script src="~/scripts/demojs.js?100"></script>
<script src="~/scripts/demojs.js?version=100"></script>

so If the version of the file changed then the url also change. so if the url is different than the file which is already in cache, the browser (client) will request to get latest file from the server.

So these file will render to clients as follows

Loading from cache

image

Loading from server

image

Solution 2: If you are not using versioning use Asp.Net MVC datetime object ticks

In this case we just use ticks from C# datetime object as follows

<script src="~/scripts/demojs.js?@DateTime.Now.Ticks"></script>
<script src="~/scripts/demojs.js?currentTime=@DateTime.Now.Ticks"></script>

image

Solution 3: Restart application and Recycle Application pool in IIS

Please do following steps after completion of your deployment in IIS

  1. Restart your website

image

2. Then find the applicationpool of your website and recycle it.

image

In case of Microsoft Azure websites

Screenshot_10

Thanks

Happy coding ComputerSmile

Advertisements

Better way to store files in Database or in filesystem..?


If you are working with files in asp.net it is better to Store the files on the file system and filepath in the database. In many situations, databases are stored on fast (read: expensive storage, 15k RPM or SSD drives) storage. Images or other files, typically can be stored on slower (read: cheaper, larger drives, 7.2k RPM drives) storage.

Because…

  1. You can access files faster
  2. easier to configure security settings
  3. No size limitation
  4. You will be able to serve the pictures as static files.
  5. No database access or application code will be required to fetch the pictures.
  6. The images could be served from a different server to improve performance.
  7. you don’t get into any trouble, if you have to migrate your back end.
  8. It will reduce database bottleneck.
  9. The database ultimately stores its data on the file system.
  10. Images can be easily cached when stored on the file system.

still if you want to store files in DataBase only, better to use FileStream field type which can provide the best of both worlds.

How to handle Double click event of asp.net button using JQuery


Subject: Here we can Learn how to Handle Double click event of Asp.Net controls using Jquery, here i will explain with asp.net button control

If you are New to Jquery Start from here.

first take new asp.net empty website and add jquery library to website and add one asp.net webform and write following code

JQuery Script:

<script type="text/javascript">
        $(function () {
            $("input[id$=Button1]").bind({
                click: function (e) {
                    e.preventDefault();
                },
                dblclick: function () {
                    alert("DoubleClick Happed to Button");
                }
            });
        });
    </script>

CompleteCode:

<%@ Page Title="Handling DoubleClick of Asp.Net Button" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="HandlingDoubleClick.aspx.cs" Inherits="HandlingDoubleClick" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("input[id$=Button1]").bind({
                click: function (e) {
                    e.preventDefault();
                },
                dblclick: function () {
                    alert("DoubleClick Happed to Button");
                    //write ur code here
                }
            });
        });
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Button ID="Button1" runat="server" Text="Double click on me" />
</asp:Content>

Explanation:

Here i am explaining Example with Master pages, the reason is, when the asp.net webform renders as html in browser it will assign dynamic ids for asp.net controls while merging master page and content page. Here why asp.net assigning dynamic ids, because to avoid naming collision

so here we have to use

$("input[id$=Button1]")

this statement to get asp.net control with dynamic id

and Bind method will bind events to control, here we are binding click and double click events

Click Event:

click: function (e) {
                    e.preventDefault();
                },

in this click event we are preventing default behavior of asp.net button control, i.e preventing post back

Double click Event:

dblclick: function () {
                    alert("DoubleClick Happed to Button");
                    //write ur code here
                }

in this double click event write your code…

 

Happy Coding….

If u have any drought feel free to contact from AboutMe page

How to Expand or Collapse panel when checkbox is checked or unchecked using JQuery with Asp.Net


Here we can learn how to expand or collapse a panel when user check or uncheck the checkbox using JQuery with asp.net

if you are very new to Jquery start from here.

Take a new website and add one webform(file—> new –> website—> asp.net Empty website—> enter website name—> press Ok—> add one webform to root directory)

then add our JQuery library file to the website as shown below

JQueryScripts

add that jquery-1.7.js file to webform and write following code

JQuery Script:

<script type="text/javascript">
        $(function () {
            $("input[id$=chkCollapseExpand]").click(function () {
                if ($(this).attr("checked")) {
                    $("div[id$=pnlCollapsable]").slideDown('slow');
                }
                else {
                    $("div[id$=pnlCollapsable]").slideUp('slow');
                }
            });
        });
    </script>

Total Code:

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("input[id$=chkCollapseExpand]").click(function () {
                if ($(this).attr("checked")) {
                    $("div[id$=pnlCollapsable]").slideDown('slow');
                }
                else {
                    $("div[id$=pnlCollapsable]").slideUp('slow');
                }
            });
        });
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:CheckBox ID="chkCollapseExpand" runat="server" Text="Show/Hide" />
    <asp:Panel ID="pnlCollapsable" runat="server" Width="400" BackColor="#FF99FF" BorderColor="Fuchsia" BorderWidth="5" Font-Size="X-Large" EnableViewState="True" style="display:none;">
        This is Jquery example for expand and collapse when user clicks on checkbox from https://chikkanti.wordpress.com
    </asp:Panel>
</asp:Content>

Explanation:

$("input[id$=chkCollapseExpand]")

Reading Checkbox Control of type input

$(this).attr("checked")

checking weather check box is checked or not by reading checked attribute

$("div[id$=pnlCollapsable]").slideDown('slow');

reading panel and expanding by calling slideDown method

slow will add little animation to panel while expanding

$("div[id$=pnlCollapsable]").slideUp('slow');

reading panel and Collapsing by calling slideUp method

slow will add little animation to panel while Collapsing

 

OutPut:

Hide Show

=====================================

Happy Coding………..

Working with JQuery and Asp.Net


Here i would like to talk about JQuery, what is JQuery, how to use it with asp.net

 

We all know what is Javascript and the importance of Javascript while building Dynamic web forms.

JQuery is Javascript library, it contains all predefined code includes animation, UI, and some useful code functionality.

The advantage of JQuery is, it will support almost all browsers(IE,Chrome,Firefox,Safari,Opera..)

we can download JQuery library from here.

and also some CDNs are also available for Jquery, Google and Microsoft are Providing CDNs for JQuery

Google CDN: <script src=”//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js”></script>

Microsoft CDN:

<script src=”http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js”></script&gt;

after completing downloading JQuery Library, start working with asp.net by adding JQuery library to Asp.Net Website.

JQueryINVS

VisualStudio2010 By default include JQuery-1.4.1 in asp.net website and also includes jquery-1.4.1-vsdoc.js file.

This file is for VisualStudio2010 Intellisense. if open this file you can find following content as commented.

/*
* This file has been commented to support Visual Studio Intellisense.
* You should not use this file at runtime inside the browser–it is only
* intended to be used only for design-time IntelliSense.  Please use the
* standard jQuery library for all production use.
*
* Comment version: 1.4.1a
*/

Intellisense works as follows:

VSI

 VSI2

We can use jquery-1.4.1.js file for production use.

Example:

Open VisualStudio and select File –> New –> Website –> ASP.NET Empty Website –> Enter Some name of website—> Ok.

Now Add New folder and name it as Scripts, and add scripts to this folder and add one webform Default.aspx as follows.

JqueryWebsite

open Default.aspx file and add JQuery-1.7.js file to it and write following code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            alert("Welcome to JQuery");
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

Explanation:

ready function will rise when DOM is ready to use

in that ready function we can write our code.

Output:

Welcome to Jquery

Select single RadioButton in GridView when RadioButton’s GroupName is not working in asp.net using JavaScript


Here we will learn how to avoid Radiobutton or RadioButtonList allows multiple selections in GridView without using any RadioButton’s Group in asp.net C#
First Create Table as follows

tbl_Employee

Add the data into the table

Data

JavaScript Code:

<script language=”javascript” type=”text/javascript”>
function SetUniqueRadioButton(index) {
for (i = 0; i < IsManager.length; i++) {
var rb_Visitor = document.getElementById(IsManager[i]);
if (i == index) {
rb_Visitor.checked = true;
}
else {
rb_Visitor.checked = false;
}
}
}
</script>

Form Content:

<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”
OnRowDataBound=”GridView1_RowDataBound” onprerender=”GridView1_PreRender”>
<Columns>
<asp:BoundField DataField=”EmpId” HeaderText=”Emp Id” />
<asp:BoundField DataField=”EmpName” HeaderText=”Emp Name” />
<asp:TemplateField HeaderText=”Is Manager”>
<ItemTemplate>
<asp:RadioButton ID=”rb_IsManager” GroupName=”ss” runat=”server” Text=’<%#Eval(“IsManager”) %> />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”DOJ” HeaderText=”Date of Join”
DataFormatString=”{0:d}” />
</Columns>
</asp:GridView>
</div>
</form>

ConnectionString in Web.Config file:

<connectionStrings>
        <addname=ConnectionStringconnectionString=Data Source=YourServerName;Initial Catalog=DemoDB;Persist Security Info=True;User ID=sa;Password=yourPassword/>
    </connectionStrings>

NameSpaces To Use:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

Filling GridView:

protected void Page_Load(object sender, EventArgs e)
{
GetData();
}
string connectionstring = ConfigurationManager.ConnectionStrings[“ConnectionString”].ToString();
public void GetData()
{
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(“select EmpId,EmpName,IsManager,DOJ from tbl_employee”, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}

Binding OnClick Javascript Method with RowIndex to RadioButton in GridView RowDataBound Event:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow row = (GridViewRow)e.Row;
RadioButton rb_IsManager = (RadioButton)row.FindControl(“rb_IsManager”);
rb_IsManager.Attributes.Add(“onclick”, “SetUniqueRadioButton(“ + row .DataItemIndex + “)”);
if (Convert.ToBoolean(rb_IsManager.Text))
{
rb_IsManager.Text = “”;
rb_IsManager.Checked = true;
}
else
{
rb_IsManager.Text = “”;
rb_IsManager.Checked = false;
}
}
}

Collecting all RadioButtons ClientIds in GridView PreRender Event:

protected void GridView1_PreRender(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
foreach (GridViewRow grdrow in GridView1.Rows)
{
RadioButton rb_IsManager = (RadioButton)grdrow.FindControl(“rb_IsManager”);
cs.RegisterArrayDeclaration(“IsManager”, String.Concat(“‘”, rb_IsManager.ClientID, “‘”));
}
}

Complete Code:

(.aspx)

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Radiobuttongroup in grid.aspx.cs”
Inherits=”Radiobuttongroup_in_grid” %><!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>

<script language=”javascript” type=”text/javascript”>
function SetUniqueRadioButton(index) {
for (i = 0; i < IsManager.length; i++) {
var rb_Visitor = document.getElementById(IsManager[i]);
if (i == index) {
rb_Visitor.checked = true;
}
else {
rb_Visitor.checked = false;
}
}
}
</script>

</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”
OnRowDataBound=”GridView1_RowDataBound” onprerender=”GridView1_PreRender”>
<Columns>
<asp:BoundField DataField=”EmpId” HeaderText=”Emp Id” />
<asp:BoundField DataField=”EmpName” HeaderText=”Emp Name” />
<asp:TemplateField HeaderText=”Is Manager”>
<ItemTemplate>
<asp:RadioButton ID=”rb_IsManager” GroupName=”ss” runat=”server” Text=’<%#Eval(“IsManager”) %> />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”DOJ” HeaderText=”Date of Join”
DataFormatString=”{0:d}” />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

(.aspx.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;public partial class Radiobuttongroup_in_grid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetData();
}
string connectionstring = ConfigurationManager.ConnectionStrings[“ConnectionString”].ToString();
public void GetData()
{
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(“select EmpId,EmpName,IsManager,DOJ from tbl_employee”, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow row = (GridViewRow)e.Row;
RadioButton rb_IsManager = (RadioButton)row.FindControl(“rb_IsManager”);
rb_IsManager.Attributes.Add(“onclick”, “SetUniqueRadioButton(“ + row .DataItemIndex + “)”);
if (Convert.ToBoolean(rb_IsManager.Text))
{
rb_IsManager.Text = “”;
rb_IsManager.Checked = true;
}
else
{
rb_IsManager.Text = “”;
rb_IsManager.Checked = false;
}
}
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
foreach (GridViewRow grdrow in GridView1.Rows)
{
RadioButton rb_IsManager = (RadioButton)grdrow.FindControl(“rb_IsManager”);
cs.RegisterArrayDeclaration(“IsManager”, String.Concat(“‘”, rb_IsManager.ClientID, “‘”));
}
}
}

OutPutScreen:

Select single RadioButton in GridView when RadioButton's GroupName is not working in asp.net using JavaScript

=======================================================>0<=====================================================================

Happy Coding

=======================================================>0<=====================================================================

How to check Entered Value in TextBox is Number or not in JavaScript


Sometimes we stuck in a situation like we have to take only integer number from textbox and leave if the value is not a number in JavaScript…

we have the solution with isNaN() function in JavaScript see this example to understand clearly.

Example :

JavaScript:

<script type="text/javascript">
        function CheckNumberOrNot() {
            var Age = document.getElementById("Age");
            var result = isNaN(Age.value);
            if (!result) {
                alert("You are : " + Age.value + " years old.");
            } else {
                alert("Not recognized as Valid No.");
            }
        }
    </script>

 

Complete Code (Jsp):

<%@ Page Language="java" import="java.util.*" pageEncoding="ISO-8859-1" %>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";

%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</title>

    <script type="text/javascript">
        function CheckNumberOrNot() {
            var Age = document.getElementById("Age");
            var result = isNaN(Age.value);
            if (!result) {
                alert("You are : " + Age.value + " years old.");
            } else {
                alert("Not recognized as Valid No.");
            }
        }
    </script>

</head>
<body>
    This is my JSP page.
    <br />
    <br />
    Age:
    <input type="text" id="Age" name="Age">
    <br />
    <br />
    <input type="button" value="submit" onclick="CheckNumberOrNot();" align="center" />
</body>
</html>

OutPut :

FormDesign

Invalid Number

Valid Number