Posts

Showing posts from January, 2008

How to hide generated javascript file in visual studio code

In this post I am going to show you a cool trick in visual studio code. Let's suppose you are writing typescript code in visual studio code and you want to hide generated javascript code.

Create .vscode folder in your folder and then create settings.json file and paste following code

{ "files.exclude": { "node_modules":true, "**/.git": true, "**/.DS_Store": true, "**/*.js.map": true, "**/*.js": {"when": "$(basename).ts"}     } }

How To Open ModalPopup on page Load in ASP.NET

Image

JavaScript Get Key Values Or Code On KeyDown

<html><head><metahttp-equiv="Content-Type"content="text/html; charset=windows-1252"><title>Find KeyCode</title><scriptlanguage="JavaScript">function TriggeredKey(e) { var keycode; if (window.event) keycode = window.event.keyCode; alert("keycode: " + keycode); } </script></head><bodyonkeydown="TriggeredKey(this)"></body></html>Special Keyboard Key(s) CodeKeyCodeBackspace 8Tab 9Enter 13 Shift 16 Ctrl 17 Alt 18 Pause/Break 19 Caps Lock 20 Esc 27 Page Up 33 Page Down 34 End 35 Home 36 Left Arrow 37 Print Screen 44Delete 46F1 112F2 113F3 114F4 115F5 116F6 117F7 118F8 119F9 120F10 121F11 122F12 123

Restrict User From Ctrl Key Press

