Friday, December 14, 2012

How to Print webpage ?

If you want to print same page then just write the javascript.


   function print() {
                window.print();
        }

if you want to print another webpage from the current page then write below scrpt



   function print(var str) {
               printWindow = window.open(  str,"mywindow");
               setTimeout('printWindow.print()', 3000);
               setTimeout('printWindow.close()', 3000);

        }

Tuesday, December 11, 2012

How to use HTTPS secure Page in URL in some Pages.


You may have to use https while Registration.

Please Add the Below code in Global.asax Page.

  protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var currentUrl = System.Web.HttpContext.Current.Request.Url;
            if (currentUrl.AbsoluteUri.Contains("Registration"))
            {
                if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
                {
                    //build the secure uri
                    var secureUrlBuilder = new UriBuilder(currentUrl);
                    secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
                    //use the default port.
                    secureUrlBuilder.Port = string.IsNullOrEmpty(ConfigurationManager.AppSettings["HttpsPort"].ToString()) ? 443 : Convert.ToInt32(ConfigurationManager.AppSettings["HttpsPort"].ToString());
                    //redirect and end the response.
                    System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
                }
            }
        }

How to add JavaScript at runtime using C#

string Script=@”function ShowName() { var txt=document.getElementById(‘txtName’); alert(‘Your name is: ‘+txt.value); }”; 

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), “ShowName”, Script, true);

Wednesday, November 7, 2012

Sorting XML in C# alphabetically and by order


Snippet
using System;
using System.Linq;
using System.Xml.Linq;
 
namespace ThrowAwayCSConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = @"<?xml version=""1.0"" encoding=""UTF-8\""?>
                    <websites> 
                        <site language=""Spanish"" name=""Excélsior"" order=""2"">http://www.excelsior.com.mx/</site> 
                        <site language=""Japanese"" name=""TOKYO Web"" order=""3"">http://www.tokyo-np.co.jp/</site>
                        <site language=""Italian"" name=""Corriere della Sera"" order=""1"">http://www.corriere.it/</site>
                        <site language=""Spanish"" name=""SpanishTest1"" order=""4"">www.spanishtest1.com</site> 
                    </websites>";
 
            XDocument xdoc = XDocument.Parse(xml);
            XDocument xNewDoc = new XDocument();
 
            xNewDoc.Add(xdoc.Root);
 
            xNewDoc.Root.RemoveNodes();
            xNewDoc.Root.Add(xdoc.Root.Elements().OrderBy(e => e.Attribute("language").Value));
 
            Console.WriteLine("Before: \r\n{0}", xdoc.ToString());
            Console.WriteLine();
            Console.WriteLine("After: \r\n{0}", xNewDoc.ToString());
            Console.ReadLine();
        }
    }
}
Which produces this output:
Before:
<websites>
 <site language="Spanish" name="Excélsior" order="2">http://www.excelsior.com.mx/</site>
 <site language="Japanese" name="TOKYO Web" order="3">http://www.tokyo-np.co.jp/</site>
 <site language="Italian" name="Corriere della Sera" order="1">http://www.corriere.it/</site>
 <site language="Spanish" name="SpanishTest1" order="4">www.spanishtest1.com</site>
</websites>

After:
<websites>
 <site language="Italian" name="Corriere della Sera" order="1">http://www.corriere.it/</site>
 <site language="Japanese" name="TOKYO Web" order="3">http://www.tokyo-np.co.jp/</site>
 <site language="Spanish" name="Excélsior" order="2">http://www.excelsior.com.mx/</site>
 <site language="Spanish" name="SpanishTest1" order="4">www.spanishtest1.com</site>
</websites>

Monday, October 29, 2012

How to Get IP Address of our own Machine..


string strHostName = "";
strHostName = System.Net.Dns.GetHostName();

IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

IPAddress[] addr = ipEntry.AddressList;

string ip= addr[addr.Length - 1].ToString();


If you want to Retrive True IP Address then


string IPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (IPAddress == null) //may be the HTTP_X_FORWARDED_FOR is null
{
            IPAddress = Request.ServerVariables["REMOTE_ADDR"];//we can use REMOTE_ADDR
}



Tuesday, October 16, 2012

Triggering an Event in Jquery with hyperlink href is firing only first time.


Before some days back i have an issue with my Jquerry.I have an hover Event and in that i am Triggering an Click Event.but the Problem is that it execute only first it will not triggering second time.The code is like this

  $(document).ready(function () {
        $(".various1").fancybox().hover(function () {
                    this.click();
            });
        });

so this code is execute for first time when i hover the image.so Replace above code with this it will worked.


  $(document).ready(function () {

            $(".various1").fancybox().hover(function () {
               if (this.click) {
                    this.click();
                 
                } else if (document.createEvent) {
                    if (event.target !== this) {
                        var evt = document.createEvent("MouseEvents");
                        evt.initMouseEvent("click", true, true, window,
          0, 0, 0, 0, 0, false, false, false, false, 0, null);
                        var allowDefault = this.dispatchEvent(evt);
               
                    }
                }

            });
        });

