Showing posts with label Tips. Show all posts
Showing posts with label Tips. Show all posts

Random Password Generator with optional combination of Lower, Upper, Special and Numeric characters

This is been quite some time since I have shared some useful stuff with community. As you all know priorities always keep changing. So here is another simple utility class to generate random password.

You can define the minimum numbers of characters in your password string as well. This can be very useful if you have strict requirements for password security. As many password policy restrict user to set a password with sufficient complexity so that no one can brute force it easily.

This class uses double randomization algorithm to ensure that passwords don't get repeated. First it randomly picks the characters into a buffer. Once done, it does random swapping of all elements on buffer to ensure randomness of password.
Here is how you can utilize this code:-
/*
    * Author: Zeeshan Muar
    * Version: 1.0
    * This program is free software: you can redistribute it and/or modify
    * it under the terms of the GNU General Public License as published by
    * the Free Software Foundation, either version 3 of the License, or
    * (at your option) any later version.
    * 
    * This program is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    * GNU General Public License for more details.
    * 
    * You should have received a copy of the GNU General Public License
    * along with this program.  If not, see .
*/
public sealed class PasswordEngine
{
    private static PasswordEngine engine = new PasswordEngine();
 
    public static PasswordEngine Default
    {
        get
        {
            return engine;
        }
    }
        
    private readonly Random rnd = new Random();
    private string[] allowedCharacters = new string[]
    {
        "abcdefghijklmnopqrstuvwxyz",
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        "1234567890",
        "!@#$%^&*()_"
    };
 
    public string Generate(int size)
    {
        return Generate(size, 0, 0, 0);
    }
 
    public string Generate(int size,  int minCapitalLetters, int minNumbers, int minSpecial)
    {
        //Parameter validation
        if (minCapitalLetters + minNumbers + minSpecial > size)
        {
            throw new Exception("Parameter size should be less than or equal to minCapitalLetters + minSmallLetters + minNumbers + minSpecial");
        }
 
 
        //Buffer for 
        char[] buffer = new char[size];
 
        int currentIndex = 0;
        //Fill Capital Letters
        currentIndex = FillBuffer(currentIndex, minCapitalLetters, 1, buffer);
        //Fill Numbers Characters
        currentIndex = FillBuffer(currentIndex, minNumbers, 2, buffer);
        //Fill Special Characters
        currentIndex = FillBuffer(currentIndex, minSpecial, 3, buffer);
 
        //Fill remaining buffer with small characters
        int minSmallLetters= size - (minCapitalLetters  + minNumbers + minSpecial);
        currentIndex = FillBuffer(currentIndex, minSmallLetters, 0, buffer);
 
        RandomizeBuffer(size, buffer);
 
        return new string(buffer);
    }
 
    private void RandomizeBuffer(int size, char[] buffer)
    {
        for (int i = 0; i < size; i++)
        {
            char source = buffer[i];
            int swapIndex = rnd.Next(size);
            buffer[i] = buffer[swapIndex];
            buffer[swapIndex] = source;
        }
    }
 
    private int FillBuffer(int startIndex, int count, int row, char[] buffer)
    {
        for (int i = 0; i < count; i++)
        {
            rnd.Next(3);
            int col = rnd.Next(allowedCharacters[row].Length);
 
            buffer[i+startIndex] = allowedCharacters[row][col];
        }
 
        return startIndex + count;
    }
}

Here is how you can call this class to generate random passwords:-
//This will generate a simple password
string password1 = PasswordEngine.Default.Generate(10);
 
//This will generate a password with 2 numbers, 2 special and 2 capital letters
string password2 = PasswordEngine.Default.Generate(10, 2, 2, 2);

Feel free to discuss, Happy Coding !!!

Get List of Process with Process Owner/User

Recently I have come to a situation where I want to list all the process in the computer. Solution was quite simple using Process.GetProcess().

Process[] processlist = Process.GetProcesses();
 
foreach (Process theprocess in processlist)
{
 Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}


However I also want to see that process is created with which user. For this after some googling, I found this solution. Hopefully it will be useful for you happy coding !!!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Management;
using System.Runtime.InteropServices;
 
