Monday 12 November 2012

Preventing the backbutton not to go to the previous URL when the control is in focus inside a textbox, textarea or radio button in any browser


While developing a website in Asp.net MVC4, I noticed that when my control is in focus inside a text-box or text-area, which are read only, it is moving to the parent of the current URL. In order to solve it i had written a JQuery below which will prevent the back to the parent URL in any browser and in any web developing programming languages.


    $(document).keydown(function(e) {
        var doPrevent;
        if (e.keyCode == 8) {
            var d = e.srcElement || e.target;
            if (d.tagName.toUpperCase() == 'INPUT' || d.tagName.toUpperCase() == 'TEXTAREA') {
                doPrevent = d.readOnly || d.disabled;
            }
            else
                doPrevent = true;
        }
        else
            doPrevent = false;

        if (doPrevent)
            e.preventDefault();
    });



Enjoy!..........

Monday 5 November 2012

Issue with the sorting the telerik grid for Asp.net MVC

While working on telerik grid , I found a peculiar issue in Internet Explorer(IE) browsers. The issue is that on the column bound HeaderTemplate if you are providing a link for sorting purpose and if you used a label inside the link then the link will not work in IE but will work for all other browsers.


Solution: So, while providing the link text for sorting the grid on that column, just be care full that u must not used any label for that link. See below:

The code below will  not work:
column.Bound(m => m.Name).Template(
        @<text>
    <a target="_blank" href="@item.Url">@item.Name</a>
    </text>) .HeaderTemplate(
        @<text><a href="javascript:void(0)" class="t-link"> <label>Name<label> </a>  ---> This will not work
    </text>);



The code below will work:
 column.Bound(m => m.Name).Template(
        @<text>
    <a target="_blank" href="@item.Url">@item.Name</a>
    </text>) .HeaderTemplate(
        @<text><a href="javascript:void(0)" class="t-link"> Name </a>  ---> This will work.
    </text>);



Enjoy!.......

Friday 2 November 2012

In MVC4 Telerik grid I got an error that telerik.textbox.js not found in the 'Script\telerik.textbox.js'

This is the tricky one, there is no problem in any where but it is throwing the problem because you might have passed some integer value to the column bound in the telerik grid in mvc3/mvc4.

There are two ways to fix it:

Method 1:

  Download the telerik.textbox.js and put in the specified location and it will work fine.

Note: Don't go for this method, since you are adding some more bytes to the  size of the Cod.

 Method 2:

 Just while binding the int value to the grid just convert it into a string. That's all, now your code will work fine



Enjoy!...

Friday 26 October 2012

After getting the Ajax result from the Action Method the the view is not updating in mvc3/mvc4

One of my friend while doing a task of a project , he implemented the Ajax call to send request to the  action method. he had done it and resend the model to the client side, but the data is not updating in the view.

So, I thought of a while and scrutinized it and found that the model is updated when the data comes from the action method but it is not updating the view. so, here is the trick how to do it.

$.ajax({
                data: { retailLocation: $("#ddlLanguages").val().split('-')[1] + "-" + this.value },
                url: '/App/index',
                success: function (result) {
                    $("#container").empty().html(result);
                    $('#container').fadeIn('fast');


                },
                complete: function (result) {
                    $("#RetailPartnerLocation option:contains(" + currentselection + ")").attr('selected', 'selected');
                },
                Error: function (result) { alter("Error occured while processing"); }
            });


Here you need to empty the container where the previous data exist and bind the new data to it.

How to Show the date like facebooks shows when you provide comments such as 1 min ago, 2 days ago, 1 Month Ago in Asp.Net/ Asp.Net MVC 2/MVC 3/ MVC 4

While working on a project , I need to show the comments published or updated as 1 min ago, 1 Hours ago, so on. So in order to do it I had written a helper class to do it for me.