Wednesday, September 26, 2012

Find Current Year Start Date and End Date in SQL?


select  DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)'Start Date ',
DATEADD(dd,-1,DATEADD(yy,0,DATEADD(yy,DATEDIFF(yy,0,getdate())+1,0))) 'End Date'


Output


Start Date                          End Date
2012-01-01 00:00:00.000 2012-12-31 00:00:00.000


Find Current QUARTER Start Date and End Date in SQL

SELECT  DATEADD(qq, DATEDIFF(qq, 0, GETDATE()),  0)'Start Date',DATEADD(qq, DATEDIFF(qq, - 1, GETDATE()), - 1)'End Date'


Output:

Start Date                                 End Date
2012-07-01 00:00:00.000 2012-09-30 00:00:00.000

Monday, September 17, 2012

Set Current Month,Year as a Default Parameter in SSRS

Introduction

                  Set Default value to Parameter  @Year=Year(Now())
                  Set Default value to Parameter @Month=Month(Today)(This gives you integer value of Month 1 to 12) or  =MonthName(Month(Now)) (This gives you the string value like January,February,March etc.)


Please Note that you have to add value in Parameter.                

Tuesday, August 7, 2012

Crosstab queries using PIVOT in SQL Server

Problem

In SQL Server 2000 there was not a simple way to create cross-tab queries, but a new option in SQL Server 2005 has made this a bit easier. We took a look at how to create cross-tab queries in SQL Server 2000 in this previous tip and in this tip we will look at this new feature in SQL Server 2005 to allow you produce cross-tab results.

Solution

With SQL Server 2005 a lot of new features have been introduced. One of these new features is PIVOT.  What this allows you to do is to turn query results on their side, so instead of having results listed down like the listing below, you have results listed across.
SalesPersonProductSalesAmount
BobPickles$100.00
SueOranges$50.00
BobPickles$25.00
BobOranges$300.00
SueOranges$500.00
With a straight query the query results would be listed down, but the ideal solution would be to list the Products across the top for each SalesPerson, such as the following:
SalesPersonOrangesPickles
Bob$300.00$125.00
Sue$550.00
To use PIVOT you need to understand the data and how you want the data displayed.  First you have the data rows, such as SalesPerson and the columns, such as the Products and then the values to display for each cross section.  Here is a simple query that allows us to pull the cross-tab results.
SELECT SalesPerson, [Oranges] AS Oranges, [Pickles] AS Pickles
FROM
(SELECT SalesPerson, Product, SalesAmount
FROM ProductSales ) ps
PIVOT
(
SUM (SalesAmount)
FOR Product IN
( [Oranges], [Pickles])
) AS pvt
So how does this work?
There are three pieces that need to be understood in order to construct the query.
  • (1) The SELECT statement
    • SELECT SalesPerson, [Oranges] AS Oranges, [Pickles] AS Pickles
    • This portion of the query selects the three columns for the final result set (SalesPerson, Oranges, Pickles)

  • (2) The query that pulls the raw data to be prepared
    • (SELECT SalesPerson, Product, SalesAmount FROM ProductSales) ps
    • This query pulls all the rows of data that we need to create the cross-tab results.  The (ps) after the query is creating a temporary table of the results that can then be used to satisfy the query for step 1.

  • (3) The PIVOT expression
    • PIVOT (SUM (SalesAmount) FOR Product IN ( [Oranges], [Pickles]) ) AS pvt
    • This query does the actual summarization and puts the results into a temporary table called pvt
Another key thing to notice in here is the use of the square brackets [ ] around the column names in both the SELECT in part (1) and the IN in part (3).  These are key, because the pivot operation is treating the values in these columns as column names and this is how the breaking and grouping is done to display the data.

Monday, July 30, 2012

How to format datetime & date in Sql ?

Introduction:

                  Lets see one by one with Example.

SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)
                                        – Jul  30 2012 11:01AM          
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 30/07/2012                  
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2012.30.07           
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) – dd mon yyyy
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy
SELECT convert(varchar, getdate(), 108) – hh:mm:ss
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)
                                        – Oct  2 2012 11:02:44:013AM   
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) – yyyymmdd
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm
                                        – 02 Oct 2012 11:02:07:577     
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm
                                        – 2012-30-07T10:52:47.513
– SQL create different date styles with t-sql string functions
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy

Default values for a date parameter in SSRS

Introduction
                 We can use sql queries or some of the cool expressions available in SSRS to set default date parameters:


Set First Day of previous week (Monday)
=DateAdd(DateInterval.Day, -6,DateAdd(DateInterval.Day, 1-Weekday(today),Today))


Set Last Day of previous week (Sunday)
=DateAdd(DateInterval.Day, -0,DateAdd(DateInterval.Day, 1-Weekday(today),Today))


