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

Asp.net TextBox post-back on each character entry


In This post I am going to Explain How to send a Request to asp.net server on every character entry in textbox control…

for this i am preparing a custom control with above functionality… named as PostBackTextBox..

First Take a Class Library Project and Delete Existing Classes then Add one class with name PostBackTextBox

Add System.Web Reference

Add System.Web Reference

and write the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
[assembly: WebResource("PostBackTextBox.Scripts.PostBackTextBox.js", "text/javascript")]
namespace PostBackTextBox
{
    [Description("PostBackTextbox")]
    [ToolboxData(@"<{0}:PostBackTextBox Text="""" AutoPostBack=""true"" runat=""server""></{0}:PostBackTextBox>")]
     public class PostBackTextBox : System.Web.UI.WebControls.TextBox
    {
            public override string Text
            {
                get
                {
                    return base.Text;
                }
                set
                {
                    base.Text = value;

                    Attributes["value"] = value;
                }
            }
            public override bool AutoPostBack
            {
                get
                {
                    return true;
                }
                set
                {
                    base.AutoPostBack = true;
                }
            }
            protected override void AddAttributesToRender(HtmlTextWriter writer)
            {
                writer.AddAttribute("onkeyup", "Refresh(this.id);");
                writer.AddAttribute("onfocus", "SetCursorToTextEnd(this.id);");
                base.AddAttributesToRender(writer);
            }

            protected override void OnPreRender(EventArgs e)
            {
                base.OnPreRender(e);
                Attributes["value"] = Text;
                ClientScriptManager cs = this.Page.ClientScript;
                cs.RegisterClientScriptInclude("PBTBScript", cs.GetWebResourceUrl(this.GetType(), "PostBackTextBox.Scripts.PostBackTextBox.js"));
            }
        }
    }

and add one Folder with name Scripts and add one script file and set the script file properties as Build action is Embedded Resource

GoTo Script File Properties

Select Build Action As Embedded Resource

and add following code in script file

function Refresh(textControlID1) {
    __doPostBack(textControlID1, '');
};
function SetCursorToTextEnd(textControlID) {
    var text = document.getElementById(textControlID);
    if (text != null && text.value.length > 0) {
        if (text.createTextRange) {
            var range = text.createTextRange();
            range.moveStart('character', text.value.length);
            range.collapse();
            range.select();
        }
        else if (text.setSelectionRange) {
            var textLength = text.value.length;
            text.setSelectionRange(textLength, textLength);
        }
    }
}

DownLoadSampleCode

How to create DataTable and add primary key to DataTable in asp.net


Creating DataTable:
//create inatance of datatable
DataTable dt = new DataTable();
//give datatable name to dt
dt.TableName = "MyTable";
//add columns to datatable dt
dt.Columns.Add("ImgPath", typeof(string));
//creating primary key column
DataColumn[] Key = new DataColumn[1];
DataColumn col = new DataColumn();
//setting datatype to column
col.DataType = System.Type.GetType("System.String");
//giving column name
col.ColumnName = "Name";
//adding column to datatable dt
dt.Columns.Add(col);
Key[0] = col;
// adding other columns to datatable directly
dt.Columns.Add("Desc", typeof(string));
dt.Columns.Add("Price", typeof(string));
//setting primary key to datatable
dt.PrimaryKey = Key;

 

Adding Data to Created DataTable:

//creating new data row
DataRow dr = dt.NewRow();
//adding data to the above created datarow
dr[0] = "ImgPath";
dr[1] = "Name";
dr[2] = "Desc";
dr[3] = "123.45";
//adding datarow to datatable
dt.Rows.Add(dr);

Complete Asp.net Project On Entity Framework and crystal Reports


Hi Guys… On sep-21st-2012 My site completes 1 year so that i am providing free downlod of a project entitled as HOUSE FINANCE APPLICATION

This project includes

1.Asp.net

2.Ado.net

3.Crystal Reports

4.linq to entities

5.Jquery

6.Asp.net Ajax

7.Sql & Tsql

DownLoadDownloadProject

AJAX::SlideShow Extender Control Example


In this post we can learn how to do slideshow using ajax
Code in ASPX page:
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
    <title></title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .style3
        {
            width: 353px;
        }
    </style>
</head>
<body>
<form id="form2" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table>
<tr><td class="style3"></td>
<td align="center">
<asp:Label ID="Label1" runat="server"
Text="Label" style="font-size: x-large;
color: #FF3300; font-family: Arial, Helvetica, sans-serif;
font-weight: 700; background-color: #FFFFCC">
</asp:Label><br />
<asp:Image ID="Image2" runat="server" Height="299px"
Width="350px" />
<asp:SlideShowExtender ID="Image1_SlideShowExtender"
runat="server" AutoPlay="True" Enabled="True"
Loop="True" SlideShowServiceMethod="GetSlides"
SlideShowServicePath="" TargetControlID="Image1"
UseContextKey="True" ImageDescriptionLabelID="Label2"
ImageTitleLabelID="Label1" NextButtonID="Button3"
PlayButtonID="Button2" PlayButtonText="Play"
PlayInterval="1500" PreviousButtonID="Button1"
StopButtonText="Stop"></asp:SlideShowExtender>
<br /><asp:Label ID="Label2" runat="server" Text="Label"
style="font-size: x-large; color: #0000FF; font-family:
Verdana; background-color: #CCFFFF"></asp:Label><br />
<asp:Button ID="Button2" runat="server" Text="Previous" />
<asp:Button ID="Button3" runat="server" Text="Stop" />
<asp:Button ID="Button4" runat="server" Text="Next" />
</ContentTemplate>
</asp:UpdatePanel></td>
</tr>
</table>
</div>
</form>
</body>
</html>
Code behind:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static AjaxControlToolkit.Slide[] GetSlides(string contextKey)
    {
        AjaxControlToolkit.Slide[] slides = new AjaxControlToolkit.Slide[10];
        slides[0] = new AjaxControlToolkit.Slide("Images/0.jpg", "baby Image", "this is hd image from flikar");
        slides[1] = new AjaxControlToolkit.Slide("Images/1.jpg", "cutebaby image", "this is hd image from google");
        slides[2] = new AjaxControlToolkit.Slide("Images/2.jpg", "nicebaby", "this image from bing");
        slides[3] = new AjaxControlToolkit.Slide("Images/3.jpg", "goodbaby", "this image from asp.net info blog");
        slides[4] = new AjaxControlToolkit.Slide("Images/4.jpg", "nicebaby", "this also…");
        slides[5] = new AjaxControlToolkit.Slide("Images/5.jpg", "cutebaby", "this too…");
        slides[6] = new AjaxControlToolkit.Slide("Images/6.jpg", "smartbaby", "this one also…");
        //return default(AjaxControlToolkit.Slide[]);
        return slides;
    }

download Download Sample Code

How to apply distinct Method on particular column in LINQ


Sometimes we need to select two or more columns based on one column distinct
in this situation if we have one primary column and one columns allows duplicates so now we want to read these two columns based on column which allow duplicates… in this situation if we apply Distinct method it will takes records based on primary key column, it won’t read based on other column…
To do that….follows these steps…

first create one method for DistinctBy

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
        {
            var set = new HashSet<TKey>();
            return source.Where(element => set.Add(selector(element)));
        }

and use this method to do Distinct based on Particular column…

var x = (from n in context.tblEmployees.Where(i => i.EMPLOYEE_ID == EmployeeId) select n).DistinctBy(i => i.EmployeeName).ToList();

Thanks…

……………HappyCoding……….

Confirm Box with yes and no options using javascript


Download Good Example

Sometimes we need to show Confirmation message to user with yes or no options…
Now we will learn about how to do this confirmation using javascript…
we can do this in different situations…
1.simple confirmation(alert)
2.with user choice we need to do the operation(confirm)
3.prompt user to enter something(prompt)

1.SimpleConfirmation(alert box)
we can use this alert box to display some simple message to user with ok button..
until user click on ok button browser won’t allow to next step…

2.ConfirmationBox with Yes and No options(confirm box)
we can use this confirm box to display confirmation to user
user need to select either yes or no, based on this user selection we can do different tasks…

3.promptbox with textbox(prompt box)
we can use this prompt box to simple data from the user…

I made an example with ticket booking in movie theatre…

<!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>
<title></title>

<script language="javascript" type="text/javascript">
// <!CDATA[

    function MyFnBooking(image) {
        var x = document.getElementById(image);
        if (x.src.substring(x.src.lastIndexOf("https://chikkanti.files.wordpress.com/2012/08/red.jpg&quot;)) != "https://chikkanti.files.wordpress.com/2012/08/red.jpg&quot;) {
            if (confirm('Are you sure u want to book this seat..?')) {
                x.src = "https://chikkanti.files.wordpress.com/2012/08/green.jpg&quot;;
                var x = prompt('Enter Your Name');
                alert(x + " Your seat Confirmed..!");
            }
            else {
                alert("Thanks for visiting..!");
            }
        }
        else {
            alert("This seat is already Booked..!");
        }
    }
// ]]>
</script>
</head>
<body>
<table>
<tr><td><img id="imgSeat1" src="https://chikkanti.files.wordpress.com/2012/08/gray.jpg&quot; onclick="MyFnBooking(this.id)"/></td></tr></table>
</body>
</html>

How to use in asp.net

we can use onclientclick  to show this confirm box

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript" language="javascript">
    function MyFunction() {
        if (confirm('Are you sure u want to delete ?')) {
            return true;
        }
        else {
            return false;
        }
    }
    function MyFunctionToGoogle(GoogleURL) {
        if (confirm('Are you sure u want to go Google ?')) {
            alert(GoogleURL);
            window.location = "http://www.Google.com&quot;;

            return true;
        }
        else {
            return false;
        }
    }
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Click!" onclick="Button1_Click"
OnClientClick="return confirm('Are you sure u want to delete','?');"/>
<asp:Button ID="Button2" runat="server" Text="Click!" onclick="Button1_Click"
OnClientClick="if(!confirm('Are you sure u want to delete ?')){return false;}"/>
<asp:Button ID="Button3" runat="server" Text="Click!" onclick="Button1_Click"
OnClientClick="if(!MyFunction()){return false;}"/>
<asp:Button ID="Button4" runat="server" Text="Click!"
OnClientClick="if(!MyFunctionToGoogle('http://www.google.com&#039;)){return false;}"/>
</div>
</form>
</body>
</html>

Thanks

…………HappyCoding…….