Tuesday 31 January 2012

difference between i++ and ++i


i++ means 'tell me the value of i, then increment'
++i means 'increment i, then tell me the value'
For the prefix form:
  • x is evaluated to produce the variable
  • the value of the variable is copied to a temporary location
  • the temporary value is incremented to produce a new value (not overwriting the temporary!)
  • the new value is stored in the variable
  • the result of the operation is the new value
For the postfix form:
  • x is evaluated to produce the variable
  • the value of the variable is copied to a temporary location
  • the temporary value is incremented to produce a new value (not overwriting the temporary!)
  • the new value is stored in the variable
  • the result of the operation is the temporary copy

++i is definitiely as fast as i++ but it may be faster.
The reason is the implementation.
In order to implement i++ the implementation needs to generate a temporary copy of i unlike the implementation for ++i.
But smart compilers can optimize the genration of this temporary, they certainly do for POD types

Tuesday 24 January 2012

Import Excel To Sql in c# Dotnet

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.OleDb;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
      string strConnection = ConfigurationManager.ConnectionStrings
        ["MarinaNewConnectionString"].ConnectionString;
  
     
        protected void Page_Load(object sender, EventArgs e)
        {
             string excelConnectionString =
            @"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\UniqueMarinaData.xls;
Extended Properties=""Excel 4.0;HDR=YES;""";

            //Create Connection to Excel work book
            OleDbConnection excelConnection =
            new OleDbConnection(excelConnectionString);

            //Create OleDbCommand to fetch data from Excel
            OleDbCommand cmd = new OleDbCommand
            ("Select [WebSource],[MarinaName],[Address],[Region],[Country],[Fax],[Phone],[Email],[Website],[Latitude],[Longitude],[NumberOfMoorings],[MGiD] from [Sheet1$]",
            excelConnection);

            excelConnection.Open();
            OleDbDataReader dReader;
            dReader = cmd.ExecuteReader();

            SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
            sqlBulk.DestinationTableName = "Marina";
            //sqlBulk.ColumnMappings.Add("ID", "ID");
            //sqlBulk.ColumnMappings.Add("Name", "Name");
            sqlBulk.WriteToServer(dReader);
        }
      
}

What is Normalization

What is Normalization?

Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.
The Normal Forms

The database community has developed a series of guidelines for ensuring that databases are normalized. These are referred to as normal forms and are numbered from one (the lowest form of normalization, referred to as first normal form or 1NF) through five (fifth normal form or 5NF). In practical applications, you'll often see 1NF, 2NF, and 3NF along with the occasional 4NF. Fifth normal form is very rarely seen and won't be discussed in this article.

Before we begin our discussion of the normal forms, it's important to point out that they are guidelines and guidelines only. Occasionally, it becomes necessary to stray from them to meet practical business requirements. However, when variations take place, it's extremely important to evaluate any possible ramifications they could have on your system and account for possible inconsistencies. That said, let's explore the normal forms.

First Normal Form (1NF)

First normal form (1NF) sets the very basic rules for an organized database:
Eliminate duplicative columns from the same table.
Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).
For more details, read Putting your Database in First Normal Form

Second Normal Form (2NF)

Second normal form (2NF) further addresses the concept of removing duplicative data:
Meet all the requirements of the first normal form.
Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
Create relationships between these new tables and their predecessors through the use of foreign keys.
For more details, read Putting your Database in Second Normal Form

Third Normal Form (3NF)

Third normal form (3NF) goes one large step further:
Meet all the requirements of the second normal form.
Remove columns that are not dependent upon the primary key.
For more details, read Putting your Database in Third Normal Form

Boyce-Codd Normal Form (BCNF or 3.5NF)

The Boyce-Codd Normal Form, also referred to as the "third and half (3.5) normal form", adds one more requirement:
Meet all the requirements of the third normal form.
Every determinant must be a candidate key.
For more details, read Putting your Database in Boyce Codd Normal Form

Fourth Normal Form (4NF)

Finally, fourth normal form (4NF) has one additional requirement:
Meet all the requirements of the third normal form.
A relation is in 4NF if it has no multi-valued dependencies.
Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database.


Acid propert in sql server 2008

ACID (an acronymn for Atomicity Consistency Isolation Durability) is a concept that Database Professionals generally look for when evaluating databases and application architectures. For a reliable database all this four attributes should be achieved.

Atomicity is an all-or-none proposition.

Consistency guarantees that a transaction never leaves your database in a half-finished state.

Isolation keeps transactions separated from each other until they’re finished.

Durability guarantees that the database will keep track of pending changes in such a way that the server can recover from an abnormal termination.

Above four rules are very important for any developers dealing with databases.

Monday 23 January 2012

Dispose in C#

dispose() method releases the memory from the variable,
we define the dispose when the variable is in not use,
this variable can be reused again.
eg:
func()
{
sqlcommand cmd=new sqlcommand()
datareader dr;

cmd=new sqlcommand("select* from emp",con)
dr=cmd.executreader;
cmd.dispose();
dr.close();

cmd=new sqlcommand("select* from dept",con)
dr=cmd.executreader;
cmd.dispose();
dr.close();

cmd=new sqlcommand("select* from salgrade",con)
dr=cmd.executreader;
cmd.dispose();
dr.close();

}
cmd.executereader();
cmd.dispose();

difference between the having clause and the group by statement

 difference between the having clause and the group by statement?


In SQL, the having clause and the group by statement work together when using aggregate functions like SUM, AVG, MAX, etc. This is best illustrated by an example. Suppose we have a table called emp_bonus as shown below. Note that the table has multiple entries for employees A and B.
emp_bonus
Employee     Bonus
A     1000
B     2000
A     500
C     700
B     1250

If we want to calculate the total bonus that each employee received, then we would write a SQL statement like this:

select employee, sum(bonus) from emp_bonus group by employee;


The Group By Clause

In the SQL statement above, you can see that we use the "group by" clause with the employee column. The group by clause does allows us to find the sum of the bonuses for each employee. Using the ‘group by’ in combination with the ‘sum(bonus)’ statement will give us the sum of all the bonuses for employees A, B, and C.

Subscribe to our newsletter on the left to receive more free interview questions!

Running the SQL above would return this:
Employee     Sum(Bonus)
A     1500
B     3250
C     700

Now, suppose we wanted to find the employees who received more than $1,000 in bonuses for the year of 2007. This is when we need to use the HAVING clause, and this is what the SQL look like:

GOOD SQL:
select employee, sum(bonus) from emp_bonus
group by employee having sum(bonus) > 1000;

And the result of running the SQL above would be this:
Employee     Sum(Bonus)
A     1500
B     3250
Difference between having clause and group by statement

So, from the example, we can see that the group by clause is used to group column(s) so that aggregates (like SUM, MAX, etc) can be used to find the necessary information. The having clause is used with the group by clause when comparisons need to be made with those aggregate functions (like “> 1,000″). So, the having clause and group by statements are not really alternatives to each other – but they are used alongside one another!

Saturday 21 January 2012

Disadvantage of Ajax

  • Back functionality cannot work because the dynamic pages don’t register themselves to the browsers history engine. Hence the need of Iframe becomes essential.
  • The page cannot be bookmarked if implemented using Ajax.
  • If java script is disabled , Ajax will not work
  • Because different components of the pages are loaded at different times, response time may be slow.
  • Because different components of the pages are loaded at different times it may create confusion for the user.

Thursday 19 January 2012

SQL Injection

SQL Injection

In this article I will show you just one way that hackers can break in to your website, using a technique known as SQL Injection. And then I'll show you how to fix it. This article touches on some technical topics, but I'll try to keep things as simple as possible. There are a few very short code examples written in PHP and SQL. These are for the techies, but you don't have to fully understand the examples to be able to follow what is going on.

Please also note that the examples used are extremely simple, and Real Hackers™ will use many variations on the examples listed.

If your website doesn't use a database, you can relax a bit; this article doesn't apply to your site — although you might find it interesting anyway. If your site does use a database, and has an administrator login who has rights to update the site, or indeed any forms which can be used to submit content to the site — even a comment form — read on.

Warning

This article will show you how you can hack in to vulnerable websites, and to check your own website for one specific vulnerability. It's OK to play around with this on your own site (but be careful!) but do not be tempted to try it out on a site you do not own. If the site is properly managed, an attempt to log in using this or similar methods will be detected and you might find yourself facing charges under the Computer Misuse Act. Penalties under this act are severe, including heavy fines or even imprisonment.

What Is SQL Injection?

SQL stands for Structured Query Language, and it is the language used by most website databases. SQL Injection is a technique used by hackers to add their own SQL to your site's SQL to gain access to confidential information or to change or delete the data that keeps your website running. I'm going to talk about just one form of SQL Injection attack that allows a hacker to log in as an administrator - even if he doesn't know the password.

Is Your Site Vulnerable?

If your website has a login form for an administrator to log in, go to your site now, in the username field type the administrator user name.

In the password field, type or paste this:

x' or 'a' = 'a
If the website didn't let you log in using this string you can relax a bit; this article probably doesn't apply to you. However you might like to try this alternative:

x' or 1=1--
Or you could try pasting either or both of the above strings into both the login and password field. Or if you are familiar with SQL you could try a few other variations. A hacker who really wants to get access to your site will try many variations before he gives up.

If you were able to log in using any of these methods then get your web tech to read this article, and to read up all the other methods of SQL Injection. The hackers and "skript kiddies" know all this stuff; your web techs need to know it too.

The Technical Stuff

If you were able to log in, then the code which generates the SQL for the login looks something like this:

  $sql =
    "SELECT * FROM users
    "WHERE username = '" . $username .
    "' AND password = '" . $password . "'";
When you log in normally, let's say using userid admin and password secret, what happens is the admin is put in place of $username and secret is put in place of $password. The SQL that is generated then looks like this:

SELECT * FROM users WHERE username = 'admin' and PASSWORD = 'secret'
But when you enter x' or 'a' = 'a as the password, the SQL which is generated looks like this:

SELECT * FROM users WHERE username = 'admin' and PASSWORD = 'x' or 'a' = 'a'
Notice that the string: x' or 'a' = 'a has injected an extra phrase into the WHERE clause: or 'a' = 'a' . This means that the WHERE is always true, and so this query will return a row containing the user's details.

If there is only a single user defined in the database, then that user's details will always be returned and the system will allow you to log in. If you have multiple users, then one of those users will be returned at random. If you are lucky, it will be a user without administration rights (although it might be a user who has paid to access the site). Do you feel lucky?

How To Defend Against This Type Of Attack

Fixing this security hole isn't difficult. There are several ways to do it. If you are using MySQL, for example, the simplest method is to escape the username and password, using the mysql_escape_string() or mysql_real_escape_string() functions, e.g.:

$userid = mysql_real_escape_string($userid);
$password = mysql_real_escape_string($password);
$sql =
"SELECT * FROM users
"WHERE username = '" . $username .
"' AND password = '" . $password . "'";
Now when the SQL is built, it will come out as:

SELECT * FROM users WHERE username = 'admin' and PASSWORD =
'x\' or \'a\' = \'a'
Those backslashes ( \ ) make the database treat the quote as a normal character rather than as a delimiter, so the database no longer interprets the SQL as having an OR in the WHERE clause.

This is just a simplistic example. In practice you will do a bit more than this as there are many variations on this attack. For example, you might structure the SQL differently, fetch the user using the user name only and then check manually that the password matches or make sure you always use bind variables (the best defence against SQL Injection and strongly recommended!). And you should always escape all incoming data using the appropriate functions from whatever language your website is written in - not just data that is being used for login.

There's More

This has just been a brief overview. There are many more hacking techniques than SQL Injection; there are many more things that can be done just using SQL Injection. It is possible to directly change data, get access to confidential information, even delete your whole database — irrespective of whether the hacker can actually log in — if your website isn't set up correctly.

If you are hungry for more, this detailed article from SecuriTeam explains other techniques hackers might use, as well as some of the methods hackers use to work out the structure of your database, the userid of the admin user, gain access to your system's configuration, etc.

different types of directives in .NET

What are different types of directives in .NET?

@Page: Defines page-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %>

@Control: Defines control-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .ascx files. <%@ Control Language="VB" EnableViewState="false" %>

@Import: Explicitly imports a namespace into a page or user control. The Import directive cannot have more than one namespace attribute. To import multiple namespaces, use multiple @Import directives. <% @ Import Namespace="System.web" %>

@Implements: Indicates that the current page or user control implements the specified .NET framework interface.<%@ Implements Interface="System.Web.UI.IPostBackEventHandler" %>

@Register: Associates aliases with namespaces and class names for concise notation in custom server control syntax.<%@ Register Tagprefix="Acme" Tagname="AdRotator" Src="AdRotator.ascx" %>

@Assembly: Links an assembly to the current page during compilation, making all the assembly's classes and interfaces available for use on the page. <%@ Assembly Name="MyAssembly" %><%@ Assembly Src="MySource.vb" %>

@OutputCache: Declaratively controls the output caching policies of an ASP.NET page or a user control contained in a page<%@ OutputCache Duration="#ofseconds" Location="Any | Client | Downstream | Server | None" Shared="True | False" VaryByControl="controlname" VaryByCustom="browser | customstring" VaryByHeader="headers" VaryByParam="parametername" %>

@Reference: Declaratively indicates that another user control or page source file should be dynamically compiled and linked against the page in which this directive is declared.

get value from RadioButtonList control in java script


How to get value from RadioButtonList control?

Here id is the name property of the RadioButtonList

function GetRadioButtonValue(id)

        {

            var radio = document.getElementsByName(id);

            for (var ii = 0; ii < radio.length; ii++)

            {

                if (radio[ii].checked)

                    alert(radio[ii].value);

            }

        }

get value from dropdown (select) control in java script

How to get value from dropdown (select) control?


Write following code

alert(document.getElementById('dropdown1').value);

get value from a textbox in java script

How to get value from a textbox in java script?

Write following code

alert(document.getElementById('txtbox1').value);

ASP.NET Page Life Cycle

What is ASP.NET 2.0 Page Life Cycle?

Main Events
=============
1. OnPreInit
2. OnInit
3. OnInitComplete
4. LoadViewState
5. OnPreLoad
6. OnLoad
7. RaisePostBackEvent
8. OnLoadComplete
9. OnPreRender
10. OnPreRenderComplete
11. SaveViewState
12. OnRender
13. OnUnload

Detailed Events
============
1. Constructor
2. Construct
3. TestDeviceFilter
4. AddParsedSubObject
5. DeterminePostBackMode
6. OnPreInit
7. LoadPersonalizationData
8. InitializeThemes
9. OnInit
10. ApplyControlSkin
11. ApplyPersonalization
12. OnInitComplete
13. LoadPageStateFromPersistenceMedium
14. LoadControlState
15. LoadViewState
16. ProcessPostData1
17. OnPreLoad
18. OnLoad
19. ProcessPostData2
20. RaiseChangedEvents
21. RaisePostBackEvent
22. OnLoadComplete
23. OnPreRender
24. OnPreRenderComplete
25. SavePersonalizationData
26. SaveControlState
27. SaveViewState
28. SavePageStateToPersistenceMedium
29. Render
30. OnUnload




Role of IIS

What is the Role of IIS ?

Visual studio having It own ASP.NET Engine which is capable enough to run Asp.net web application from visual studio. So we just click on Run button to start the application.
Now this is the scenarios of local environment. But If we want to host it on server from where all user can access the sites then IIS comes into the picture.

IIS provides a redesigned WWW architecture that can help you achieve better performance, reliability, scalability, and security for our Web sites. IIS can support following Protocol HTTP/HTTPS, FTP, FTPS, SMTP Etc. We need to host the site on IIS, when request comes from client it first hits the IIS Server, then the server passed it to ASP.NET worker process to execute. Then the response also passes to client via IIS itself.
Note only Hosting of Site we can create our FTP Server, SMTP Server using IIS itself.
There are different version of IIS available like 5.1, 6.0, 7.0 etc

benefit of using LINQ on Dataset

What is the benefit of using LINQ on Dataset?


The main aim of using LINQ to Dataset is to run strongly typed queries on Dataset.

Suppose we want to combine the results from two Datasets, or we want to take a distinct value from the Dataset, then it is advisable to use LINQ.

Normally you can use the SQL queries to run on the database to populate the Dataset, but you are not able to use SQL query on a Dataset to retrieve a particular values. To get this you need to use ADO.NET functionalities. But, in case of LINQ, it provides more dignified way of querying the Dataset and provides some new features as compared to ADO.NET.

Lambda expression

What is a Lambda expression?


A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements. Lambda expressions can be used mostly to create delegates or expression tree types. Lambda expression uses lambda operator => and read as 'goes to' operator.

Left side of this operator specifies the input parameters and contains the expression or statement block at the right side.

Example: myExp = myExp/10;

Now, let see how we can assign the above to a delegate and create an expression tree:

delegate int myDel(int intMyNum);

        static void Main(string[] args)

        {

            //assign lambda expression to a delegate:

            myDel myDelegate = myExp => myExp / 10;

            int intRes = myDelegate(110);

            Console.WriteLine("Output {0}", intRes);

            Console.ReadLine();



            //Create an expression tree type

            //This needs System.Linq.Expressions

            Expression<myDel> myExpDel = myExp => myExp /10;

           

        }


No te:
The => operator has the same precedence as assignment (=) and is right-associative.

Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where.

difference between Linq and Stored procedure

How LINQ is beneficial than Stored Procedures?

There are couple of advantage of LINQ over stored procedures.

1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries.

2. Deployment - With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.

3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!

Dot net Solutions By Piush Shukla: Can we have try block without catch

Dot net Solutions By Piush Shukla: Can we have try block without catch: Can we have try block without catch? Yes. We can write Try { } Finally { } block. In this case exception will be thrown in try block if it...

Wednesday 18 January 2012

Scope of public/private/friend/protected/protected friend



Scope of public/private/friend/protected/protected friend.

Visual Basic/Visual C#
Public/public All members in all classes and projects.

Private/private Members of the current class only.

Friend/internal All members in the current project.

Protected/protected All members in the current class and in classes derived from this member?s class. Can be used only in member definitions, not for class or module definitions.

Protected Friend/protected internal All members in the current project and all members in classes derived from this member?s class. Can be used only in member definitions, not for class or module definitions. 

Create Html table in c# dynamically

Dynamically create a HTML table (C#)

File:

<%@ Page language="c#" Inherits="TablePictures" CodeFile="Default.aspx.cs" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Table Test</title>
</head>
<body>
  <form runat="server">
  <div>
    Rows:
    <asp:TextBox ID="txtRows" runat="server" />&nbsp;
    Cols:
    <asp:TextBox ID="txtCols" runat="server" />
    <br /><br />
    <asp:CheckBox ID="chkBorder" runat="server"
         Text="Put Border Around Cells" />
    <br /><br />
    <asp:Button ID="cmdCreate" OnClick="cmdCreate_Click" runat="server"
     Text="Create" />
    <br /><br />
    <asp:Table ID="tbl" runat="server" />
  </div>
  </form>
</body>
</html>



File: Default.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class TablePictures : System.Web.UI.Page
{
  protected void Page_Load(object sender, System.EventArgs e)
  {
    tbl.BorderStyle = BorderStyle.Inset;
    tbl.BorderWidth = Unit.Pixel(1);
  }

  protected void cmdCreate_Click(object sender, System.EventArgs e)
  {
    tbl.Controls.Clear();

    int rows = Int32.Parse(txtRows.Text);
    int cols = Int32.Parse(txtCols.Text);
   
    for (int i = 0; i < rows; i++)
    {
      TableRow rowNew = new TableRow();
      tbl.Controls.Add(rowNew);
      for (int j = 0; j < cols; j++)
      {
        TableCell cellNew = new TableCell();
        Label lblNew = new Label();
        lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";

        System.Web.UI.WebControls.Image imgNew = new System.Web.UI.WebControls.Image();
        imgNew.ImageUrl = "cellpic.png";

        cellNew.Controls.Add(lblNew);
        cellNew.Controls.Add(imgNew);

        if (chkBorder.Checked == true)
        {
          cellNew.BorderStyle = BorderStyle.Inset;
            cellNew.BorderWidth = Unit.Pixel(1);
          }

        rowNew.Controls.Add(cellNew);
      }
    }
  }
}

first text as a custom in dropdown in c#.net



I have dropdown list control in one of my application and when I add Items in it from database Its displaying the first Item into Dropdown list by default but I want to display someother text into this like "Select Item from the List" Is there any way I can do this .

 On the ASP.NET side of things, you can create the DropDownList with AppendDataBoundItems="true" and any items you bind to it will come after the default:

<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
    <asp:ListItem Text="Select something" Value="-1" />
</asp:DropDownList>

As for doing the same thing completely in Javascript, you can do it with a function like this:

function addFirstItem(list, text, value)
{
    var newOption = document.createElement("option");
    newOption.text = text;
    newOption.value = value;
    list.options.add(newOption);
}

addFirstItem(document.getElementById("yourListId"), "Select something", "-1");

Or with jQuery (there is probably something much cleaner, especially for creating a new option tag, but this works):

$("#yourListId option:first").before("<option value='-1'>Select something</option>"

Dot net Solutions By Piush Shukla: Dotnet Interview question for fresher

Dot net Solutions By Piush Shukla: Dotnet Interview question for fresher: What are session management techniques in .NET? There are three different techniques of managing session in ASP.NET InProc Session state ...

Tuesday 17 January 2012

Can we have try block without catch

Can we have try block without catch?

Yes.

We can write Try { } Finally { } block. In this case exception will be thrown in try block if it is but code inside finally block will execute.

Here any exception in CallFirstMethod() or CallSecondMethod() will be handled by MainMethod() and finally block will execute always to perform any cleanups for respective methods.

public void MainMethod()

{

try

{

CallFirstMethod();

CallSecondMethod();

}

Catch(Exception ex)

{

//handle exception

}

}

publiv void CallFirstMethod()

 {

try

{

//code

}

finally

{

//cleanups

}

}

publiv void CallSecondMethod()

{

try

{

//code

}

finally

{

//cleanups

}

}

difference between ASP.NET and VB.NET

What is the difference between ASP.NET and VB.NET?

ASP.Net is a program application with server controls with programmable objects, which can do the same job HTML did in the past. ASP.Net is used to build a Website and VB.Net is a computer language you use to build the site. Some use VB.Net and others use C# (C Sharp language) to build a website. Using ASP. Net and VB.Net or C# you can build an E-commerce store, which has multi functional capabilities. You can integrate PayPal or one of the other payment programs into your site. Create an Email system, speed up the applications by caching the pages and the data within the pages of your site and do a number of other things to successfully run an E- commerce store on the Internet.

ASP.Net is very successful Web application platform used by individuals and many large companies, who want to build and run their own websites. ASP.Net provides server controls with the ability to give you rich web content and more. Anyone willing to purchase the software and learn how to properly use this technology can use the tools, and application system to build a great Website. You can develop and build your own database choosing to use VB.net or C# language. Many websites today, which were built in the past used HTML language to build their websites.

Difference between Globalization and Localization

Difference between Globalization and Localization ?

Globalization refers to formatting data in formats relevant for the current culture setting.

example:
a)consider this tag in Web.Config file.
<globalization culture="fr-FR"/>
It would cause the dates to be displayed in French for the web page of
the folder where this Web.Config file is located.

b) CultureInfo d=new CultureInfo("de-DE");
Response.Write(DateTime.Now.ToString("D",d);
It would display date in long format using German culture


Localization refers to retrieving and displaying appropriately
localized data based on the culture.
It can be done by using the Resource files.

example:
we have 2 resource files:
a)default.aspx.fr-FR.resx
b)default.aspx.en-US.resx

Using appropriate coding in the .aspx.cs files of a web page, the strings written in these resource files can be used to change the text of the strings dynamically.

Difference between lock and Monitor.Enter()

Difference between lock and Monitor.Enter()


lock keyword basically provides a shortcut to Enter method of Monitor class.
Monitor is used to provide thread synchronization.It means till the Thread in which the method is being used finishes its task, no other thread can access the object.

example:

lock (object)
{

}

It is compiled into

Monitor.Enter(object);
try
{
//code
}
finally
{
Monitor.Exit(object);
}

See the MSIL of the assembly.

We can write much more code and perform customization in the try block.

What is Constructor Chaining?

What is Constructor Chaining?


We can chain the call of constructor from child class to base class depending on our requirement. This concept makes sure that the matching base class constructor must be called based on the parameter passed to the child class constructor.

Example:

namespace ConsoleApplication1

{

    class A

    {

        public A(){

            Console.WriteLine("Constructor A.");

        }

        public A(string s){

            Console.WriteLine("Constructor A with parameter = {0}",s);

        }

        public A(string s,string t){

            Console.WriteLine("Constructor A with parameter = {0} & {1}", s,t);

        }

    }



    class B:A

    {

        public B():base(){

            Console.WriteLine("Constructor B.");

        }

        public B(string s):base(s){

            Console.WriteLine("Constructor B with parameter = {0}", s);

        }

        public B(string s, string t):base(s,t){

            Console.WriteLine("Constructor B with parameter = {0} & {1}", s, t);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            B b1 = new B();

            B b2 = new B("First Parameter ", "Second Parameter");



            Console.Read();

        }

    }

}



Output:
Constructor A.
Constructor B.
Constructor A with parameter = First Parameter & Second Parameter
Constructor B with parameter = First Parameter & Second Parameter

Difference between event and delegate

Difference between event and delegate?

Event:

1) It is a data member of a type(class/structure)
2)It is declared inside a type(class/structure)
3) It is used to generate notifications which are then passed to methods though
delegates.

delegate:

1)It is a datatype(reference type) that holds references of methods with
some signatures.also called as function pointer.
2)It may or may not be declared inside a class.
3)It is used as the return type of an event and used in passing messages from event to methods.


event-->delegate-->method

example:

namespace dd
{
//delegate declaration
delegate void first();
class cc
{
//event declaration
public first myevent;
}
}

example 2:
button1.Click+=new EventHandler(this.button1_Click);
(Windows Applications)

Click is the event that returns an instance of the EventHandler delegate.
EventHandler delegate has the reference of button1_Click event and that
helps in the communication betwen the Click event and button1_Click method

Difference between a Class and Component

Difference between a Class and Component?


Class is a datatype that encloses data and function members.
It can be used for implementing the various OOPS features.

Component is a particular class that must implement the IComponent interface .It is the base class for all components in the common language runtime that marshal by reference. Component is remotable and derives from the MarshalByRefObject class.
IComponent interface belongs to System.ComponentModel namespace.

So, we can say Component is subclassification of a class

Difference between imperative and interrogative code

Difference between imperative and interrogative code.

Imperative code does not return a value. It just does performs an action.

example:

c#
void demo()
{
Console.WriteLine("welcme");

}

vb.net
sub procedures are imperative code.
sub dd()

end sub

Interrogative code does return a value.

c#
ex: int add(int a)
{
return a*5;
}

VB.NET FUNCTIONS
ex
function calc(byval a as integer) as integer
return a*5
end function

Can abstract class have constructors

Can abstract class have constructors?


Yes, an abstract class does have a constructor.
It will be called when it subclass is instantiated.

example:

abstract class bank

    {

        public bank()

        {

            Console.WriteLine("bank");

        }

       

    }

    class icici : bank

    {

        icici()

        {

            Console.WriteLine("icici");

        }

        static void Main()

        {

            bank b = new icici();



        }

    }



//Output:

when the object of icici class is created,
They will be displayed in the output.
bank
icici

difference between .NET 1.1,2.0,3.0,3.5 and 4.0

What is the difference between .NET 1.1,2.0,3.0,3.5 and 4.0 ?

The list of differences are huge. In interviews you normally need to short and sweet. So we will list down top 5 differences from each section.

So lets first start with the difference between 1.0 and 2.0.

Support for 64 bit application.
Generics
SQL cache dependency
Master pages
Membership and roles

Now the next difference .NET 2.0 and 3.0
=========================================

WCF
WPF
WWF
WCS ( card space)

3.0 and 3.5
==========================================
LINQ
Ajax inbuilt
ADO Entity framework
ADO data services
Multi targeting

Finally 3.5 and 4.0
===========================================
MEF
Parallel computing
DLR dynamic
Code contract
language runtime
Lazy initialization

Differences between Window and Web Forms

Differences between Window and Web Forms

Window Forms:

1)They do not need a web browser or web server to execute.
2)They execute through their respective exe files
3)They run on the same machine they are displayed on.
4)Their single instance exists until we close them or dispose them through coding
5)Used for developing games, inventory management, system utiltites etc.
6)They run under Code Access Security.


Web Forms:

1)They need a web browser as well as a web server(on the server machine only).
2)They execute through the dll of the web application which is then processed by IIS and the .net framework.
3)They run on a remote server and are displayed remotely on the clients.
4)Every time they are submitted, their new instance is created.
5)Used in web site development.
6)They use role based security

difference between casting and boxing

What is the difference between casting and boxing?


casting is the technique using which we convert data of one
type to data of another type.
It is like a main category of boxing.

boxing is a sub category of casting which deals with
converting a value type to a reference type.

example:
1) double d=245.66;
//casting: conversion between 2 value types
int a=(int)d;


2) int f=200;

object z=f; //casting as well as boxing: conversion of a value type to a reference type.

Differences between interface and an abstract class

What are the differences between an interface and an abstract class.


Both interface and an abstract class cannot be instantiated and are implemented
by inheriting them in other classes.

The differences between them are:

Interfaces--

a)All members are public by default.
b)They cannot contain fields.
c)No coding of the methods or the properties is allowed.
d)They do not provide implementation.
e)Interfaces support multiple inheritance
f)abstract keyword is not there before the interface or its members names.


Abstract classes--

a)All members are private by default. We can put modifiers like
public, protected before the abstract class members.
b)They can contain fields.
c) coding of the methods or the properties is allowed.(nonabstract)
we can also declare abstract methods(methods with no coding) and only
the declaration
d)They can provide implementation. An abstract class can implement an
interface
e)Abstract classes support single inherritance
g)abstract keyword is required before their names and also before the
abstract methods or properties.

Querystring,cookies,View state,session state,application state,Context.handler

What are the ways to retain variables between requests?





Below there are different ways to retain variables between requests. That is:

Context.Handler: This object can be used to retrieve public members of the webform from a subsequent web page.

Querystring: Querystring is used to pass information between requests as part of the web address. Since it is visible to use, we can't use it to send any secured data.

Cookies: Cookies stores small amount of information on client side. But we can't reply on cookies since many clients can refuse cookies.

View state: View state stores items added to the pages. These properties are as hidden fields on the page.

Session state: Session state stores items that are local to the current session.

Application state: Application state stores items that are available to all users of the application.

differences between arrays and collections

Explain the similarities and differences between arrays and collections?


• The Array class is not part of the System.Collections namespace. But an array is a collection, as it is based on the list interface.

• Array has a fixed capacity but the classes in the System.Collections namespace don’t have fixed capacity. That’s why array is a static container, but collection is dynamic container.

• Collections objects have a key associated with them. You can directly access an item in the collection by the key. But to find a specific item in an array, unless you don’t know the index number you need to traverse the array to find the value.

difference between a Thread and a Process

Describe the difference between a Thread and a Process?

A Process is an instance of an running application. And a thread is the Execution stream of the Process. A process can have multiple Thread.
When a process starts a specific memory area is allocated to it. When there is multiple thread in a process, each thread gets a memory for storing the variables in it and plus they can access to the global variables which is common for all the thread.

Immutable

What does the term immutable mean?

In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created.
The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory. Ex: String.
Making an object immutable is usually inappropriate if the object contains a large amount of changeable data.
So, For this reason .NET has the System.Text.StringBuilder class which is Mutable and appropriate for large amount of changeable data.

differences between .NET Framework 3.0 and 3.5


What are the differences between .NET Framework 3.0 and 3.5?


- .NET 3.0 is the combination of .NET Framework 2.0 with WCF, WPF, WF and cardspace.
- .NET 3.5 is the combination of .NET Framework 3.0 with New AJAX controls, LINQ, Richer WCF support, Silverlight Support...

Difference between Web.config and Machine.config

What is the Difference between Web.config and Machine.config?

Scope:
Web.config => For particular application in IIS.
Machine.config = > For All the applications in IIS

Created:
Web.config => Created when you create an application
Machine.config => Create when you install Visual Studio

Known as:
Web.config => is known as Application Level configuration file
Machine.config => is known as Machine level configuration file

Location:
Web.config => In your application Directory
Machine.config => …\Microsoft.NET\Framework\(Version)\ CONFIG

differences between Server-side and Client-side code

differences between Server-side and Client-side code?

Server side code will execute at server (where the website is hosted) end, & all the business logic will execute at server end where as client side code will execute at client side (usually written in javascript, vbscript, jscript) at browser end.

Difference between VB.NET and C#.NET

Difference between VB.NET and C#.NET
VB.NET :

1)no unsigned int
2)Loosely typed language
3)no operator overloading
4)no pointers
5)no auto XML documentation


C#.net :

1) supports unsigned int
2)strongly typed language
3)supports operator overloading
4)supports pointers
5)supports auto XML documentation

similarilty & difference between .dll extension and .exe extension files

whats the similarilty & difference between .dll extension and .exe extension files?


A standard exe application is one that is created using Standard EXE project. It is the most widely used Project type using VB6. Standard EXE application is normally the most widely used among the available Project types in Visual Basic. Stand-alone programs have an .EXE file extension.

Usage A standard EXE application is normally used when you want to develop a stand-alone application. Examples include calculators, text editors, and other similar applications.

An ActiveX EXE application is one that is created using ActiveX EXE project. ActiveX EXE are widely used in conjunction with standard EXE applications. There are three types of widely used of ActiveX projects. These are:

a. ActiveX EXE
b. ActiveX DLL
c. ActiveX Control

ActiveX EXE: Unlike a stand-alone EXE file, an ActiveX EXE file is designed to work as an OLE server, which is nothing more than a program designed to share information with another program. It has an .EXE file extension.

ActiveX DLL: ActiveX DLL files are not meant to be used by themselves. Instead, these types of files contain subprograms designed to function as building blocks when creating a stand-alone program. It has a .DLL file extension.

ActiveX Control: Unlike an ActiveX DLL or ActiveX EXE file, an ActiveX Control file usually provides both subprograms and a user interface that you can reuse in other programs. It has an .OCX file extension.

Usage
1. The ActiveX EXE/DLL is normally used when you need to build a component that is separate from the main program. The concept is based on COM model.

2. ActiveX DLL/EXE allows multiple applications to share the same code. This allows for scalability of programs, and saves time because you only need to write the code once.

3. ActiveX DLLs and ActiveX EXEs are almost same in the ways they are built and used. In either case, you build one or more classes that applications can use to do something.

4. One of the main differences between ActiveX EXE and an ActiveX DLL's is that the code is executed within the main program's address space for ActiveX DLL. This is because the code lies inside the program's address space, calling methods and execution of code is very fast.

Differences

An ActiveX Exe provides the reusability of code, by accessing it from different clients.

An ActiveX Exe is a component that can be called by another application by providing a reference to the component. But a Standard Exe application cannot be called in this way.

An ActiveX EXE's code is run in a separate process. When the main program calls an ActiveX EXE's method, the application passes required parameters into the ActiveX EXE's and calls the method. The ActiveX EXE, upon execution may return the results to the main program. This is slower than running an ActiveX DLL's method inside the main program's address space.

Difference between debug build and release build

What is the difference between debug build and release build?


The biggest difference between these is that:

In a debug build the complete symbolic debug information is emitted to help while debugging applications and also the code optimization is not taken into account.

While in release build the symbolic debug info is not emitted and the code execution is optimized.
Also, because the symbolic info is not emitted in a release build, the size of the final executable is lesser than a debug executable.

One can expect to see funny errors in release builds due to compiler optimizations or differences in memory layout or initialization. These are ususally referred to as Release - Only bugs :)

In terms of execution speed, a release executable will execute faster for sure, but not always will this different be significant.

IsPostBack in Asp.net

What is isPostback property?


This property is used to check whether the page is being loaded and accessed for the first time or whether the page is loaded in response to the client postback. 
"Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback."

Example:
Consider two combo boxes
In one lets have a list of countries
In the other, the states.
Upon selection of the first, the subsequent one should be populated in accordance. So this requires postback property in combo boxes to be true.

In code Behind in c#.net

private void Page_Load()
{
    if (!IsPostBack)
    {
        // Validate initially to force asterisks
        // to appear before the first roundtrip.
        Validate();
    }
}

Dotnet Interview question for fresher

 What are session management techniques in .NET?


There are three different techniques of managing session in ASP.NET
InProc
Session state is stored locally in memory of ASP.NET worker process.

StateServer
Session state is stored outside ASP.NET worker process and is managed by Windows service. Location of this service is specified by stateConnectionString attribute.

SQLServer
Session state is stored outside ASP.NET worker process in SQL Server database. Location of this database is represented by sqlConnectionString attribute.



What is MVC (Model View Controller) pattern?

The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes [Burbeck92]:

Model. The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).

View. The view manages the display of information.

Controller. The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.


How to use trace in libraray classes (like BAL, DAL)?


Use following code to use Trace.Warn, Trace.Write etc.

System.Web.HttpContext.Current.Trace

What is gacutil.exe?


It's a command to install the assembly into the Global Assembly Cache.

What is boxing and unboxing?


Converting a value type to reference type is called Boxing and Converting reference type of value type is Unboxing.

int i = 1;
object o = i; // boxing
int j = (int) o; // unboxing


Difference between Response.Expires and Response.ExpiresAbsolute?

Response.Expires
This property specifies the number of minutes before a page cached in the browser expires ie. if the user returns to the same page before the specified number of minutes the cached version of the page is displayed.
<% Response.Expires = minutes %>

Response.ExpiresAbsolute
Using this property we can set the date and/or time at which page cached in the browser expires.
<% Response.ExpiresAbsolute=#May 15, 1999 18:00:00# %>

What is CLR (Common Language Runtime)?


This is an execution engine for .NET Framework application. It provides a number of services including
1. Code Management
2. Application memory isolation
3. Verification of type safety
4. Conversion of IL to native code.
5. Access to meta data
6. Managing memory for managed objects
7. Enforcement of code access security
8. Exception handling, including cross-language exceptions.
9. Inter operation between managed code, COM objects and pre-existing DLLs (Unmanaged code and data)
10. Automation of object layout
11. Support for developer services (profiling, debugging etc.)

Write a function into Javascript that will toggle display a HTML element.?



function ShowHide(id)

        {

document.getElementById(id).style.display == '' ? document.getElementById(id).style.display = 'none' : document.getElementById(id).style.display = '';      

        }



We can call this function like
<a href="#" onclick="ShowHide('divid')">Show/Hide</a>

If the "divid" is already displaying on the page it will hide if not it will show on the page and so on.

When to use String and StringBuilder class?


Use the String class to concat, join or format methods to join multiple items in a single statement.

Use StringBuilder class to create dynamic strings.


String is a value type or reference type?

String is a reference type variable.

List few ValueTypes variables.

Below are all ValueTypes variables.

System.SByte,
System.Byte
System.Int16
System.Int32
System.Int64
System.Single
System.Double
System.Decimal
System.Char
System.Boolean
System.DateTime

What is the use of RCW & CCW?

RCW : Runtime Collable Wrapper takes a COM component, wrap it up and allows .NET client to consume it.

CCW: COM Collable Wrapper wraps a .NET object for consumption by COM client

Where reference and value types variables are stored?

All reference type variables are stored in heap (Random) and all value types variables are stored in stack (Sequential).

What is Singleton pattern?

Singleton pattern ensures a class has only one instance & provide a global point of access to it. It is achieved by declaring a static variable for the class & checking for null before actually instantiating it.

What does apsx stand for?

Active Server Pages Extension

What is CTS?


CTS (Common Type System) is a rich type system, build into the common language runtime that supports the types and operations found in most of the programming languages. The common type system supports the complete implementation of a wide range of programming language.

What is CLS?

CLS (Common Language Specification) is a set of constructs or constraints that serves as a guide for library writers and compiler writers.It allows libraries to be fully usable from any language supporting the CLS, and for those languages to integrate with each other. The CLS is a subset of common type system. The common language specifications is also important to application developers wh are writing code that will be used by other developers.

What is MSIL?


MSIL (Microsoft Intermediate Language) is a CPU-Independent instructions set into which .NET Framework programs are compiled. It contains instructions for loading, storing, initializing and calling methods on objects.

What is Satellite Assembly?

It is a often used to deploy language specific resources for an application. These assemblies work in side-by-side execution because the application has a separate product ID for each language & installed satellite assemblies in a language specific sub-directory.
When uninstalling, the application removes only the satellite assemblies associated within a give language & .NET Framework version.

What is RSS?

RSS (Really Simple Syndication/Rich Site Summary) is a light weight XML format for distributing news headlines or site summary & other contents of the website.

What is application domain?

The primary purpose of application domain is to isolate an application from other application. Win32 process provides isolation but in distinct memory address spaces. This is effective but it is expensive and doesn't scale well. The .NET runtime enforces app domain isolation by keeping control over the use of memory.

All memory in the app domain is managed by the .net runtime so the runtime can ensure that app domain do not access each other's memory. Objects in different application domains communicate either by transporting copies of objects across application domain boundries or by using a proxy to exchange messages.

What is Remoting in .NET?

.NET Remoting offers much more complex functionality including support for passing objects by values or by references, callbacks & multiple objects activation ^ life cycle management policy.

In order to use Remoting a client need to build using .NET.

What is Property?

A property is a method or pair of methods that are exposed to the outside world as if they are fields.


Can a DataAdapter.Fill method take DataTable as parameter or it works only for DataSet?


It has 5 different overloads and of course it can take DataSet as well as DataTable as parameter to fill data in from database.

What is typed dataset ?

A typed dataset is very much similar to a normal dataset. But the only difference is that the sehema is already present for the same. Hence any mismatch in the column will generate compile time errors rather than runtime error as in the case of normal dataset. Also accessing the column value is much easier than the normal dataset as the column definition will be available in the schema.

Can you place two .dll files with the same name in GAC (Global Assembly Cache)?

Yes, provided both have different versions.

GAC is a Folder that contains .dll that have strong name. So we can keep myproject.dll and myproject.dll two files into GAC with different version like 1.0.0.0 and 1.0.0.1

What's the difference between private and shared assembly?

Private Assembly is used inside an application only and does not have to be identified by a strong name.

Shared Assembly can be used by multiple applications and has to have a strong name.

What is the location of Global Assembly Cache on the system.
C:\$WINDOWS\assembly

What is JIT (Just-in-time) Compiler ?

Just-in-time compiler is a compiler used to convert the Commmon Intermediate Language (CIL) code into native code (also called machine code) that is processed by machine.

A little description

While compiling of .NET program, its code is converted into Common Intermediate Language code that is done by Common Language Runtime.


But while executing the program this CIL code is converted into Machine code or Native code that is done by JIT Compiler.

What is Managed and Unmanaged code?


Managed Code is what Visual Basic .NET and C# compilers create. It compiles to Intermediate Language (IL), not to machine code that could run directly on your computer. The IL is kept in a file called an assembly, along with metadata that describes the classes, methods, and attributes (such as security requirements) of the code you've created. This assembly is the one-stop-shopping unit of deployment in the .NET world. You copy it to another server to deploy the assembly there—and often that copying is the only step required in the deployment.

Unmanaged code is what you use to make before Visual Studio .NET 2002 was released. Visual Basic 6, Visual C++ 6, heck, even that 15-year old C compiler you may still have kicking around on your hard drive all produced unmanaged code. It compiled directly to machine code that ran on the machine where you compiled it—and on other machines as long as they had the same chip, or nearly the same. It didn't get services such as security or memory management from an invisible runtime; it got them from the operating system. And importantly, it got them from the operating system explicitly, by asking for them, usually by calling an API provided in the Windows SDK. More recent unmanaged applications got operating system services through COM calls.



What is the difference between Namespace and Assembly?


Namespace:
1. It is a Collection of names wherein each name is Unique.
2. They form the logical boundary for a Group of classes.
3. Namespace must be specified in Project-Properties.

Assembly:
1. It is an Output Unit. It is a unit of Deployment & a unit of versioning. Assemblies contain MSIL code.
2. Assemblies are Self-Describing. [e.g. metadata,manifest]
3. An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within their implementation unit, or by code outside that unit.

What is Manifest?

The manifest describes the assembly, providing the logical attributes shared by all the modules and all components in the assembly. The manifest contains the assembly name, version number, locale and an optional strong name that uniquely identifying the assembly.

What is Metadata?

Metadata is the complete way of describing what is in a .NET assembly. Digging into the metadata yields the types available in that assembly, viz. classes, interfaces, enums, structs, etc., and their containing namespaces, the name of each type, its visibility/scope, its base class, the interfaces it implemented, its methods and their scope, and each method’s parameters, type’s properties, and so on.

What is CODE Access security?

Code Access Security (CAS), in the Microsoft .NET framework, is Microsoft's solution to prevent untrusted code from performing privileged actions.

It performs following function

1. Defines permissions and permission sets that represent the right to access various system resources.
2. Enables administrators to configure security policy by associating sets of permissions with groups of code (code groups).
3. Enables code to request the permissions it requires in order to run, as well as the permissions that would be useful to have, and specifies which permissions the code must never have.
4. Grants permissions to each assembly that is loaded, based on the permissions requested by the code and on the operations permitted by security policy.
5. Enables code to demand that its callers have specific permissions.
6. Enables code to demand that its callers possess a digital signature, thus allowing only callers from a particular organization or site to call the protected code.
7. Enforces restrictions on code at run time by comparing the granted permissions of every caller on the call stack to the permissions that callers must have.

What’s difference between System.SystemException and System.ApplicationException?


The difference between ApplicationException and SystemException is that SystemExceptions are thrown by the CLR, and ApplicationExceptions are thrown by Applications.

What is multi-threading?

It is basically trying to do more than one thing at a time within a process.

There are two main ways of multi-threading which .NET encourages: starting your own threads with ThreadStart delegates, and using the ThreadPool class either directly (using ThreadPool.QueueUserWorkItem) or indirectly using asynchronous methods (such as Stream.BeginRead, or calling BeginInvoke on any delegate).


What the way to stop a long running thread ?

System.Threading.Thread.Abort

What is the diffeernce between Overload and Override?

Overload is the another version of the same function into the class. There can be different parameters, return type in overload functions (in brief: Same function and different parameters).

Override is entirely overriding the base class function and creating our own version in the child class. Base class and child class function name and return type should be same.

Query string in asp.net

Example url with querystring can be something similar like this

http://yourdomainname.com/defauld.aspx?variable1=value1&variable2=value2

Suppose we have a textbox txtData and we want it's value on other page
than in code behind we would write in click event of btnGo

private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?Value=" +
txtData.Text);
}

Or

1private void btnGO_Click(object sender, System.EventArgs e)
2{
3Response.Redirect("Default2.aspx?city=" +
4txtData.Text + "&country=" + txtcountry.Text);
5}


Now to retrieve these values on other page we need to use request.querystring, we can either retrieve them by variable name or by index

private void Page_Load(object sender,System.EventArgs e)
{
txtCity.Text = Request.QueryString["city"];
txtCountry.Text = Request.QueryString["country"];
}

Or we can also use

private void Page_Load(object sender,System.EventArgs e)
{
txtCity.Text = Request.QueryString[0];
txtCountry.Text = Request.QueryString[1];
}



QueryString can't be used for sending long data because it has a max lenght limit

Data being transferred is visible in url of browser

To use spaces and & in query string we need to replace space by %20 and & by %26


private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?Value=" +
txtData.Text.Replace(" ","%20");
}

Or we can use Server.UrlEncode method

private void btno_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.Aspx?" +
Name=" + Server.UrlEncode(txtData.Text));
}

Monday 16 January 2012

Jquery calender as a dropdown in asp.net

Jquery calender as a dropdown to select month and year  in asp.net





 In .aspx page In head section

<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js" type="text/javascript"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type = "text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type = "text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel = "Stylesheet" type="text/css" />


    <script type ="text/javascript">

        $(function () {
            $("#txtDateOfBirth").datepicker({
                dateFormat: 'mm/dd/yy',
                changeMonth: true,
                changeYear: true,
                yearRange: '-100y:c+nn',
                maxDate: '-1d'
            });
        });
</script>



In body section --

   <asp:TextBox ID="   <asp:TextBox ID="txtDateOfBirth"   runat="server"
                             ></asp:TextBox>
                          "   runat="server"
                             ></asp:TextBox>