Here is the code below:
 public static string GetFormattedDate(string date)
        {
            string formattedDate = string.Empty;
            TimeSpan ts = System.DateTime.Now - DateTime.Parse(date);
            int weeks = (int)(DateTime.Now - DateTime.Parse(date)).TotalDays / 7;

            if (ts.Minutes == 0)
                formattedDate = "Few Seconds Ago";
            if (ts.Minutes > 0 && ts.Minutes < 59)
                formattedDate = ts.Minutes + (ts.Minutes == 1 ? " Minute Ago" : " Minutes Ago");
            if (ts.Hours > 0 && ts.Hours < 24)
                formattedDate = ts.Hours + (ts.Hours == 1 ? " Hour ago" : " Hours ago");
            if (ts.Days >= 1 && ts.Days<30)
            {
                if (ts.Days == 1)
                {
                    formattedDate = "Today";
                }
                else if (ts.Days>1 && ts.Days < 7)
                {
                    formattedDate = ts.Days + (ts.Days == 1 ? " Day ago" : " Days ago");
                }
                else
                {
                    formattedDate = (ts.Days / 7).ToString() + ((ts.Days / 7).ToString() == "1" ? " Week Ago" : " Weeks Ago");
                }
            }
            else if (ts.Days >= 30 && ts.Days<365)
            {
                formattedDate = ts.Days/30 + ( ts.Days<60 ? " Month ago" : " Months ago");
            }
            else if(ts.Days>=365)
            {
                formattedDate = ts.Days / 365 + ( ts.Days < 730 ? " Year ago" : " Years ago");
            }
          
            return formattedDate;
        }

How to Write a Extension method to strip html-tags from a rich text Editor in ASP.Net/ MVC

Today while working with CKEditor , I find out that what ever I provide in the Editor body and saved, it is not properly translating the html tags such as paragraph in the Editor body.

So to fix it I had written an extension method to strip the HTML tags as :


        public static string StripHtml(string inputString)
        {
            if (!string.IsNullOrEmpty(inputString))
                return Regex.Replace(inputString, "<.*?>", string.Empty);

            return string.Empty;

        }


How to call: Classname.StripHtml("some string");

How to Minimize Long Title or Overflowed text with less text followed with ellipsis using Jquery or CSS


While working on a project I got a requirement  of showing a limited amount of text followed with ellipsis(...)  in  a telerik grid, to do it I thought I will use the CSS property  text-overflow: ellipsis; but unable to succeed. I thought a lot and at last done it with CSS.

What I had done with CSS:
So in order to get the text as "Hello Hai how Are..." I used the following CSS

#divContainer td:first-child + td {height: 45px;width:280px;max-width: 280px;overflow: hidden;
text-overflow: ellipsis; display:block;white-space: nowrap;}

Here divContainer is the Container and td:first-child + td  : refers to the second column of a table. InOrder to make it work you need to specify the width,max-width(for IE), white-space and Overflow:hidden and text-overflow: ellipsis;

The output is:
 


 *Note: Here We get the desired result with single line only but I need multiple line with  ellipsis, so to do it I followed JQuery.


What I had done with JQuery:

In order to fix this issue I just write below the two line to get multiple lines followed with ellipsis(...)

$("#divContainer td:first-child + td").each(function() {
            $(this).text($(this).text().substr(0,75)+"...");
        });


The Output is:

Monday 6 August 2012

Creating your own Folder Locker in Windows Operating systems.

Wow..today I came to know how to write my own folder protector and safe guard my files with out using any software. I started my career in IT as a Software Instructor for teaching people as Computer fundamentals, DOS, MS-Office etc.

At that time I knew that DOS is Powerful and has the capacity to do many low level works but not had the idea that it can create a utility file for me when I am searching for a software to protect it from the guys who stoles the data.

here is the Bat file content.

MyFolderLocker.bat