namespace ProcessViewer
{
 class Program
 {
  static void Main(string[] args)
  {
   GetProcessInfo();
  }
 
  /// Gets the process info.
  static void GetProcessInfo()
  {
   foreach (var process in Process.GetProcesses())
   {
    string name = process.ProcessName;
    int processId = process.Id;
    string windowTitle = process.MainWindowTitle ?? "N/A";
 
    Console.Out.WriteLine(string.Format("{0,20}|{1,10}|{2,20}|{3,20}",
     name,
     processId,
     GetProcessOwner(processId),
     windowTitle));
   }
   Console.ReadKey();
  }
 
  /// Gets the process owner.
  static string GetProcessOwner(int processId)
  {
   string query = "Select * From Win32_Process Where ProcessID = " + processId;
   ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(query);
   ManagementObjectCollection moCollection = moSearcher.Get();
 
   foreach (ManagementObject mo in moCollection)
   {
    string[] args = new string[] { string.Empty };
    int returnVal = Convert.ToInt32(mo.InvokeMethod("GetOwner", args));
    if (returnVal == 0)
     return args[0];
   }
 
   return "N/A";
  }
 }
}

Automatically redirect user when session timout

You can create a BasePae class which inherits System.Web.UI.Page. Override the OnInit method and write appropriate code in that which will redirect to default page.
public class BasePage : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        if (Session["UserName"] == null)
        {
            Response.Redirect("~/Login.aspx");
        }
    }
}

And inherit all your ASPX pages from BasePage class, instead of System.Web.UI.Page like this:-
public partial class HomePage : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

And finally in your login page, simply set Session["UserName"] with user's name. Feel free to share your comments. Happy Coding !!!

$(document).ready(), pageLoad() and Sys.Application.add_init()

When I have basic understanding of AJAX and jQuery, I thought that $(document).ready(), pageLoad() and Sys.Application.add_init() are equivalent and they does the same job. In most of the samples they seems to behave in same way and I wondered that why there are too many ways to do the same thing. So I did bit research on this and I am sharing that with the developer community.

jQuery's $(document).ready()
This function is called when DOM is ready. Generally if browser supports DOMContentLoaded event, $(document).ready() will fire after this event. If browser do not support DOMContentLoaded, then when document achieve readyState, then $(document).ready() will be fired. If above two events are not available in Brower's event model then window.onload event is used to fire $(document).ready() event.

If you are using jQuery, then my No. 1 recommendation is this function as this will work on
all browsers. Here is a sample how you can use this function:-
$(document).ready(function () {
//Your code here
});

Application.Init
This event is fired only once when page is loaded first time. Remember, that if you are using update panel then this method will not be called whenever update panel refresh your page. So, this is best event when you want initialization which should be done only once and not after every update panel refresh.
<script type="text/javascript">
    Sys.Application.add_init(function () {
        // Your code here
    }); 
script>

ASP.NET AJAX's pageLoad() Method
As we all know java scripts runs as a single thread, pageLoad method uses a trick, it calls a setTimeout() function of JavaScript with 0. So, whenever DOM is ready and JavaScript execution is started, you  pageLoad() will be triggered.

Now, use this method when you want to call your code every time when your update panel gets refresh.
<script type="text/javascript">
    function pageLoad() {
        // Your code here 
    } 
script>
 
Note that to use AJAX methods you need to place ScriptManager object on  your page other wise they won't work.

Feel free to comment, Happy Coding !!!

Unable to find the requested .Net Framework Data Provider. It may not be installed

Hi guys, I was on my holidays and enjoying something different so I was away for some time. However right now I am back and working on a Sliver light project. In that project I found an interesting situation which I would like to share with you. I was using Enterprise Library 5.0 for my connection string and I was using Oracle.DataAccess for my connection.

Here was the line on which I was getting error:-
dbase = DatabaseFactory.CreateDatabase("MyDB");


After spending some time I checked that every thing seems OK and there is no issue with my web.config file. I tried to replace CreateDatabase and use another way to create database connection in Enterprise Library:-
DbProviderFactory providerFactory =
DbProviderFactories.GetFactory("Oracle.DataAccess.Client");
dbase = new Microsoft.Practices.EnterpriseLibrary.Data
.GenericDatabase("data source=xxx;User id=xxx;Password=xxx;",providerFactory);