Set First Day of Current Week (Monday)
=DateAdd("d", 1 - DatePart(DateInterval.WeekDay, Today(),FirstDayOfWeek.Monday), Today())


Set Last Day of Current Week (Sunday)
=DateAdd("d" ,7- DatePart(DateInterval.WeekDay,Today(),FirstDayOfWeek.Monday),Today())


Set First Date of last month
=DateAdd("m", -1, DateSerial(Year(Now()), Month(Now()), 1))

Set Last date of last month
=DateAdd("d", -1, DateSerial(Year(Now()), Month(Now()), 1))

Set First date of current month
=DateSerial(Year(Now()), Month(Now()), 1)

Set Last date of current month
=DateAdd("d",-1,(DateAdd("m", 1, DateSerial(Year(Now()), Month(Now()), 1))))

Saturday, July 28, 2012

Interview Questions in ASP.NET,C#.NET,SQL Server,.NET Framework


Here I am posting the most common interview questions whatever everybody have faced during their interviews.

The most common question for experience persons is

Why would you like to change the company?

1) I am looking for a more challenging career in a firm with a larger employee base such as yours.
2)Chane is always welcome and new things are always there.I want to get a new opportunity and discover myself in a bigger role which would give me in extending my limitation.and also help me in building my career development.
2) Keeping in mind my career goals, the time has come for me to move onto the next step of
the ladder and make a mark for myself. This can be achieved in a company like this.
3) I am looking for the experience that can prepare me better for my future also your company is known for developing  people professionally i wanted to grow professionally as 
well as financially.

What is Software Architecture?


  •          Partitioning the problem and the system to be built into discrete pieces
  •          Techniques used to create interfaces between these pieces
  •          Techniques used to manage overall structure and flow
  •          Techniques used to interface the system to its environment
  •          Appropriate use of development and delivery approaches, techniques and tools.


Why Architecture is important?


  •     Controls complexity
  •     Enforces best practices
  •     Gives consistency and uniformity
  •     Increases predictability
  •     Enables re-use.


Difference between stored procedure and function

1) Procedure can return zero or n values whereas function can return one value which is mandatory.

2) Procedures can have input, output parameters for it whereas functions can have only input parameters.
3) Procedure allows select as well as DML statement in it whereas function allows only select statement in it.
4) Functions can be called from procedure whereas procedures cannot be called from function.
5) Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
6) We can go for transaction management in procedure whereas we can't go in function.
7) Procedures cannot be utilized in a select statement whereas function can be embedded in a select statement.

Difference between Abstract and Interface


Abstract Class:
-Abstract class provides a set of rules to implement next class
-Rules will be provided through abstract methods
-Abstract method does not contain any definition
-While inheriting abstract class all abstract methods must be override
-If a class contains at least one abstract method then it must be declared as an “Abstract Class”
-Abstract classes cannot be instantiated (i.e. we cannot create objects), but a reference can be created
-Reference depends on child class object’s memory
-Abstract classes are also called as “Partial abstract classes”
-Partial abstract class may contain functions with body and functions without body
-If a class contains all functions without body then it is called as “Fully Abstract Class” (Interface)
An abstract class means that, no object of this class can be instantiated, but can make derivations of this.
An example of an abstract class declaration is:

abstract class absClass
{
}
An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
An example of an abstract method:

abstract class absClass
{
  public abstract void abstractMethod();
}
Also, note that an abstract class does not mean that it should contain abstract members. Even we can have anabstract class only with non abstract members. For example:

abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
}
A sample program that explains abstract classes:

using System;

namespace abstractSample
{
      //Creating an Abstract Class
      abstract class absClass
      {
            //A Non abstract method
            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be
            //overridden in derived class
            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

      //A Child Class of absClass
      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an
               //instance of the derived class

               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0},
                       Multiplied : {1}", added, multiplied);
            }

            //using override keyword,
            //implementing the abstract method
            //MultiplyTwoNumbers
            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}