cls
@ECHO OFF
title Folder Technade
if EXIST "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" goto UNLOCK
if NOT EXIST Technade goto MDLOCKER
:CONFIRM
echo Are you sure u want to Lock the folder(Y/N)
set/p "cho=>"
if %cho%==Y goto LOCK
if %cho%==y goto LOCK
if %cho%==n goto END
if %cho%==N goto END
echo Invalid choice.
goto CONFIRM
:LOCK
ren Sudarsan "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
attrib +h +s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
echo Folder locked
goto End
:UNLOCK
echo Enter password to Unlock folder
set/p "pass=>"
if NOT %pass% = = sudarsan123$ HERE goto FAIL
attrib -h -s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
ren "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" Sudarsan
echo Folder Unlocked successfully
goto End
:FAIL
echo Invalid password
goto end
:MDLOCKER
md Sudarsan
echo Sudarsan created successfully
goto End
:End

Here the password is sudarsan123$, you can change the password as per your wish.

Lets go for a test:

Copy the bat file which you had created from the above content, now take it to the place where you want to hide the files.

Here create a folder name Sudarsan and store your files you want to protect . Now run the batch file by double clicking it.

For unlocking again , run the file it will ask for password and here i had used  sudarsan123$, once you provide the password correctly it will unlock the folder.


Happy Coding......

How to protect your data to be taken through usb in Windows 7 or Win XP

I came to notice few days back that some one is using my system and I found data loss as windows system are prone to data theft easily. so, followed a technique to stop it with out using any software.

There are three ways are there,

1. Make you Registry to protect in such a way that it should not write data into the USB drives

2. Use a .bat file that protect your files and folder with a password.

3. Use a folder locker/ PC Locker for this purpose.

Write Protect to the USB Drives:

Go to the Start menu --> Run---> type Regedit,
You will get the Windows Registry Editor.

Now search for the Following key:
    HKEY_LOCAL_MACHINE\System\ControlSet001\Control\StorageDevicePolicies

if the "StorageDevicePolicies" key is not found you can create a new one in HKEY_LOCAL_MACHINE\System\ControlSet001\Control


Now set the Key value to 1 in order to protect it from writing data to the USB Devices.

If you you want to copy data from you computer to usb devices it will not allow.

In order to write the data again to the USB devices you can chane this value to 0 again.



for Windows Xp Machines follow the above same procedure but you the registry key is:
HKEY_LOCAL_MACHINE\System\ControlSet001\Control\StorageDevicePolicies


Note: Just back up the registry before changing any thing so that if u do any thing wrong or the system goes unstable it can be restored.

Happy coding...

Friday 20 July 2012

How to Show a Pop-Up Message Window in Asp.net (Like the Message Window in Windows Forms)

You all might aware of that in win forms you might have used Message.Show("Some Text")  to show some information. However in Asp.net forms you might have used Alert( ) or used a Literal or Label to Show some Message when you want to show some thing to the user like  1)  Your Resume has been updated Successfully. or 2) User Created Successfully or 3) A mail has been sent to your Mail ID and so on. In above all case the best one is to be go for a Literal or a Label and show the message there. How ever you want to show a message like alert using Literal, then go for the code below:


public static void ShowMessage(Page page,string message)
{
     Literal literalMessage=new Literal( );
     literalMessage.Text="<script>alert('" + message + " ')</script>";
     page.Controls.Add(literalMessage);
}

How we can use the above code :-

Just think that we want some message on a button click event,then we can use it as:

protected void btnSave_Click(Object sender, EventArgs e)
{
    ShowMessage(this, "Data updated Successfully!");
}

Enjoy it...........


Thursday 24 May 2012

Why int is 16-bit in 16-bit compilers but even if long, float are 32 bits?

This is because of processor size. As the default data type is int so, if this matches then it optimizes the operations. another important thing is that int depends on OS, Processor, etc. so it is 16-bit in 16 bit compiler.

IEnumerable.Count() is a bad style of Coding, Why?

IEnumerable<Participant> participants=GetParticipants();

if(products.count()==0)
{
       SomeControls.Visible=false;
}
else
{
     SomeControls.Visible=true;
}
The wrong thing with the above code is that Count() is a Linq extension Method that literally iterates through every item in an  enumerable( here it is participants). In other words it won't short circuit after it finds more than zero items and will continue iterating through every single item. And while, that one may be fast operation in Dev environment but it will be a slow process in production. This is because of Linq's deferred Execution.

How we can refine the above Code