Above also did not solved my problem and I started to get another error :-

I checked that either I have installed ODP or not but It was installed in my GAC folder (usually at C:\Windows\assembly). Here is how my GAC folder looks like:-

Now finally I had a clue that what happened. My system have multiple versions of Oracle.DataAccess installed and .net can not decide that which version should be used. So, to Resolve this I have to add a DbProviderFactory in my web.config file. So here is how I added it:-
 <system.data>
    <DbProviderFactories>
    <add name="Oracle Data Provider for .NET"
            invariant="Oracle.DataAccess.Client"
            description="Oracle Data Provider for .NET"
            type="Oracle.DataAccess.Client.OracleClientFactory,
                  Oracle.DataAccess,
                  Version=2.112.1.2,
                  Culture=neutral,
                  PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>

Now last thing, I know that I have to use Oracle.DataAccess but how did I get other information i.e. Version, Culture and PublicKeyToken. To do this simply right click on the Assembly and take it properties. Here is the page that will appear through which you can get all the details:-

Finally my application started working and it connected to database perfectly. Hopefully this will also be useful for you . Do share your comments with me. Happy coding !!!



Improve ASP.Net Performance by effective utilitzation of String

Many people ask me that how they can improve their website's performance? There are many ways through which you can improve the performance of your website but today, I will discuss the performance improvement with Strings.
In my opinion String is the most frequently used data type compared to other data types available. But there is a big problem with string, it is immutable. An immutable object is an object which cannot be modified. So whenever we try to change anything with string a new string object is created. These frequent creations of objects degrade the system's policy.

Avoid using "" as empty string

Every time when you write "" a new string object is created. But if you use string.Empty it will not create any additional string before assignment.
//bad practice
string str = "";

//good practice
string str1 = string.Empty;

Avoid .ToLower()/.ToUpper() for Comparison

Usually developers heavily use .ToLower() or .ToUpper() to perform case insensitive comparison. Instead you should use string.Compare function.
//Bad Practice
string errorCode= "ec-1001";
if (errorCode.ToLower() == "ec-1001")
{

}

//good Practice
string errorCode1 = "ec-1001";
if (string.Compare( errorCode1,"ec-1001",true)==0)
{
}

Also there are situations when we can control the case of a string i.e. generally we add 'M' or 'F' for gender. Now we can ensure that throughout application we either use capital 'M' or small 'm' to define male. A good approach is to use const in such cases.
const string Male = "M";
const string Female = "F";
string myGender = Male;

Avoid multiple string concatenation

Whenever you have to modify a string many times then consider using StringBuilder instead of simple string. Every time when you modify a string, a new object would be created. However, StringBuilder is mutable object and it performs string modifications without creating multiple objects.

//Bad practice
string text = "start";
text += "start 1";
text += "start 2";
text += "start 3";
text += "start 4";
text += "start 5";

for (int i = 0; i < 10; i++)
{
    text += "text " + i;
}

//Good Practice
StringBuilder sb = new StringBuilder();
sb.Append("start");
sb.Append("start 2");
sb.Append("start 3");
sb.Append("start 4");
sb.Append("start 5");

for (int j = 0; j < 10; j++)
{
    sb.Append( "text " + j);
}

How to print contents of Div only

Generally we do not want to create complex report and our clients are not interested in purchasing expensive reporting tools then we can generate simple HTML based reports for them. You just have to place your report inside a< div>... < / div> and you can easily print that. Here is a sample through which you can easily print contents of specified div only:-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <script language="javascript" type="text/javascript">
        function printDiv(divID) {
            //Get the HTML of div
            var divElements = document.getElementById(divID).innerHTML; 
            //Get the HTML of whole page
            var oldPage = document.body.innerHTML;
            
            //Reset the page's HTML with div's HTML only
            document.body.innerHTML = "<html><head><title></title></head><body>" + divElements + "</body>";
            
            //Print Page
            window.print();
            
            //Restore orignal HTML
            document.body.innerHTML = oldPage;
            
            //disable postback on print button
            return false;
        }
    </script>
    <title>Div Printing Test Application by Zeeshan Umar</title>
