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...........

How to Increasing website performance and decrease Loading Time

Every time I entered into a new project, I am always thinking of about the speed how www.google.co.in loads,but in vain and unable to achieve it. The reason is that they had a dedicated server and the content in their page is very less. So even if it we cannot achieve that one with using a space for domain by the Domain provider but we can minimize it.So the Questions arises as:
  1. How to improve website performance ?
  2. How to speed up website ?
  3. How to compress webpages
  4. What are the methods to improve page loading speed
  5. How to optimize webpages
  6. How to make my site to process request faster.
  7. How can I achieve Rich Look Interface and so on.

To the above 1st 5 questions you need to follow some guide lines and to last two questions you need to make some thing of your coding better and  and have good and glossy look design and for other see below.

First of all minimize your CSS,JS,image files, try to avoid the re-size of images and then put the code below in your project. You will find a change in speed and performance of your site. Go to your Global.asax file and add the Code below or create a new Global.asax file( if not there ) and add the code to it.See below how to create the Global.asax file.

How to create Global.asax
Adding a Global.asax to your web project is quiet simple.
Open Visual Studio 2005 or 2008 or 2010 or 2011 beta> Create a new website > Go to the Solution Explorer > Add New Item > Global Application Class > Add.


Add the code below to Global.asax file:
 void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
     //Create an application variable
        HttpApplication app = sender as HttpApplication;
     //<span class="IL_AD" id="IL_AD3">check</span> for null referance
        if (app == null || app.Context == null || app.Context.CurrentHandler == null)
            return;
        string acceptEncoding = app.Request.Headers["Accept-Encoding"];
        Stream prevUncompressedStream = app.Response.Filter;
     //check whether the application is eligible for compression
     if (!(app.Context.CurrentHandler is Page || app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
            app.Request["HTTP_X_MICROSOFTAJAX"] != null)
            return;
        if (acceptEncoding == null || acceptEncoding.Length == 0)
            return;
        acceptEncoding = acceptEncoding.ToLower();
        // if the application accept defalte encoding, encode it with deflate, which is the lighter one
        if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
        {
            // defalte
            app.Response.Filter = new DeflateStream(prevUncompressedStream,
                CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding", "deflate");
        }
            //endoe with gzip
        else if (acceptEncoding.Contains("gzip"))
        {
            // gzip
            app.Response.Filter = new GZipStream(prevUncompressedStream,
                CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding", "gzip");
        }
    }

Monday, 16 April 2012

How you can fix It's an error to use a section registered as allowDefinition='MachineToApplication' beyond application level

Few Days Ago I got a strange error while I am Uploading my files to the FTP. The error was " Cannot allowDefinition='MachineToApplication' beyond application level " in the web.config file.

After doing R & D for more than an hour I came to know that there are two config files in the FTP and it causing this error.

However there might be some more reasons for the above error to come. Some of are as follows:

1)   If you Have Not configured your asp.net application in IIS:

          If you have not Configure your application to run on IIS First Configure your Site to Run on IIS.For that Create Virtual Directory From IIS and Give Permission to Application (Read,Write)

 2. If Above is Not Problem Then There are Mainly Problem of Two or many Web.Config Exists on your Site.When you Open Some Site and if Software Create Backup of that Application then Software mainly Do Create Subfolder and Copy All Files + Web.Config in Application. Just Remove this Subfolder web.config from Subfolder.  OR See that there are two web.config files of similar nature residing on the in the application.

Note: If you are having a demo folder and in that you are having another web.config file with different nature to that of the  web.config file then it will work fine and will not throw any MachineToApplication error. However if the 2 web config files of same type are there in the root and in the demo folder then it will throw the above error.

Just relax and make your app working. if found any issues just ask me........Happy to code.


 

Thursday, 5 April 2012

How to empty all TextBoxes of the page at one shot?


using System;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web;
public class MyClass

{

public static void ResetTextBoxes(Control oControl)
{
     foreach (Control c in oControl.Controls)
     {
        if (c is TextBox)
        {
             TextBox t = (TextBox)c.FindControl(c.ID);
             t.Text = string.Empty;
        }
          if (c.HasControls())
          {
             ResetTextBoxes(c);
          }
        }
    }//ResetTextBoxes
}
Call the above function as: MyClass.ResetTextBoxes(this);

ReSetting Form Fields using javascript/Jquery


function ClearAll(){
for (i=0;forms[0].length; i++)
{
doc = document.forms[0].elements[i];
switch (doc.type)
{
case "text" :
doc.value = "";
break;
case "checkbox" :
doc.checked = false;
break;
case "radio" :
doc.checked = false;
break;
case "select-one" :
doc.options[doc.selectedIndex].selected = false;
break;
case "select-multiple" :
while (doc.selectedIndex != -1)
{
indx = doc.selectedIndex;
doc.options[indx].selected = false;
}
doc.selected = false;
break;
default :
break;
}
}
}
}

Azure Complete Tutorials

Is it possible to make a radio button a required field? or Adding a required field to radio button


 yes, see the example below.

<asp:RadioButtonList runat="server" ID="radio">

                <%--Creaint Items to be display in Radio Button List--%>

                <asp:ListItem Value="0">Male</asp:ListItem>

                <asp:ListItem Value="1">Female</asp:ListItem>

            </asp:RadioButtonList>

            <%--Creating RequiredFieldValidator control to validate RadioButtonList that we have created--%>

            <asp:RequiredFieldValidator runat="server" ID="radRfv" ControlToValidate="radio"  errormessage="Select One option"></asp:RequiredFieldValidator>



Either you can use initialvalue property required filed validator. which is like  

 <asp:RequiredFieldValidator runat="server" ID="radRfv" ControlToValidate="radio"  initialvalue="0" errormessage="Select one option"></asp:RequiredFieldValidator>

For radio buttons:

Radio Buttons do not support the Required Field Validator. You can
either have a button selected by default or employ javascript. Here's a
simple example that forces a user to select either a Male or Female radio
button. There are plenty of variations of this on the Internet if you do a
little digging:

if ( ( document.myForm.gender[0].checked == false ) && (
document.myForm.gender[1].checked == false ) )
{
alert ( "Please select either Male or Female" );
valid = false;
}

How to get all the Table Names and the Rowcount for each Table of a specified DataBase


Some times it is necessary to get all the table names and its row count of each table of a particular Database in SQL server 2008/2008 R2

 SELECT  [TableName] = so.name,  [RowCount] = MAX(si.rows)  FROM sysobjects AS so,
sysindexes AS si WHERE  so.xtype = 'U'  AND  si.id = OBJECT_ID(so.name)  GROUP BY
so.name ORDER BY  1 ASC

C# Generate Random String of a Specific Length

Today I came across a need of generating random string as a registration numbers in C# while  taking the participant information and generating a registration number of unique one. So to do it here is the code below.

public String generateRandomString(int length) {
    //Initiate objects & vars 
byte[ ] seed = Guid.NewGuid().ToByteArray();
Random random = new Random(BitConverter.ToInt32(seed,0));

    String randomString = "";
    int randNumber;

    //Loop ‘length’ times to generate a random number or character
    for (int i = 0; i < length; i++)            {
        if (random.Next(1, 3) == 1)  // here it is for taking 3 alphabets and all other numeric
             randNumber = random.Next(97, 123); //char {a-z}
        else
             randNumber = random.Next(48, 58); //int {0-9}

        //append random char or digit to random string
        randomString = randomString + (char)randNumber;
    }
    //return the random string
    return randomString;
}