The above Code can be refined by changing it into as:
IEnumerable<Participant> participants=GetParticipants();

if(products.Any())
{
       SomeControls.Visible=false;
}
else
{
     SomeControls.Visible=true;
}

In the above code once the expression finds more than one item, it simply stops iterating and just increasing the Optimization time.

Happy Coding.........!

Thursday 17 May 2012

Function to find GCD using Euclidean Algorithm

int GCD(int a, int b)
{
     while (a != 0 && b != 0)
     {
         if (a > b)
            a %= b;
         else
            b %= a;
     }

     if (a == 0)
         return b;
     else
         return a;
}

Using "Bitflags" in C

Bitflags are a method of storing multiple values, which are not mutucally exclusive, in one variable. You've probably seen them before. Each flag is a bit position which can be set on or off. You then have a bunch of bitmasks #defined for each bit position so you can easily manipulate it:
 
#define LOG_ERRORS            1  // 2^0, bit 0
#define LOG_WARNINGS          2  // 2^1, bit 1
#define LOG_NOTICES           4  // 2^2, bit 2
#define LOG_INCOMING          8  // 2^3, bit 3
#define LOG_OUTGOING         16  // 2^4, bit 4
#define LOG_LOOPBACK         32  // and so on...

// Only 6 flags/bits used, so a char is fine
unsigned char flags;

// initialising the flags
// note that assignming a value will clobber any other flags, so you
// should generally only use the = operator when initialising vars.
flags = LOG_ERRORS;
// sets to 1 i.e. bit 0

//initialising to multiple values with OR (|)
flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING;
// sets to 1 + 2 + 8 i.e. bits 0, 1 and 3

// setting one flag on, leaving the rest untouched
// OR bitmask with the current value
flags |= LOG_INCOMING;

// testing for a flag
// AND with the bitmask before testing with ==
if ((flags & LOG_WARNINGS) == LOG_WARNINGS)
   ...