</head>
<body>
    <form runat="server">
    <asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="return printDiv('div_print');" />
    <div id="garbage1">I am not going to be print</div>
    <div id="div_print"><h1 style="color: Red">Only Zeeshan Umar loves Asp.Net will be printed :D</h1></div>
    <div id="garbage2">I am not going to be print</div>
    </form>
</body>


Here is the output of the page when I run the code:-



And when I pressed print button, it hide all the remaining area and only my div's contents are visible which will be printed:-


Feel free to comment if you require any clarification. Happy coding !!!

How to get the week number of date

Recently I faced a problem in my project that I have 52 images and I have to display images based on the week of year. So as a solution I created images with image name like image1.jpg,image2.jpg and so on. And created a small function which returns the week of year. Here is the code through which I calculated the week of year after searching it on net for a while:-

/// <summary>

/// Gets the week number.

/// </summary>

/// <param name="dtDate">The date for which week number is required.</param>

/// <returns></returns>

public static int GetWeekNumber(DateTime dtDate)

{

    CultureInfo culture = CultureInfo.CurrentCulture;

    int weekNumber= culture.Calendar.GetWeekOfYear(dtDate, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);

    return weekNumber;

}


After this function I placed a server side Image control on my aspx page like this:-
<asp:Image ID="imgForWeek" runat="server" />

And here is how I called my function to display image for week in my code behind file:-

protected void Page_Load(object sender, EventArgs e)

{

    if (!IsPostBack)

    {

        imgForWeek.ImageUrl = "../Images/image" + GetWeekNumber(DateTime.Now)+".jpg";

    }

}


Hopefully this will be useful for you as well. Happy Coding !!!

How to prevent cache issue with Images, CSS and Java scripts, a better aproach

Generally when we update images, CSS or java script (.js) files on server, browser still shows old files. This is because in first request, browser download all images, CSS and .js files. But on subsequent requests, browser load images, CSS and .js files from its cache. Here is the solution which you might found on most of blogs i.e. add a DateTime.Now.Ticks as parameter after file name like this:-
<img src='PTCL-3.jpg?websiteversion=<%=DateTime.Now.Ticks.ToString()%>' alt="Sample Image" />

This will solve your problem and you will always get updated images. But the problem with this approach is that your images, CSS and java script will be downloaded for every request which will slowdown your site's performance.

Now, here is how you can solve both the problems, Add a key in appSettings section of your wen.config file like this:-
<appSettings>
    <add key="WebsiteVersion" value="1"/>
</appSettings>

And add the parameter to your images, CSS and java script files like this:-
<img src='PTCL-3.jpg?websiteversion=<%=System.Configuration.ConfigurationSettings.AppSettings["WebsiteVersion"] %>' alt="Sample Image" />

Now whenever you change any Image, CSS or .js file you have to update the WebsiteVerion value in your web.config file.

Do share your comments, happy coding !!!

How to restart your web application

Generally we all use cache to improve our website's performance. Caching is really useful when we are frequently displaying data which rarely requires changes. But, sometime client request an immediate change in cache entries and we have no option to manually run IISReset or change the contents of web.config file to clear all the cache.

In below code, I am sharing different approaches which can help you:-

namespace Utilities.General

{

    public static class Utility

    {

        public static bool RestartAppPool()

        {

            //First try killing your worker process

            try

            {

                //Get the current process

                Process process = Process.GetCurrentProcess();

                // Kill the current process

                process.Kill();

                // if your application have no rights issue then it will restart your app pool

                return true;

            }

            catch (Exception ex)

            {

                //if exception occoured then log exception

                Logger.Log("Restart Request Failed. Exception details :-" + ex);

            }

 

            //Try unloading appdomain

            try

            {

                //note that UnloadAppDomain requires full trust

                HttpRuntime.UnloadAppDomain();

                return true;

            }

            catch (Exception ex)

            {

                //if exception occoured then log exception

                Logger.Log("Restart Request Failed. Exception details :-" + ex);

            }

 

            //Finally automating the dirtiest way to restart your application pool

 

            //get the path of web.config

            string webConfigPath= HttpContext.Current.Request.PhysicalApplicationPath + "\\web.config";

            try

            {

                //Change the last modified time and it will restart pool

                File.SetLastWriteTimeUtc(webConfigPath, DateTime.UtcNow);

                return true;

            }

            catch (Exception ex)

            {

                //if exception occoured then log exception

                Logger.Log("Restart Request Failed. Exception details :-" + ex);

            }

 

            //Still no hope, you have to do something else.

            return false;

        }

    }

}