In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers andMultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation andMultiplyTwoNumbers is an abstract method that does not contain implementation.
The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers andMultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the childclass it is optional to make the implementation of the abstract methods of the parent class.
Example
//Abstract Class1
abstract class absClass1
{
    public abstract int AddTwoNumbers(int Num1, int Num2);
    public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//Abstract Class2
abstract class absClass2:absClass1
{
    //Implementing AddTwoNumbers
    public override int AddTwoNumbers(int Num1, int Num2)
    {
        return Num1+Num2;
    }
}

//Derived class from absClass2
class absDerived:absClass2
{
    //Implementing MultiplyTwoNumbers
    public override int MultiplyTwoNumbers(int Num1, int Num2)
    {
        return Num1*Num2;
    }
}
In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. The AddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived fromabsClass2 and the MultiplyTwoNumbers is implemented there.
Interface:
-If a class contains all abstract methods then that class is known as “Interface”
-Interfaces support like multiple inheritance
-In interface all methods r public abstract by default
-Interfaces r implementable
-Interfaces cannot be instantiated, but a reference can be created


Abstract class vs. Interface

An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.
An example of interface:
 Collapse | Copy Code
interface iSampleInterface
{
  //All methods are automaticall abstract
  int AddNumbers(int Num1, int Num2);
  int MultiplyNumbers(int Num1, int Num2);
}
Defining an abstract class with abstract members has the same effect to defining an interface.
The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.
A class can inherit one or more interfaces, but only one abstract class.
Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.
The selection of interface or abstract class depends on the need and design of your project. You can make anabstract class, interface or combination of both depending on your needs.

What is the difference between an Interface and an Abstract class?

There are quite a big difference between an interface and an abstract class, even though both look similar.
  •   Interface definition begins with a keyword interface so it is of type interface
  •   Abstract classes are declared with the abstract keyword so it is of type class
  •   Interface has no implementation, but they have to be implemented.
  •   Abstract class’s methods can have implementations and they have to be extended.
  •   Interfaces can only have method declaration (implicitly public and abstract) and fields (implicitly public static)
  •  Abstract class’s methods can’t have implementation only when declared abstract.
  •  Interface can inherit more than one interfaces
  •  Abstract class can implement more than one interfaces, but can inherit only one class
  •  Abstract class must override all abstract method and may override virtual methods
  •  Interface can be used when the implementation is changing
  •  Abstract class can be used to provide some default behavior for a base class.
  •  Interface makes implementation interchangeable
  •  Interface increase security by hiding the implementation
  •  Abstract class can be used when implementing framework
  •  Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies.

Index types in SQL Server

An index is a physical structure containing pointers to the data. Indexes are created in an either existing table to locate rows more quickly and efficiently or It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes; they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application.

A table scan happens when there is no index available to help a query. In a table scan SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance. There are two types of indexes are available in SQL SERVER

Clustered indexes define the physical sorting of a database table’s rows in the storage media. For this reason, each database table may have only one clustered index.

Non-clustered indexes are created outside of the database table and contain a sorted list of references to the table itself. Non-clustered indexes can be multiple.



What are differences between Array list and Hash table?

1) In Hash Table it stores the data as name and value pair while in array it stores only value.
2) To access Hash Table data you have to pass name while to access array you have to pass index.
3) you can store different type of data in hash table, say int, string etc. while in array you can store only similar type of data.

How many Types of Index are there in SQL

Ans: Two types of indexes are there one is clustered index and non-clustered index



How many types of memories are there in .net?

Ans: Two types of memories are there in .net stack memory and heap memory

Is it possible to set the session out time manually?

Ans: Yes we can set the session out time manually in web.config.

What are differences between function and stored procedure?

Ans:
1) Function returns only one value but procedure returns one or more than one value.
2) Function can be utilized in select statements but that is not possible in procedure.
3) Procedure can have an input and output parameters but function has only input parameters only.
4) Exceptions can be handled by try catch block in procedures but that is not possible in function.

What are the differences between Application object and session object?

Ans: The session object is used to maintain the session of each user. If one user enter in to the application then they get session id if he leaves from the application then the session id is deleted. If they again enter in to the application they get different session id.
But for application object the id is maintained for whole application.

What are differences between system.stringbuilder and system.string?

The main difference is system.string is immutable and system. string builder is a mutable. means you cant change the string in system.string while using system. string builder you can change the string by using various operation like append.Append keyword is used in string builder but not in system.string.

.Net has five access Specifiers

What is an access specifier?

An access specifier defines the scope of a class member. A class member refers to the variables and functions in a class. A program can have many classes. The programmer gets the privilege to decide the of use access specifier to implement encapsulation and abstraction in C#.

So, when we use Access Specifiers in C# they help the other class members to know how they can access the methods or variables declared/defined inside another class.

C# supports five types of access specifiers to tell the extent of visibility of a class member. They are:-

• public,
• private,
• protected,
• internal and
• protected internal.

Let's now go into detail.

public:

The public access specifier in C# allows a class to expose its member variables and member functions to other functions and objects. So any member declared public can be accessed outside the class also.

Let's check an example for this..
----------------------------------------------------------------

using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
}
class MyMainClass
{
static void Main(string[] args)
{
hello HelloObject=new hello();
HelloObject.iNum1=10; /* since variable iNum1 is public it can be accessed in other classes also*/

Console.WriteLine(HelloObject.iNum1);
}
}
}

----------------------------------------------------------------

private:

The private access specifier in C# is just opposite to the public access specifier. That is it allows a class to hide its member variables and member functions from other class objects and functions. So it is not visible outside the class. By default, the access specifier is private; if public, private or protected is not specified.

Let's check an example for this..
----------------------------------------------------------------

using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
private int iNum2;

public hello()
{
iNum1=0;
iNum2=10;
}

}

