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

How to set radwindow behaviors through ClientSide javascript


<script type=”text/javascript” language=”javascript”>
function ShowPopup() {
var oWnd = radopen(“Popups/Employees.aspx”, “radWin_Employees”);
oWnd.SetTitle(“Visitors”);
oWnd.set_initialBehaviors(Telerik.Web.UI.WindowBehaviors.None);
oWnd.set_behaviors(Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Move);
}
</script>

RadWindow position – always in the center of screen through ClientSide javascript


<script type="text/javascript" language="javascript">
            function ShowPopup() {
                var oWnd = radopen("Popups/Employees.aspx", "radWin_Employees");
                oWnd.SetTitle("Visitors");
                oWnd.SetSize(950, 502);
                oWnd.Center();
            }
        </script>

How to convert first letter of each word to uppercase of text entering in textbox in asp.net


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

<!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 type="text/javascript" language="javascript">
      function myFunction(id) {
      var txt  = document.getElementById(id);
      txt.value = txt.value.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
     }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" onkeyup="myFunction(this.id)"></asp:TextBox>
    </div>
    </form>
</body>
</html>

How to convert entering text in textbox to LowerCase or UpperCase using Javascript in asp.net


If we want to convert Values Entering in textbox to LowerCase or UpperCase we can user onkeyup client event for textbox.
and to convert to LowerCase/UpperCase We can use Javascript Methods toLowerCase/toUpperCase.
See the following example to Understand how to use above methods…

toUpperCase:

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

<!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 ToUpper(id) {
            document.getElementById(id).value = document.getElementById(id).value.toUpperCase();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" onkeyup="ToUpper(this.id)"></asp:TextBox>
    </div>
    </form>
</body>
</html>

toLowerCase:

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

<!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 ToLower(id) {
            document.getElementById(id).value = document.getElementById(id).value.toLowerCase();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" onkeyup="ToLower(this.id)"></asp:TextBox>
    </div>
    </form>
</body>
</html>

HashTable in C#.net


The Hashtable class implement the IDictionary interface. Therefore, each element in this collection is a key-and-value pair.
it is a collection class like an arraylist but stores the value in name,value or key,value based. arraylist also stores values in key,value pairs only where index is the key which is predefined.

hashtable
in case of hashtable these keys can be userdefined which can be specified by us explicitely as per our requirement…
A Hashtable object consists of buckets that contain the elements of the collection. A bucket is a virtual subgroup of elements within the Hashtable, which makes searching and retrieving easier and faster than in most collections. Each bucket is associated with a hash code, which is generated using a hash function and is based on the key of the element.

Hashtable should not allow Duplicate Keys, but allows Duplicate Values

Examples in Console Application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace HashtableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();
            
            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //Displaying values in hashtable ht_employee
            Console.WriteLine("We Can display Hashtable Data in different Types of Logics");
            Console.WriteLine();
            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:1 If u don't know keys");
            Console.WriteLine("================================");
            foreach (DictionaryEntry de in ht_Employee)
            {
                Console.Write(de.Key + "\t:");
                Console.WriteLine(de.Value);
            }
            
            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:3 If u know keys");
            Console.WriteLine("================================");
            Console.Write("EmpId" + "\t:");
            Console.WriteLine(ht_Employee["EmpId"]);
            Console.Write("EmpName" + "\t:");
            Console.WriteLine(ht_Employee["EmpName"]);
            Console.Write("Job" + "\t:");
            Console.WriteLine(ht_Employee["Job"]);
            Console.Write("Sal" + "\t:");
            Console.WriteLine(ht_Employee["Sal"]);
            Console.Write("Dept" + "\t:");
            Console.WriteLine(ht_Employee["Dept"]);
            Console.Write("Loc" + "\t:");
            Console.WriteLine(ht_Employee["Loc"]);

            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:2 If u don't know keys");
            Console.WriteLine("================================");
            foreach (DictionaryEntry de in ht_Employee)
            {
                Console.Write(de.Key + "\t:");
                Console.WriteLine(ht_Employee[de.Key]);
            }
            Console.Read();
        }
    }
}

Output:

HashTableConsole

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Hashtable1
{
    class HashTableExtentions
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();

            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //If We add Existed key to hashtable it raises exception
            Console.WriteLine("==============================================================");
            Console.WriteLine("Add method Raise exception if new key is already in Hashtable");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            try
            {
                ht_Employee.Add("EmpId", 1000);
            }
            catch
            {
                Console.WriteLine("An element with Key = \"EmpId\" already exists.");
            }
            Console.WriteLine();

            //If we want to display values in discriptive manner
            Console.WriteLine("==============================================================");
            Console.WriteLine("If we want to display values in discriptive manner");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            Console.WriteLine("For key = \"EmpId\", value = {0}.", ht_Employee["EmpId"]);
            Console.WriteLine();

            //How to change values associated with keys in hashtable
            Console.WriteLine("==============================================================");
            Console.WriteLine("If we want to display values in discriptive manner");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            Console.WriteLine("For key = \"EmpId\", Oldvalue = {0}.", ht_Employee["EmpId"]);
            ht_Employee["EmpId"] = 101;
            Console.WriteLine("For key = \"EmpId\", Newvalue = {0}.", ht_Employee["EmpId"]);
            Console.WriteLine();
            Console.Read();

        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Hashtable1
{
    class HashTableExtentions2
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();

            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //if we don't know wether the key is exist or not… we need to check and use that key
            //for this
            Console.WriteLine("==============================================================");
            Console.WriteLine("Checking wether key is exist or not");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            if (ht_Employee.ContainsKey("EmpName"))
            {
                Console.WriteLine("Value Exist for key = \"EmpName\": {0}", ht_Employee["EmpName"]);
            }
            Console.WriteLine();
            if(!ht_Employee.ContainsKey("SomeName"))
            {
                Console.WriteLine("Value Doesn't Exist for key = \"SomeName\"");
            }
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Adding Value for SomeName key");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            if (!ht_Employee.ContainsKey("SomeName"))
            {
                ht_Employee.Add("SomeName", "Raju");
                Console.WriteLine("Value Exist for key = \"SomeName\": {0}", ht_Employee["SomeName"]);
            }
            Console.WriteLine();

            //To get the values only, use the Values property.
            ICollection valueColl = ht_Employee.Values;

            //Print values in valueColl using foreach loop
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Print values in valueColl using foreach loop");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            foreach (object s in valueColl)
            {
                Console.WriteLine("Value = {0}", s);
            }

            //To get the keys only, use the Keys property.
            ICollection keyColl = ht_Employee.Keys;

            //Print keys in keyColl using foreach loop
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Print keys in keyColl using foreach loop");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            foreach (object s in keyColl)
            {
                Console.WriteLine("Key = {0}", ht_Employee[s]);
            }

            // Use the Remove method to remove a key/value pair.
            Console.WriteLine("\nRemove(\"SomeName\")");
            ht_Employee.Remove("SomeName");

            if (!ht_Employee.ContainsKey("SomeName"))
            {
                Console.WriteLine("Key \"SomeName\" is not found.");
            }
                
            Console.Read();
        }
    }
}

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