// testing for multiple flags
// as above, OR the bitmasks
if ((flags & (LOG_INCOMING | LOG_OUTGOING))
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

// removing a flag, leaving the rest untouched
// AND with the inverse (NOT) of the bitmask
flags &= ~LOG_OUTGOING;

// toggling a flag, leaving the rest untouched
flags ^= LOG_LOOPBACK;

 
WARNING: DO NOT use the equality operator (i.e. bitflags == bitmask) for testing if a flag is set - that expression will only be true if that flag is set and al others are unset. To test for a single flag
 
if (flags == LOG_WARNINGS) //DON'T DO THIS
   ...
 

Using Enumerations in C and C++

Whenever you need to define a set of mutually exclusive states, always use an enumeration. Don't use an int and a bunch of #defines. If space is really a premium and you only need a few things, you could settle for a char and a few letters as a code. If you need to represent some states that aren't mutually exclusive, use bitflags (see the next section).
An enumeration is basically an integer type associated with a bunch of special tokens. These tokens can be used for assignment and is-equal or not-equal checks - you can think of them as a sort of special #define.
 
//declare the enumeration _type_
enum BirdState {FLYING, LANDING, STANDING, TAKEOFF, EATING, SLEEPING};

//create a variable of it (in c or c++)
enum BirdState bs1 = SLEEPING;
//create a variable of it (in c++ only)
BirdState bs2 = SLEEPING;

//compare state
if (bs1 == EATING)
   bird1.hungry--;

//set and compare state
if (bs1 == TAKEOFF && bird1.velocity > 0.3)
   bs1 = FLYING;
 
There are some differences between enums in C and C++. First, in C++ you do not need the enum keyword when declaring a variable. Second, in C++ you cannot use general integer operators (such as arithmetic and bitwise operators) on enumerations
 
enum BirdState bs2;  // legal in C and C++
BirdState bs3;       // legal in C++ only

typedef enum BirdState BirdState_t
BirdState_t bs4;     // can use typedef like this
                     // to make it legal in C as well

bs2++;               // Illegal in C++
bs3 = 2;             // Illegal in C++
bs4 = bs2 | bs3;     // Illegal in C++
 

Polymorphic Structures in C

This can be achieved with a little creative union and struct work. The basic idea is to have a structure representing a superclass, which contains a union of all the other subclasses.
You will need another entity (preferably an enumeration) in the superclass and all subclasses to determine what type of struct it is.
Example:

typedef struct{
   int type;
   float ypos;
   float xpos;
   float length;
   float height;
} Shape_Triangle

typedef struct{
   int type;
   float ypos;
   float xpos;
   float length;
} Shape_Square

typedef struct{
   int type;
   float ypos;
   float xpos;
   float radius;
} Shape_Circle

typedef union{
  int type;
  Shape_Square square;
  Shape_Triangle triangle;
  Shape_Circle circle;
} Shape;

...

Shape s = getShape();
switch(s.type)
{
   case SHAPE_SQUARE:
      s.Shape_Square.length=3;
      break;
   case SHAPE_TRIANGLE:
      s.Shape_Triangle.height=4;
      break;
   case SHAPE_CIRCLE:
      s.Shape_Circle.radius=5;
      break;
}

A drawback of this method is that you need to duplicate the members in the substructure, and you must make sure the type variables are all in the same physical position (first is best) in the struct/union. Alternatively, use a struct for the superclass and subclass:

typedef struct{
   float length;
   float height;
} Shape_Triangle

typedef struct{
   float length;
} Shape_Square

typedef struct{
   float radius;
} Shape_Circle

typedef union{
  Shape_Square square;
  Shape_Triangle triangle;
  Shape_Circle circle;
} Shape_Union;

typedef struct{
   int type;
   float xpos;
   float ypos;
   Shape_Union subshape;
}

...

Shape s = getShape();
switch(s.type)
{
   case SHAPE_SQUARE:
      s.subshape.Shape_Square.length=3;
      break;
   case SHAPE_TRIANGLE:
      s.subshape.Shape_Triangle.height=4;
      break;
   case SHAPE_CIRCLE:
      s.subshape.Shape_Circle.radius=5;
      break;
}


This requires extra typing "through" the union.

Bit Masks in C

Bit masks are where you specify the number of bits to use in a integral member of a class or struct. C has more restrictions than C++ on this. In particular, only "int", "signed int" or "unsigned int" can have bit masks in C. Many C compilers ignore bit masks altogether.
First rule of bit masks: Don't. Don't unless you have a really bad need to save a tiny amount of memory, and slowing down your code a lot isn't a problem (the compiler will have to work around things as they are not properly aligned). Bit masks are also inherently non-portable and differ on different compilers on different machines. Some compilers will ignore them totally.
If you really want to go ahead with it, all you do is put a colon after the member followed by the number of bits it should occupy. Here's an example:

struct TwelveHourTime
{
   unsigned hour     : 4;     //4 bits (16), enough for 1-12
   unsigned minute   : 6;     //6 bits (64), enough for 0-59
   unsigned am       : 1;     //1 bit, on for am off for pm
};

//   0 1 2 3 4 5 6 7 8 9 A
//  |_ _ _ _|_ _ _ _ _ _|_|
//    hour     minute    am 

You can use bit masks with a blank identifier to add some padding:

struct TwelveHourTime
{
   unsigned hour     : 4;     //4 bits (16), enough for 1-12
   unsigned minute   : 6;     //6 bits (64), enough for 0-59
   unsigned          : 5;     //5 unused bits
   unsigned am       : 1;     //1 bit, on for am off for pm
};

//   0 1 2 3 4 5 6 7 8 9 A B C D E F
//  |_ _ _ _|_ _ _ _ _ _|_ _ _ _ _|_|
//    hour     minute    (unused)  am 

You can a blank identifier with bit mask of 0 to force the next element to align to the boundary of the given type:

struct TwelveHourTime
{
   unsigned hour     : 4;     //4 bits (16), enough for 1-12
   char              : 0;     //push minute to the next byte boundary
   unsigned minute   : 6;     //6 bits (64), enough for 0-59
   unsigned am       : 1;     //1 bit, on for am off for pm
};

//   0 1 2 3 4 5 6 7 8 9 A B C D E
//  |_ _ _ _|_ _ _ _|_ _ _ _ _ _|_|
//    hour  (unused)  minute     am

Again, bit masks are very non-portable and the exact layout depends on the compiler and platform. The diagrams are a guide only.

Wednesday 9 May 2012

Writing log files for Applications in C# with time stamp

 A sample code which creates a log file (one per day & instance) 
and puts in time-stamped log entries into it. The file names are such 
that sorting them in Windows File Explorer is very easy for the SysAdmin
 
 
using System.IO;
public void WriteLogLine(string sCallerName, string sLogFolder, 
                        long lCallerInstance, string sLogLine)
{
  lock(this)
  {
    string sFileName;
    sFileName = String.Format("{0}_{1:yyyy.MM.dd}_{2:00}.log", 
                  sCallerName, DateTime.Now, lCallerInstance);
    StreamWriter swServerLog = 
           new StreamWriter(sLogFolder + sFileName, true);
    swServerLog.WriteLine(
           String.Format("[{0:T}] {1}", DateTime.Now, sLogLine));
    swServerLog.Close();
  }
}

Title: Get the description of a Enum value.

Some times it is required to get the Enum description to be used inside your drop down control 
or list box control or some where else, here is a small program that will help you to do this.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Text;

namespace LinkedIn.Utility
{
  /// <summary>
  /// A helper class for enums.
  /// </summary>
  public static class EnumHelper
  {
    /// <typeparam name="TValue">usually int</typeparam>
    public static List<TValue> GetValues<TEnum, TValue>()
    {
      List<TValue> values = new List<TValue>();
      Array array = Enum.GetValues(typeof(TEnum));
      foreach (TValue item in array)
      {
        values.Add(item);
      }

      return values;
    }

    /// <summary>
    /// Get the description of a <see cref="Enum" /> value.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <returns>A description of the <see cref="Enum" /> value.</returns>
    public static string GetDescription(Enum value)
    {
      FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
      DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fieldInfo.GetCustomAttributes(
            typeof(DescriptionAttribute), false);

      return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
    }

    /// <summary>
    /// </summary>
    /// <typeparam name="TEnum"></typeparam>
    /// <param name="enumeratedType"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool HasFlag<TEnum>(this TEnum enumeratedType, TEnum value)
        where TEnum : struct, IComparable, IFormattable, IConvertible
    {
      if ((enumeratedType is Enum) == false)
      {
        throw new InvalidOperationException("Struct is not an Enum.");
      }

      if (typeof(TEnum).GetCustomAttributes(
          typeof(FlagsAttribute), false).Length == 0)
      {
        throw new InvalidOperationException("Enum must use [Flags].");
      }

      long enumValue = enumeratedType.ToInt64(CultureInfo.InvariantCulture);
      long flagValue = value.ToInt64(CultureInfo.InvariantCulture);

      if ((enumValue & flagValue) == flagValue)
      {
        return true;
      }

      return false;
    }
  }
}

Enjoy............!
   

Tuesday 24 April 2012

How to change the Image of a button or control on MouseOver as in Windows7


<script type="text/javascript">
        function OnMouseOver( ) {           
            document.getElementById("imgbtnSubmit").src = "btnActive.png";
        }
        function OnMouseOut( ) {
            document.getElementById("imgbtnSubmit").src = "btnInActive.png";
        }
    </script>

Method 1 :-
    Call the above JavaScript function on client MouseOver and MouseOut;

Method 2 :-
    Using styles in the CSS file,
 You can change the image on hover and on out of focus you can show the default Image.

for e.g. :
              <asp:ImageButton   ID="imgBtnSubmit"  ImageUrl="~/Image/btnInActive.png" CssClass="btnSubmit" runat="server"></asp:ImageButton>

In the CSS File:
      .btnSubmit:hover {backgroundImage:url("~/images/btnActive.png"); }

 Method 3 :-

In the page's Load event, call the Add method of the control's Attributes collection.

imgbtnSubmit.Attributes.Add("onmouseover","OnMouseOver( )");
imgbtnSubmit.Attributes.Add("onmouseout", "OnMouseOut( )");

Just enjoy..........that's all.

Monday 23 April 2012

max salary,second max salary etc from the Employee table in Ms-Sql-Server


Here there are diffrent methods are used to find the second Highest salary, max salary, min salary from the Employee table in MS-SQL Server.


use EmpDB;
select DISTINCT salary from Employee group by salary ;
// Show all the Distinct salaries


SELECT Min(Salary ) FROM [EmpDB].[dbo].[Employee]
WHERE Salary IN (SELECT DISTINCT TOP 2 Salary FROM [EmpDB].[dbo].[Employee] order BY Salary desc) //  for 2nd highest salary( i.e. Top 2 is used), you can change the number as per to get the desired one.


SELECT MAX(Salary)  FROM Employee WHERE Salary<(SELECT MAX(Salary) FROM Employee) // only for 2nd highest salary

select distinct a.salary from Employee a where 2=( select count(distinct b.salary) from Employee b where a.salary<=b.salary) //  for 2nd highest salary( i.e. where 2= is used), you can change the number(3,4,5..)   as per your need to get the desired one.

SELECT * FROM (SELECT salary, ROW_NUMBER() OVER (order by Employee.Salary DESC) AS RANK FROM Employee  group by salary) v where RANK = 8 ;


/*---Finding Max and min salary from Emp Table*/
SELECT  a.[firstName], a.Salary AS Salary
FROM Employee AS a
WHERE a.Salary IN (
SELECT MIN(b.Salary)
FROM Employee AS b)
UNION
SELECT  a.[firstName], a.Salary AS Salary
FROM Employee AS a
WHERE a.Salary IN (
SELECT MAX(b.Salary)
FROM Employee AS b)
ORDER BY a.Salary


/*Selecting all the 2nd max salary here 2 represents the 2nd higest salary
  Here u can able to sell all the records with second highest salary

  Table:

CREATE TABLE #T1 (ID1 INT, [Name] NVARCHAR(50), Salary INT)
INSERT INTO #T1 VALUES (1,'Vamshi', 1000)
INSERT INTO #T1 VALUES (2, 'xxxxx', 2000)
INSERT INTO #T1 VALUES (3, 'yyyyy', 3000)
INSERT INTO #T1 VALUES (4, 'zzzzz', 4000)
INSERT INTO #T1 VALUES (5, 'sssss', 5000)
INSERT INTO #T1 VALUES (6, 'ccccc', 6000)
INSERT INTO #T1 VALUES (7, 'ppppp', 2000)
INSERT INTO #T1 VALUES (8, 'aaaaa', 4000)
INSERT INTO #T1 VALUES (9, 'bbbbb', 5000)
INSERT INTO #T1 VALUES (10,'eeeee', 5000)


Select * from #t1 order by salary;
SELECT a.ID1, a.[Name], a.Salary
FROM #T1 AS a
WHERE (2) = (
SELECT COUNT(DISTINCT(b.Salary))
FROM #T1 AS b
WHERE b.Salary > a.Salary)

*/
/* Displaying all the records with max and min salary
select distinct * from Employee where salary in (select max(salary) from Employee
union
select min(salary) from Employee
);*/

/* finding all the 2nd higest Salary using Rank here 2 refers to the 2nd highest salary , here a means alias
Select *
from (Select *, DENSE_RANK() OVER (ORDER BY Salary DESC) AS Ranks from Employee) a
WHERE Ranks = 2 */


/*
first method:
select top 1 salary from (
select top 6 salary from employee group by salary order by salary desc) a order by salary
go

2nd method:
with nthsalary as
(
select salary,row_number() over(order by salary desc) as row from employee group by salary
)
select salary from nthsalary where row=6
GO
3RD method:
select distinct * from employee a where 6=(select count(distinct salary)
from employee b where a.salary<=b.salary)

*/

/*
create table EmpDept(
empno int identity(1,1),
empname varchar(50),
sal numeric(18,2),
dep varchar(20)
)
go
insert into EmpDept(empname, sal, dep)
select 'A_123',12000,'BANK'
Union
select 'A_234',5000,'BANK'
Union
select 'A_345',10000,'BANK'
Union
select 'A_456',25000,'BANK'
Union
select 'A_567',8000,'BANK'
Union
select 'B_123',25000,'PROG'
Union
select 'B_234',27000,'PROG'
Union
select 'B_345',23000,'PROG'
Union
select 'B_456',13000,'PROG'
Union
select 'B_567',50000,'PROG'
Union
select 'C_123',11000,'TEST'
Union
select 'C_234',9000,'TEST'
Union
select 'C_345',22000,'TEST'
Union
select 'C_456',30000,'TEST'
Union
select 'C_567',8000,'TEST'

Select * from EmpDept
Select * from EmpDept a where empno in (select top 3 empno from EmpDept where dep=a.dep order by sal desc)*/

What can a Global.asax file can do ?


Sometimes you need of writing logic at the application level; precisely a location or a file where you could handle events or errors at the application level? The answer is Global.asax file
The Global.asax, also known as the ASP.NET application file, is located in the root directory of an ASP.NET application. This file contains code that is executed in response to application-level and session-level events raised by ASP.NET or by HTTP modules. You can also define ‘objects’ with application-wide or session-wide scope in the Global.asax file. These events and objects declared in the Global.asax are applied to all resources in that web application.
Note 1: The Global.asax is an optional file. Use it only when there is a need for it.
Note 2: If a user requests the Global.asax file, the request is rejected. External users cannot view the file.
The Global.asax file is parsed and dynamically compiled by ASP.NET. You can deploy this file as an assembly in the \bin directory of an ASP.NET application.
How to create Global.asax
Adding a Global.asax to your web project is quiet simple.
Open Visual Studio 2005 or 2008 > Create a new website > Go to the Solution Explorer > Add New Item > Global Application Class > Add.
Examining the methods related to the events in Global.asax
There are 2 ‘set’ of methods that fire corresponding to the events. The first set which gets invoked on each request and the second set which does not get invoked on each request. Let us explore these methods.
Methods corresponding to events that fire on each request
Application_BeginRequest() – fired when a request for the web application comes in.
Application_AuthenticateRequest –fired just before the user credentials are authenticated. You can specify your own authentication logic over here.
Application_AuthorizeRequest() – fired on successful authentication of user’s credentials. You can use this method to give authorization rights to user.
Application_ResolveRequestCache() – fired on successful completion of an authorization request.
Application_AcquireRequestState() – fired just before the session state is retrieved for the current request.
Application_PreRequestHandlerExecute() - fired before the page framework begins before executing an event handler to handle the request.
Application_PostRequestHandlerExecute() – fired after HTTP handler has executed the request.
Application_ReleaseRequestState() – fired before current state data kept in the session collection is serialized.
Application_UpdateRequestCache() – fired before information is added to output cache of the page.
Application_EndRequest() – fired at the end of each request
Methods corresponding to events that do not fire on each request
Application_Start() – fired when the first resource is requested from the web server and the web application starts.
Session_Start() – fired when session starts on each new user requesting a page.
Application_Error() – fired when an error occurs.
Session_End() – fired when the session of a user ends.
Application_End() – fired when the web application ends.
Application_Disposed() - fired when the web application is destroyed.
Lets See some example!!
Let us see an example of how to use the Global.asax to catch unhandled errors that occur at the application level.
To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add New Item > Global.asax). In the Application_Error() method, add the following code:
 C#
 void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs
        Exception objErr = Server.GetLastError().GetBaseException();
        string err = "Error in: " + Request.Url.ToString() +
                          ". Error Message:" + objErr.Message.ToString();
       
    }
Think that you want to start an application @ a particular time
C# 
 void Application_BeginRequest(object sender, EventArgs e)
    {
        // Code that runs @ particular time.
     
    }
  Just go for it...........