class MyMainClass
{
static void Main(string[] args)
{
hello HelloObject=new hello();
//CORRECT METHOD
HelloObject.iNum1=10; //Here since variable iNum1 is public it can be accessed in other classes also

//WRONG METHOD
HelloObject.iNum2=20; /*This line will return an Error since the access to this variable is Private. So it cannot be accessed outside the class*/

Console.WriteLine(HelloObject.iNum1);
}
}
}

----------------------------------------------------------------

protected:

The protected access specifier in C# allows a class to hide its member variables and member functions from other class objects and functions, except the child class. This access specifier is used when we need to use Inheritance in the program.

Let's check an example for this..
----------------------------------------------------------------

using System;
namespace HelloWorld
{
class hello
{
public int iNum1;
protected int iNum2;
}

class world : hello
{
public int AddDetails()
{
iNum1=20;
iNum2=10;

return iNum1+iNum2;
}
}

class MyMainClass
{
static void Main(string[] args)
{
world worldObject=new world();

worldObject.iNum1=50; //Line 1 No Error

worldObject.iNum2=10; //Line 2 Error

Console.WriteLine(worldObject.AddDetails().ToString());

}
}
}

----------------------------------------------------------------
In the above case we have not called the object of the class hello. But we have inherited the class hello to the class world. So all the public and protected members inside the class is accessible inside the derived class also. We don't need to create objects for the base class to access the variables or methods we have in our parent class.
Now inside the Main() function we are assigning value to iNum1 and iNum2. Line 1 will not return any error because the variable iNum1 is public. So, it can be accessed from anywhere in the program, but Line2 will give an Compilation Error saying "iNum2 is inaccessible due to protection level". This is because access of the variable iNum2 is set to protected. The protected members can only be accessed inside the Child class and its parent class.


internal:

Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#. Friends can be accessed by all classes within an assembly but not from outside the assembly.

protected internal:

The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and ofcourse, within the class itself.


Lets now understand the above with an example:
----------------------------------------------------------------
using System;
class Student
{
private string sAddress;
protected string sPhNo;
protected internal long iZipCode;
void Hello()
{
Console.WriteLine(“Hello World!”);
}
internal void Hello2()
{
Console.WriteLine(“Hello Student!”);
}
public void SetAddress()
{
Console.WriteLine(“Enter your Address:”)
sAddress = Console.ReadLine();
}
public void SetPhNo()
{
Console.WriteLine(“Enter your Phone Number:”)
sPhNo = Console.ReadLine();
}
public void SetZipCode()
{
Console.WriteLine(“Enter the Zip Code: “);
iZipCode =Convert.ToInt64(Console.ReadLine());
}
public void DisplayStudent()
{
Console.WriteLine(“The Address is: {0}”, sAddress);
}
}
class Display
{
static void Main(string[] args)
{
Student John = new Student();
Console.WriteLine(John.sAddress); //Error: protected members cannot be accessed
John.SetAddress(); //public members can be accessed outside the class definition
John.SetPhNo(); //public members can be accessed outside the class definition
Console.WriteLine(John.sPhNo); //error: protected internal members cannot be accessed outside the class definition
John.SetZipCode(); //public members can be accessed outside the class definition
John.DisplayStudent(); // public members can be accessed outside the class definition
Console.WriteLine(John.sAddress); //error: private members cannot be accessed outside the class definition
John.Hello(); //error: private members cannot be accessed outside the class definition
John.Hello2(); //displays Hello student!
Console.ReadLine();
}
}

What is the difference between primary key and unique key?

Ans:There is not difference between Primary key and unique key except Primary key does not accept null values while unique key accept the null value.

What is boxing and unboxing concepts in .net?

Ans: Boxing is a process of converting value type into reference type
       Unboxing is a process of converting reference type to value type.

What are the differences between value type and reference type?

Ans: Value type contain variable and reference type are not containing value directly in its memory.
Memory is allocated in managed heap in reference type and in value type memory allocated in stack. Reference type ex-class value type-struct, enumeration

What is SOA(Service Oriented Architecture)?

A service-oriented architecture is essentially a collection of services. These services communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating some activity. Some means of connecting services to each other is needed.

Why we go for page rendering in Asp.Net Page life cycle?

Ans: Browser understands an only html control that’s why in page rendering we will convert the aspx controls into html controls.

Write a sample query for self join?

Ans: Select e1.ename, e2.empid from emp e1, emp e2 where e1.empid=e2.mgrid;

Can we change the index of primary key on table?

Ans: No

How to find out which index is defined on table?

Ans: sp_helpindex tablename

The out Parameter