To implement above case you can create a dummy page i.e. RestartApplication.aspx or add a querystring parameter to your existing page like Home.aspx?RestartPool=true. Feel free to share your thoughts with me. Happy Codding !!!

How do disable back button in browser

Generally there are cases when we want to disable back button in browser. We have multiple options to disable back button in browser. Here are the few:-

Java Script Way
We can use following java script to prevent back button:-
<script type = "text/javascript" >
function disableBackButton()
{ 
window.history.forward();
}
setTimeout("disableBackButton()", 0);
window.onunload=function()
{
null
};
</script>

HTML Way
We can also add Meta Tags in Head Section like this:-
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />

If you want to do above approach through code. Here is the trick:-

HtmlMeta pragma = new HtmlMeta();

pragma.HttpEquiv = "Pragma";

pragma.Content = "no-cache";

Page.Header.Controls.Add(pragma);

 

HtmlMeta expires = new HtmlMeta();

expires.HttpEquiv = "Expires";

expires.Content = "-1";

Page.Header.Controls.Add(expires);


ASP.Net Way
In ASP.Net we can use Cache to disable back button like this:-

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));

Response.Cache.SetNoStore();

Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

A potentially dangerous Request.Form value was detected from the client


Above error comes because by default ASP.Net blocks the possible Script Injection request. e.g. if user type <script>alert('yes');</script> in your text box and when you display the text in text box, this java script will be executed instead of displaying text.

To resolve this problem you need to keep few things in mind:-

1- We can remove HTML Tags from TextBoxes with a simple regular expression filter like this:-
<asp:textbox id="txtSecureTextBox" runat="server" onblur="this.value = this.value.replace(/&lt;\/?[^>]+>/gi, '');">

2- Add ValidateRequest="false" in your Page directive line incase you want to disable this on single page.
<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false"/>

3- Incase you want to disable validation through out the site then you can do it in your web.config file like this:-
<configuration>  
  <system.web>  
    <pages validateRequest="false" />  
  </system.web> 
</configuration>

4- Use HTMLEncode whenever you are displaying unsafe contents in labels like this:-
Label1.Text = Server.HtmlEncode(TextBox1.Text) 

For further details see Request Validation - Preventing Script Attacks.

Different Server Side Tags

There are multiple types of server tags and most of the time I wonder what does they mean and in which situation what tag should I use. I Search out the internet and found something which I like to share.

There are six types of the server side tags:-
  1. <% %> This is an inline server side code block which is executed during Render. Generally we call methods inside our page code behind file through this. For Details see this.
  2. <%= %> This is the replacement for Response.Write to a specific place. Most of the time we use it to display single pieces of information. For Details see this.
  3. <%# %> We use during the data binding. For Details see this.
  4. <%$ %> This is used for ASP.NET Expression. Generally I use it to extract resources from resource files. For Details see this.
  5. <%@ %> This is use for Directive Syntax. For Details see this.
  6. <%-- --%> Server-Side Comments generally we use this to comment server side controls. For Details see this.

How to send periodic/timely Emails

I was busy during last few months and can not spare time for my blog. However during my project i came up with a situation that I have to send emails on daily basis through system. I would like to share the different approaches which I found during my goggling.

I came across three options to accomplish this:-

1- Create a simple .exe file which sends the mails and add it in windows scheduled tasks.
How To Schedule Task in Windows XP

2- Create a Window Service, which sleeps for 24 hours after sending emails.
Simple Windows Service Sample

3- Create a JOB in Sql Server. For details see:
Automated Email Notifications using SQL Server Job Scheduler

Visual Studio 2008 Tips and Tricks

Tip # 1: Track Active Item 
When using Visual Studio Often it is difficult to figure out which file is being edited specially when working with Solution having many projects and many files. I found a simple way to easily keep track of this.