<html><head><metahttp-equiv="Content-Type"content="text/html; charset=windows-1252"><title>Restrict Ctrl Key Press</title><script>function Restrict() { if ((window.event.keyCode == 17)) { alert("Ctrl Key Press In !" + '\r\n' + "Add Your Own Code Here"); // Add Your Code Here } } </script></head><bodyonload="JavaScript:document.body.focus();"onkeydown="Restrict()"></body></html>

Get Mouse Position Using JavaScript

<html><body><scriptlanguage="JavaScript"> document.onmousemove = getCoordinate; var mosX = 0; var mosY = 0; function getCoordinate(e) { mosX = event.clientX + document.body.scrollLeft; //clientX Property Sets or retrieves the x-coordinate of the mouse//pointer's position relative to the client area of the window,//excluding window decorations and scroll bars//scrollLeft Property Sets or retrieves the distance between the//left edge of the object and the leftmost portion of the content//currently visible in the window. mosY = event.clientY + document.body.scrollTop; //clientY Property Sets or retrieves the y-coordinate of the mouse//pointer's position relative to the client area of the window,//excluding window decorations and scroll bars.//scrollTop Property Sets or retrieves the distance between the top//of the object and the topmost portion of the content currently…

Dynamically Increase The Size Of The TextBox Using JavaScript

<html><head><script>function incr() { var len = document.getElementById('txt').value; document.getElementById('txt').style.width = 75 + len.length * 4 + 'px'; } </script><body><inputtype='text'id='txt'onkeydown='incr()'style='width: 75px'/></body></html>

Trap F1 key in IE, ByPass Showing Help Window

<html><head><script>function ByPass() { var kCode = window.event.keyCode; if(kCode == 112) { alert('F1 Clicked'); // Alter Code As Your Wish } } </script></head><bodyonhelp="return false;"onkeydown="ByPass()"></body></html>

javascript function for invoking button click event

<htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title>javascript function for invoking btnclick event</title><scriptlanguage="javascript"type="text/javascript">function TrigButton() { if (window.event.keyCode == 13) { if (document.getElementById('txt').value.length > 0) { document.getElementById('bt').focus(); document.getElementById('bt').click(); } } } </script></head><body><formid="form1"runat="server"><div><asp:textboxid="txt"runat="server"onkeydown="TrigButton()"></asp:textbox><asp:buttonid="bt"runat="server"text="Button"onclientclick="javascript:alert('Button Triggered');"onclick="bt_Click"/></div></f…

How To Use Sleep Function Using JavaScript

<html><head><scriptlanguage='javascript'>function sleep() { var Sleep = setTimeout("alert('Hi Have A Nice Time And Day ')", 2000); // 2000 Millisecond(2 sec) } </script><bodyonload='sleep()'> Alert Box Will Be Displayed After 2 Seconds the Body is Loaded </body></html>

Restrict Numberic Input In TextBox

<html><head><scriptlanguage="javascript">function blockNum(e) { var keyVal = (window.event) ? event.keyCode : e.keyCode; if (window.event) keyVal = window.event.keyCode; if ((keyVal > 47 && keyVal < 58) || (keyVal > 95 && keyVal < 107)) { returnfalse; } } </script></head><bodyonload="javascript:document.getElementById('txt').focus();"><inputtype="text"id='txt'onkeydown="return blockNum(this);"/></body></html>

Restrict Alphabet Input In TextBox

<html><head><scriptlanguage="javascript">function blockChar(e) { var keyVal = (window.event) ? event.keyCode : e.keyCode; if (window.event) keyVal = window.event.keyCode; if ((keyVal > 64 && keyVal < 93)) { returnfalse; } } </script></head><bodyonload="javascript:document.getElementById('txt').focus();"><inputtype="text"id='txt'onkeydown="return blockChar(this);"/></body></html>

Restrict Alphabet Input In TextBox Using Regular Expression

<html><head><scriptlanguage="javascript">function blockChar() { var str = document.getElementById('txt').value; str = str.replace(/[^\d]*/g, ''); document.getElementById('txt').value = str; } </script></head><bodyonload="javascript:document.getElementById('txt').focus();"><inputtype="text"id='txt'onkeyup="blockChar();"/></body></html>

How TO Add copy to clipboard Button On Page

<html><head></head><body><textareaid='clipText'> Enter Text And Click Button To Copy Text To ClipBoard</textarea><br/><inputtype="button"id='bt'onclick="clipboardData.setData('Text',document.getElementById('clipText').value);"value="Copy"/><inputtype="button"onclick="clipboardData.clearData('Text');"value="Clear"/><inputtype="button"onclick="alert(clipboardData.getData('Text'));"value="Paste"/></body>

How To Block F5(Refresh) Key In IE and Firefox

<html><head><metahttp-equiv="Content-Type"content="text/html; charset=windows-1252"><title>Block F5 Key In IE & Mozilla</title><scriptlanguage="JavaScript">var version = navigator.appVersion; function showKeyCode(e) { var keycode = (window.event) ? event.keyCode : e.keyCode; if ((version.indexOf('MSIE') != -1)) { if (keycode == 116) { event.keyCode = 0; event.returnValue = false; returnfalse; } } else { if (keycode == 116) { returnfalse; } } } </script></head><bodyonload="JavaScript:document.body.focus();"onkeydown="return showKeyCode(event)"></body></html>

Sample source code for JavaScript Page Processing

We have provided below sample source code for JavaScript Page Processing in Asp.Net. You can copy and paste it in your pages to create the sample application. Code for Processing Page (PageProcessor.aspx) <htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title>Please wait...We Are Processing Your Request..</title><script>function PageOnLoad() { location.href = "<%=PageToLoad%>"; document.images['imgsrc'].src = "Images/Loading.gif"; } </script></head><bodybottommargin="0"leftmargin="0"rightmargin="0"topmargin="0"onload="PageOnLoad();"><formid="form1"runat="server"><div><tableborder="0"cellpadding="0"cellspacing="0"height="100%"width="100%"><tr><tdheight="50"class="NormalTe…

Trapping close of IE window in ASP.NET

Trap window close event for IE browser Let's say you want to trap the window close event for the web browser so that you can give a confirmation dialog asking if the user is sure to leave the page.The problem is that there is no onclose event for the window object.The closest event might be onunload since it fires immediately before the window object is unloaded. However, when the onunload event fires it is too late to display a JavaScript alert. Therefore, we need an event that fires prior to a page being unloaded, which is onbeforeunload. Define onbeforeunload event in your page <BODY> element as follows: <BODY onbeforeunload="HandleOnClose()"> Then, add the following JavaScript code into the <HEAD> section of your ASPX page: <scripttype="text/javascript">function HandleOnClose() { if (event.clientY < 0) { event.returnValue = 'Are you sure you want to leave the page?'; } }����…

How To Create your own CustomValidation Control In ASP.net 2.0

how to derive your custom control from a base class and add your own features. In this article we'll demonstrate how to derive a class from the BaseValidtor class to create your own validator control. Why would you do this? Well, in short the validator controls collection is very good, but as you will find they don't cover every type of validation you will need to do. You can use the custom validtor control to accomidate this, but if you need to do validtation in multiple places within your web application or even multiple web applications and sites then this isn't such a good solution. Instead, I would recommend creating a custom validation control and using that - why? Because it's cleaner!As previously mentioned this is an example of a very simple control. This validator control is derived from the base class BaseValidator . There is one properties added to the BaseValidator Email and the contents of the ControlToValidator must be this values.EmailValidator.csusin…

How To Upload Multiple Files

Image
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultipleUpload.aspx.cs" Inherits="MultipleUpload" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title></title><scripttype="text/javascript">//This function Creates the clone of the file upload control to upload images when //clicked on AddAnother link.The function first get the reference of the file upload //control "myElement1" added in HTML and the refernce of the td where we want to add //the new control and then creates the clone of this referenced file upload.//The vale attribute of this newly created control is set to null as it contains //the value of previously entered.The unique id and name is assigned to it and then //added in the TD. Before inser…

How To Convert ArrayList To DataSet

How to convert an arraylist to dataset or datatable so that I can filter or make a select distinct from it or Bind it to Gridview. public DataSet ConvertArrayListToDataSet() { DataSet dsTemp = new DataSet(); DataTable Tables = new DataTable(); dsTemp.Tables.Add(Tables); dsTemp.Tables[0].Columns.Add("val", System.Type.GetType( "System.String")); foreach (string str in arraylistcontainer) { if (str != string.Empty) { DataRow myRow = dsTemp.Tables[0].NewRow(); myRow[0] = str; dsTemp.Tables[0].Rows.Add(myRow); } } }

How To Use ICallback & JSON In ASP.NET

ICallback & JSON based Javascript Serialization Whilst working in asp.net sometimes we need to call server side methods asynchronously without have postback either it is full page postback or partial page postback so thanks to asp.net team to provide implementation of ICALLBACK very easily. ICALLBACK ICALLBACK is lightweight process, It uses well known xmlhttp object internally to call server side method, it doesn’t cause page postback so doesn’t cause page rendering so we to show output ICallback & JSON based Javascript SerializationWhilst working in asp.net sometimes we need to call server side methods asynchronously without have postback either it is full page postback or partial page postback so thanks to asp.net team to provide implementation of ICALLBACK very easily. ICALLBACKICALLBACK is lightweight process, It uses well known xmlhttp object internally to call server side method, it doesn’t cause page postback so doesn’t cause page rendering so we to show output at clie…

हाउ To Open NewWindow From CodeBehind Using ASP.NET

using System; using System.Collections.Generic; using System.Text; using System.Web; using System.IO; using System.Collections; using System.Web.UI; namespace com.StadiumRoar.Utility { publicclass Utilities { publicstaticvoid OpenPopUp(System.Web.UI.WebControls.WebControl opener, string PagePath, string windowName, int width, int height) { string clientScript; string windowAttribs; //Building Client side window attributes with width and height.////Also the the window will be positioned to the middle of the screen// windowAttribs = "width=" + width + "px," + "height=" + height + "px," + "left=\'+((screen.width -" + width + ") / 2)+\'," + "top=\'+ (screen.height - " + height + ")/ 2+\'"; //***Building the client script- window.open, with additional parameters***/// clientScript = "window.o…

How To Disable a button untill processing is complete

Here's the scenario - let's say you have an Insert subroutine, called 'doInsert'. You want to immediately disable the Submit button, so that the end-user won't click it multiple times, therefore, submitting the same data multiple times. For this, use a regular HTML button, including a Runat="server" and an 'OnServerClick' event designation - like this: < id="Button1" onclick="">=true;" type="button" value="Submit - Insert Data" name="Button1" runat="server" onserverclick="doInsert"> Then, in the very last line of the 'doInsert' subroutine, add this line: Button1.enabled="True"

How To Add Google Map to Your Web Application

Here is an example of how you can add a map to any contact us page or blog quickly and easily. •First you need a google api key ,which is free. You can find it,along with other documentation at http://www.google.com/apis Follow the instructions to "Sign up for a google API key". You'll need a gmail account, and to enter your domain name. This key can then only be used on pages served from that domain name. Along with your key, Google will give you a bit of starter code. Now create a new web application in vs.net and copy the highlited code in head section of your .aspx page.(replace [YOURKEY] with actual key) <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GoogleMap.aspx.cs" Inherits="GoogleMap" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><head><ti…

How To Export Datatable To CSV Format in ASP.NET

Create a new Web Application in VS.NET Add a button control to the page . write down following code in the click event of the button protectedvoid Button1_Click(object sender, EventArgs e) {string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();SqlConnection conn = new SqlConnection(strConn);SqlDataAdapter da = new SqlDataAdapter("select * from tablename ", conn);DataSet ds = new DataSet();da.Fill(ds, "tbl");GridView1.DataSource = ds.Tables["tbl"].DefaultView;GridView1.DataBind();DataTable dt = ds.Tables["Emp"];CreateCSVFile(dt, "c:\\csvData.csv");}publicvoid CreateCSVFile(DataTable dt, string strFilePath) { // Create the CSV file to which grid data will be exported. StreamWriter sw = new StreamWriter(strFilePath, false); // First we will write the headers.int iColCount = dt.Columns.Count; for (int i = 0; i < iColCount; i++) { sw.Wri…

How To Send Email Through Gmail In ASP.NET

Create a web application in VS.NETAdd a button control on the PageImport namespace System.MailWrite down following code in the click event of the buttonprotectedvoid SendMail() { //Create Mail Message Object with content that you want to send with mail. MailMessage MyMailMessage = new MailMessage ("test@gmail.com", "myfriend@domain.com", "This is the mail subject", "Just wanted to say Hello"); MyMailMessage.IsBodyHtml = false; //Proper Authentication Details need to be passed when sending email from gmail NetworkCredential mailAuthentication = new NetworkCredential("test@gmail.com", "myPassword"); //Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587//For different server this details changes and you can//get it from respective server. SmtpClient mailClient = new SmtpClient("smtp.g…

How To See The Path Of The Parsed class generated by ASP.NET

Add Debug="true" to your @Page directive. Place <%= GetType().Assembly.Location %>somewhere on your page This will print the location of the assembly generated for your page. If you go to that directory, you will also see source code files (*.cs or *.vb) that contain the class definitions

How to Register User Controls and Custom Controls in Web.config

In previous versions of ASP.NET developers imported and used both custom server controls and user controls on a page by adding <%@ Register %> directives to the top of pages like so: <%@ Register TagPrefix="scott" TagName="header" Src="Controls/Header.ascx" %> <%@ Register TagPrefix="scott" TagName="footer" Src="Controls/Footer.ascx" %> <%@ Register TagPrefix="ControlVendor" Assembly="ControlVendor" %> <html> <body> <form id="form1" runat="server"> <scott:header ID="MyHeader" runat="server" /> </form> </body> </html> Note that the first two register directives above are for user-controls (implemented in .ascx files), while the last is for a custom control compiled into an assembly .dll file. Once registered developers could then declare these controls anywhere on the page using the tagprefix and tagn…

How To Get HTML from a URL

You need to get the HTML returned from a web server in order to examine it for items of interest. For example, you could examine the returned HTML for links to other pages or for headlines from a news site. using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace ConsoleApplication1 { class Program { staticvoid Main(string[] args) { Console.WriteLine(GetHtmlFromUrl("http://www.google.com")); Console.Read(); } publicstaticstring HostName2IP(string hostname) { // Resolve the hostname into an iphost entry using the Dns class. IPHostEntry iphost = System.Net.Dns.GetHostEntry(hostname); // Get all of the possible IP addresses for this hostname. IPAddress[] addresses = iphost.AddressList; // Make a text representation of the list. StringBuilder addressList = new StringBuilder(); // Get each IP addres…

How To Convert a Hostname to an IP Address

You have a string representation of a host (such as www.google.com ), and you need to obtain the IP address from this hostname. using System; using System.Collections.Generic; using System.Text; using System.Net; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine(HostName2IP("www.google.com")); Console.Read(); } public static string HostName2IP(string hostname) { // Resolve the hostname into an iphost entry using the Dns class. IPHostEntry iphost = System.Net.Dns.GetHostEntry(hostname); // Get all of the possible IP addresses for this hostname. IPAddress[] addresses = iphost.AddressList; // Make a text representation of the list. StringBuilder addressList = new StringBuilder(); // Get each IP address. foreach (IPAddress address in addresses) { // Append it to the l…

How To Convert an IP Address To Hostname

You have an IP address that you need to resolve into a hostname. Use the Dns.GetHostEntry method to get the hostname for an IP address. In the following code, an IP address is resolved, and the hostname is accessible from the HostName property of the IPHostEntry: using System; using System.Net; //… // Use the Dns class to resolve the address. IPHostEntry iphost = Dns.GetHostEntry("127.0.0.1"); // HostName property holds the hostname. string hostName = iphost.HostName; // Print out name. Console.WriteLine(hostName);

How To Get Information for All Drives on a System

Your application needs to know if a drive (HDD, CD drive, DVD drive, etc.) is available and ready to be written to and/or read from. Additionally, it would be nice to know if you have enough available free space on the drive to write information to. Use the various properties in the DriveInfo class as shown here: public static void DisplayAllDriveInfo() { foreach (DriveInfo drive in DriveInfo.GetDrives()) { if (drive.IsReady) { Console.WriteLine("Drive " + drive.Name + " is ready."); Console.WriteLine("AvailableFreeSpace: " + drive.AvailableFreeSpace); Console.WriteLine("DriveFormat: " + drive.DriveFormat); Console.WriteLine("DriveType: " + drive.DriveType); Console.WriteLine("Name: " + drive.Name); Console.WriteLine("RootDirectory.FullName: " + drive.RootDirectory.FullName); Console.WriteLine("To…

How To Compare Version Information of Two Executable Modules

You need to programmatically compare the version information of two executable modules. An executable module is a file that contains executable code such as an .exe or .dll file. The ability to compare the version information of two executable modules can be very useful to an application in situations such as:Trying to determine if it has all of the "right" pieces present to executeDeciding on an assembly to dynamically load through reflectionLooking for the newest version of a file or .dll from many files spread out in the local filesystem or on a networkUse the CompareFileVersions method to compare executable module version information. This method accepts two filenames, including their paths, as parameters. The version information of each module is retrieved and compared. This file returns a FileComparison enumeration, defined as follows: public enum FileComparison { Same = 0, Newer = 1, // File1 is newer than File2 Older = 2, // File1 is older than File2 Err…