The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.
public class mathClass
{
public static int TestOut(out int iVal1, out int iVal2)
{
iVal1 = 10;
iVal2 = 20;
return 0;
public static void Main()
{
int i, j; // variable need not be initialized
Console.WriteLine(TestOut(out i, out j));
Console.WriteLine(i);
Console.WriteLine(j);
}
}

The ref parameter

The ref keyword on a method parameter causes a method to refer to the same variable that was passed as an input parameter for the same method. If you do any changes to the variable, they will be reflected in the variable.
You can even use ref for more than one method parameters.
namespace TestRefP
using System; 
public class myClass 
public static void RefTest(ref int iVal1 ) 
iVal1 += 2; 
public static void Main() 
int i; // variable need to be initialized 
i = 3; 
RefTest(ref i ); 
Console.WriteLine(i); 
}
ref means that value is already set, method can read it and can modify it.
out means that value isn't set and method must set it before return and couldn't read before setting value.

What is “ref” keyword in C#

“ref Keyword” in C#.

Passing variables by value is the default. However, we can force the value parameter to be passed by reference. 

Point to be kept in mind while using ref keyword.
variable “must” be initialized before it is passed into a method.


Example, Without Using ref keyword
class Test
{
public static void Main()
{
int a = 3;
DoWork(a);
Console.WriteLine("The value of a is " + a); 
}

public static void DoWork(int i)
{
i++;
}
}
The program will result in : The value of a is 3


Example, With the Use of ref keyword
class Test
{
public static void Main()
{
int a = 3; // must be initialized
DoWork(ref a); // note ref
Console.WriteLine("The value of a is " + a); 
}

public static void DoWork(ref int i) // note ref
{
i++;
}
}
The program will result : The value of a is 4

Can you write the program to find the length of string without using library function?
Ans: for (int i=0; str[i]!=”\n”; i++)
{
Count++;
}

What is the difference between scope_identity() and current_identity()?

Ans: Scope_identity and current _identity both are similar and it will return the last identity value generated in the table.
Scope_Identity will return the identity value in table that is currently in scope

What are difference between POST and GET Methods?

POST Method ():
  •  Data is not appended to the URL.
  •  Data is Secret
  •  it is a two call system.
  •  There is no Limit on the amount of data. That is characters any amount of data can be sent.
  •  Data transmission is comparatively slow.
  •  No default and should be explicitly specified.
GET Method ():
  •  Data is appended to the URL.
  •  Data is not secret.
  •  It is a single call system
  •  Maximum data that can be sent is 256.
  •  Data transmission is faster
  •  this is the default method for many browsers

What are difference between truncate and delete?

Ans: 1) Delete keep the lock over each row where Truncate keeps the lock on table not on all the row.
2) Counter of the Identity column is reset in Truncate where it is not reset in Delete.
3) Trigger is not fired in Truncate where as trigger is fired in Delete.
4) In TRUNCATE we cannot rollback.
5) In DELETE we can rollback


• DataTable,DataSet,DataView,Data Adapter,Data Reader

DataGridView is a control which gets data from DataTable, DataView or Dataset.
DataTable is an in-memory table.
DataSet is a collection of DataTable objects.

Difference Between DataSet and DataTable.

A Dataset has an overhead perfomance hit when its loaded with a lot of Data. Now let me be more clearer, a Dataset can Contain a lot of Datatable :) A Dataset is like a Container for Datatables because every dataset has a datatable contained inside it and a Datatable is like a table you have in SQL and a Dataset its like a Database that contain table(Datatable)

 DataView:: Represents a customized view of a DataTable for
 sorting, filtering, searching, editing, and navigation.

See the following example u can get Better idea...

// Create a new DataTable.
        System.Data.DataTable table = new
DataTable("Customers");
        // Declare variables for DataColumn and DataRow objects.
        DataColumn column;
        DataRow row;

        // Create new DataColumn, set DataType,
        // ColumnName and add to DataTable.  
        column = new DataColumn();
        column.DataType = System.Type.GetType("System.String");
        column.ColumnName = "ID";
        column.ReadOnly = true;
        column.Unique = true;
        // Add the Column to the DataColumnCollection.
        table.Columns.Add(column);


        // Create second column.
        // Add the column to the table.
        table.Columns.Add("FirstName",
System.Type.GetType("System.String"));

        // Add the column to the table.
        table.Columns.Add("LastName",
System.Type.GetType("System.String"));

        // Make the ID column the primary key column.
        DataColumn[] PrimaryKeyColumns = new DataColumn[1];
        PrimaryKeyColumns[0] = table.Columns["id"];
        table.PrimaryKey = PrimaryKeyColumns;


        // add new datarow by adding the values
        table.Rows.Add("C101", "Rajesh", "Kumar");
        table.Rows.Add("C102", "Fareed", "sk");
        table.Rows.Add("C103", "Rajesh", "Raji");

        //Sort and display
        DataView Dview = new DataView(table);
        Dview.Sort = "LastName ASC, FirstName ASC";

        GridView1.DataSource = Dview;
        GridView1.DataBind();

What is the difference Grid View and between Data Grid (Windows)?

Ans:
1) GridView Control Enables you to add sorting, paging and editing capabilities without writing any code.
2)GridView Control Automatically Supports paging by setting the ‘PagerSetting’ Property.The Page Setting Property supports four Modles