All you need to do is to enable Tools->Options->Projects & Solutions->Track Active Item In Solution Explorer.


 When you enable this feature current open file is automatically selected in your solution explorer.

Tip # 2: Speed up ASPX page loading by opening it in Source View
Often when I double click on aspx or asxc file, it takes some time to create its design view and often I just have to adjust its markup little bit. We can set Tools->Options->HTML Designer->Source View.

This will always open ASPX files in source view.

Tip # 3: Speed up IDE by Turning off Animations
Visual Studio 2008 comes with many animations such as when you Take mouse over Tool Box or Solution Explorer it comes in an animated way. But if your PC is slow then you can turn it off to get some speed. You can do it by unchecking Tools->Options->Environment->Animate environment tools.


These are the few useful tips for Visual Studio 2008. Please share with me if you know some other tips as well.

How to Test System Generated Emails without Internet in Vista

Recenetly I have to develop a system which generates highly formatted emails. And I decided that I will do that in my home instead of office. After spending some time I figure out a way to do this. I configured IIS server in Windows Vista to save emails in my local drive. and I can see those emails from my outlook express. Here are the details that how to configure IIS:-
1- Run IIS from Start->run->inetmgr
2- Select your PC name from connections pane. and Right Click on SMTP E-Mail in middle pane.

3- In Features screen select Store e-mail in a pickup directory.

4- I have entered D:\Mails in the path.
5- Now goto D:\Mails (or what ever folder you mentioend).
6- When your application sends mail , mails will be saved in that folder with .eml extension. You can view those files with outlook.

7- If still not getting emails in your folder then try to add this line in your code before sending email:-

smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;

How to Auto Refresh / Re Load Page

Sometimes we need a page which shows real time date e.g. Stock exchange, cricket match, etc. To add auto refresh / re load you need to add the following meta tag in your markup's head section.
<meta http-equiv="refresh" content="600">

If you want to add this from code behing, then you can add it like this:-
protected void Page_Load(object sender, EventArgs e)
{
HtmlMeta hmRefresh = new HtmlMeta();
hmRefresh.HttpEquiv = "Refresh";
hmRefresh.Content = "10";//Time in seconds
Page.Header.Controls.Add(hmRefresh);
}

System.UnauthorizedAccessException: Access to the path 'C:\inetpub\wwwroot\...' is denied


This exception is a very common exception. It usually occurs when we move our application to IIS server (usually on production environment).

This exception occurs because IIS uses ASP .Net (IIS_IUser in Vista) user account and ASP .Net is not authorized to access that location.

To give a quick fix to this, follow these steps:-

  1. Give read/write rights to ASP.NET user to C:\Inetpub\yourfolder\ folder:-
    1. Right Click on FOlder and Select Properties
    2. Go to Security Tab
    3. Click Add, then click Location.
    4. Select your pc name, usually first item.
    5. Press Ok, then press advance and then Find Now.
    6. Select ASP.NET user if not exist then select Authenticated Users.
    7. Press Ok. And Select Read/Write/Modify/List Folder Contents.
  2. Go to IIS->WebSites->DefaultWebSite->YourSiteName->Properties, and at Virtual Directory Tab check 'Read' and 'Write' button.

How to Enable Internet Explorer Advance Tab in Vista


Recently my system got crashed and IT guys installed windows Vista on it, by default they have disabled Advance Tab in Tools-> Internet Options. And I was unable to debug Javascript through my Visual Studio.

After searching the net for a while i found a registry key which opens that option:-


Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Internet Explorer\Control Panel]
"AdvancedTab"=dword:00000000


Save this code as IE.reg and double click on it. After that I was able to view Advance Tab in IE and enabled javascript debugging in IE.

Just for refrence I am adding the path to enable javascript debugging in IE.

Tools-> Internet Options -> Advance -> Check Disable Script debugging (Internet Explorer)

Tools-> Internet Options -> Advance -> Check Disable Script debugging (Others)

How To Get The IP Address of Users using ASP .Net


If you want to track or analyze who is accessing your website, you can easily do this by capture the IP address of an incoming connection to your aspx page.
Here is the Code to access user's IP Address

Label1.Text = Request.ServerVariables["REMOTE_ADDR"];