a. Numeric(by default)
b. Next Previous
c. NumericFirstLast
d. Next PreviousLast

3)It is Used in asp.net
4)GridView Supports RowUpdating and RowUpdated Events.
5)GidView is Capable of Pre-Operations and Post-Operations.
6)GridView Has EditTemplates for this control
7)It has AutoFormat

DataGrid(Windows)

1)DataGid Control raises single Event for operations
2)DataGird Supports the SortCommand Events that occur when a column is Soted.
3)DataGrid Supports UpdataCommand Event that occurs when the UpdateButton is clicked for an item in the grid.
4)DataGrid is used in Windows GUI Application.
5)It doesnot have EditTemplates for this control
6)It doesnot have AutoFormat

If I write System.exit (0); at the end of the try block, will the finally block still execute?

Ans: No in this case the finally block will not execute because when you say system.exit(0),the control immediately goes out of the program, and thus finally never executes.

What are the different levels of State management in ASP.NET?

Ans:
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

There are 2 types State Management:

1. Client – Side State Management
This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator (url), or a cookie. The techniques available to store the state information at the client end are listed down below:

a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.

b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.

c. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.

d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.

e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.

2. Server – Side State Management
a. Application State - Application State information is available to all pages, regardless of which user requests a page.

b. Session State – Session State information is available to all pages opened by a user during a single visit.

Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.


• Data Reader and DataAdapter

Data Reader:
 If your Data access operations is mainly fetching and displaying the records and doesnt involve insert/update/delete statements and other manipulations (forward only, read only) actions, go for the DataReader.

DataReader offers a forward only read stream of access to the records. It is very useful in cases where we just grab the data from the database to display in DataGrid, Label and other Webcontrols.

However, DataReader requires the connection with the database open until its operation is completed.

Data Reader will read only one record at a time.So memory consumption will be less,it is purely connection oriented it will use connection.
 exclusively when datareader is closed.the memory will be released on the server machine and connection will be used for any other purpose.

Data Reader read only forward only
It's connection oriented
should Explicitly close the connection

• Data Adapter
 Data Adapter acts as a mediator between dataset and database server. it will read data  from the database server and places with in dataset the manipulations on the dataset will  be updated with the database server. Data Adapter is disconnected its acts as a bridge  between data set and database. Data Adapter is nothing but mediator between Dataset and  Database, first data adapter connect to the database then fetches into the data set and  closes the connection, you can update the data into dataset, also you can update database  as well.

Abstract Class:

Abstract class is a class which can’t be instantiate. Class should have “Abstract” key word with the name. In any one of the method of class having abstract method with in it, then it should be define as abstract class. The class which derived the abstract class should have definition of the abstract method. These classes which derived the abstract class and implement the abstract methods call concrete class.
Abstract class may have the definition of function or may not. Below is the simple example of an abstract class
public abstract alass AbstractStudent
{
String Roll
{
get;
set;
}

String FirstName
{
get;
set;
}

String LastName
{
get;
set;
}


Public String GetStudentDetails()
{

// Implementation of Method
}

public String SaveStudentDetails ()
{
// Implementation of Method
}

public abstract String CalculateWage();

}
So, the class having one abstract method so we need to mention the class as "abstract" .

Difference between Abstract Class and Interface?

Abstract class is a class which can’t be instantiated and which can have methods with definition as well as declaration also. This can be inherited.

As for Example:

public abstract class AbstractStudent
{
String Roll
{
get;
set;
}

String FirstName
{
get;
set;
}

String LastName
{
get;
set;
}

Public String GetStudentDetails()
{
// Implementation of Method
}

public String SaveStudentDetails ()
{
// Implementation of Method
}

public abstract String CalculateWage();

}


Interface can only contain the methods declaration and can be implemented in the class.

As for Example:
Public interface IStudnet
{
String Roll
{
get;
set;
}

String FirstName
{
get;
set;
}

String LastName
{
get;
set;
}

String GetStudentDetails();
String SaveStudentDetails ();
}

• Use Of Global.asax File:

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events raised by ASP.NET or by HttpModules. The Global.asax file resides in the root directory of an ASP.NET-based application. At run time, Global.asax is parsed and compiled into a dynamically generated .NET Framework class derived from the HttpApplication base class. The Global.asax file itself is configured so that any direct URL request for it is automatically rejected; external users cannot download or view the code written within it.

Event
• Application_Init: Fired when an application initializes or is first called. It's invoked for all HttpApplication object instances.
• Application_Disposed: Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.
• Application_Error: Fired when an unhandled exception is encountered within the application.
• Application_Start: Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.
• Application_End: Fired when the last instance of an HttpApplication class is destroyed. It's fired only once during an application's lifetime.
• Application_BeginRequest: Fired when an application request is received. It's the first event fired for a request, which is often a page request (URL) that a user enters.
• Application_EndRequest: The last event fired for an application request.
• Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework begins executing an event handler like a page or Web service.
• Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework is finished executing an event handler.
• Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).
• Application_PreSendContent: Fired before the ASP.NET page framework sends content to a requesting client (browser).
• Application_AcquireRequestState: Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.
• Application_ReleaseRequestState: Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.
• Application_ResolveRequestCache: Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.
• Application_UpdateRequestCache: Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests.
• Application_AuthenticateRequest: Fired when the security module has established the current user's identity as valid. At this point, the user's credentials have been validated.
• Application_AuthorizeRequest: Fired when the security module has verified that a user can access resources.
• Session_Start: Fired when a new user visits the application Web site.
• Session_End: Fired when a user's session times out, ends, or they leave the application Web site.


what is ExecuteDataset?

Executes the command and returns the results in a new dataset with all the rows.

What is a Partial class?

Ans: Instead of defining an entire class, you can split the definition into multiple classes by using partial class keyword. When the application compiled, c# compiler will group all the partial classes together and treat them as a single class. There are a couple of good reasons to use partial classes. Programmers can work on different parts of classes without needing to share same physical file
Ex:
Public partial class employee
{
Public void somefunction()
{
}
}
Public partial class employee
{
Public void function ()
{
}
}

Difference Between Executescalar and ExecuteNonQuerry

ExecuteScalar - Returns only one value after execution of the query. It returns the first field in the first row. This is very light-weight and is perfect when all your query asks for is one item. This would be excellent for receiving a count of records (Select Count(*)) in an sql statement, or for any query where only one specific field in one column is required.

ExecuteNonQuery - This method returns no data at all. It is used majorly with Inserts and Updates of tables. It is used for execution of DML commands.
Example:
SqlCommand cmd = new SqlCommand("Insert Into t_SomeTable Values('1','2')",con);
//note that con is the connection object
con.Open();
cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed
Difference between ExecuteNonQuery, ExecuteScalar and ExecuteReader

1)ExecuteNonQuery 

a) Used mainly for action queries(insert,delete,update,create,alter,drop).

It can also be used with select queries.

example: A stored procedure in SQL Server that can be used for autogeneration of ID's using its

output parameter can have the value of output parameter returned on a windows form using ExecuteNonQuery.

b)returns an int value indicating the number of affected rows


2)ExecuteScalar 

a)Used in queries where we have to read a single value

example: 1)select count(*) from emp

2) select ename from emp where eno=100

b)returns an object


3)ExecuteReader 

b)Used in queries where we have to read a complete row of the data

example: select * from emp where eno=100

b)It initializes a SqlDataReader/OleDbDataReader variable which can then

be used to read the data returned.

What is difference between constants, read-only and, static?

Constants: The value can’t be changed
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.

What is the difference between application exception and system exception?

Ans: The difference between application exception and system exception is that system exceptions are thrown by CLR and application exceptions are thrown by applications.

What is the difference between authorization and authentication?

Ans: Authorization is a process of allowing or denying resources to particular user or record

Declaration of authorization is
Sometimes authorization allows the unauthorized persons at that time we will use

Authentication means
Authentication is a process where we identify the credentials of user i.e. username, password and create an identity to mention user as an authenticated.

How to get the version of the assembly?

Ans: lbltxt.text=Assembly. GetExecutingAssembly().GetName().Version.ToString();

What is the location of Global Assembly Cache on the system?

Ans: c:\Windows\assembly

What is the serialization means?

Ans: Serialization is a process of converting object into a stream of bites.

What is synchronization?

Ans: The mechanism needed to block one thread access to the data. If the data is being accessed by another thread.
Synchronization can be accessed by using system.monitor class
A monitor class methods are enter, exit, pulse for this lock statement is also used
Suppose if we need to synchronize some data at that time we need to place that data in this block
Lock
{
}
Whatever the data has been placed into the lock block that data has been blocked

What are the thread priority levels?
Ans: Thread priority levels are five types
0 - Zero level
1 - Below Normal
2 - Normal
3 - Above Normal
4 - Highest
By Default priority level is 2

What is the difference between .tostring(), Convert.tostring()?

Ans: The basic difference between them is “Convert” function handles NULLS while
“.ToString()” does not it will throw a NULL reference exception error. So as a good coding
practice using “convert” is always safe.

How many web.config files are there in 1 project?

Ans: There might be multiple web.config files for a single project depending on the hierarchy of folders inside the root folder of the project, so for each folder we can use one web.config file

What is the difference between throw and throw ex?

What is the difference between view state and hidden field?

Ans: viewstate is secured hidden field is insecure
Viewstate will store large amount of data but hidden filed will store small amount of data.

What is the Difference between read only and constant variables?

Ans: Read only can assign the values at runtime only.
Constant will assign the values at compile time only.
We cannot modify the both variable values.

What is static keyword in .Net?

Ans: Static is same as constant variable but we can change the value of static variable and we can access the variables without creating any instances


Continue.............