Saturday, November 29, 2008

Static Member, Static Method, Static Constructor

Static Members of the class
“static members” belong to the whole class rather than to individual object

How to access static member of class?
Static members are accessed with the name of class rather than reference to objects. Example: className.StaticMemberName

Example of Static Member

class Test
{
public int rollNo;
public int mathsMarks;
public static int totalMathMarks;
}

class TestDemo
{
public static void main()
{
Test stud1 = new Test();
stud1.rollNo = 1;
stud1.mathsMarks = 40;

stud2.rollNo = 2;
stud2.mathsMarks = 43;

Test.totalMathsMarks = stud1.mathsMarks + stud2.mathsMarks;
}
}



Static Method of the class
- Static Method is Method that you can call directly without first creating an instance of a class. Example: Main() Method, Console.WriteLine()
- You can use static fields, methods, properties and even constructors which will be called before any instance of the class is created.
- As static methods may be called without any reference to object, you can not use instance members inside static methods or properties, while you may call a static member from a non-static context. The reason for being able to call static members from non-static context is that static members belong to the class and are present irrespective of the existence of even a single object.


Static Constructor
In C# it is possible to write a static no-parameter constructor for a class. Such a class is executed once, when first object of class is created.

One reason for writing a static constructor would be if your class has some static fields or properties that need to be initialized from an external source before the class is first used.
Example
Class MyClass
{
static MyClass()
{
//Initialization Code for static fields and properties.
}
}

What is Difference between == and .Equals() Method?

What is Difference between == and .Equals() Method?



For Value Type: == and .Equals() method usually compare two objects by value.

For Example:

int x = 10;

int y = 10;

Console.WriteLine( x == y);

Console.WriteLine(x.Equals(y));


Will display:

True

True




For Reference Type: == performs an identity comparison, i.e. it will only return true if both references point to the same object. While Equals() method is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent.

For Example:


StringBuilder s1 = new StringBuilder(“Yes”);

StringBuilder s2 = new StringBuilder(“Yes”);

Console.WriteLine(s1 == s2);

Console.WriteLine(s1.Equals(s2));


Will display:

False

True


In above example, s1 and s2 are different objects hence “==” returns false, but they are equivalent hence “Equals()” method returns true. Remember there is an exception of this rule, i.e. when you use “==” operator with string class it compares value rather than identity.


When to use “==” operator and when to use “.Equals()” method?

For value comparison, with Value Tyep use “==” operator and use “Equals()” method while performing value comparison with Reference Type.

SQL Optimization Tips

SQL Optimization Tips

• Use views and stored procedures instead of heavy-duty queries.
This can reduce network traffic, because your client will send to
server only stored procedure or view name (perhaps with some
parameters) instead of large heavy-duty queries text. This can be used
to facilitate permission management also, because you can restrict
user access to table columns they should not see.

• Try to use constraints instead of triggers, whenever possible.
Constraints are much more efficient than triggers and can boost
performance. So, you should use constraints instead of triggers,
whenever possible.

• Use table variables instead of temporary tables.
Table variables require less locking and logging resources than
temporary tables, so table variables should be used whenever possible.
The table variables are available in SQL Server 2000 only.

• Try to use UNION ALL statement instead of UNION, whenever possible.
The UNION ALL statement is much faster than UNION, because UNION ALL
statement does not look for duplicate rows, and UNION statement does
look for duplicate rows, whether or not they exist.

• Try to avoid using the DISTINCT clause, whenever possible.
Because using the DISTINCT clause will result in some performance
degradation, you should use this clause only when it is necessary.

• Try to avoid using SQL Server cursors, whenever possible.
SQL Server cursors can result in some performance degradation in
comparison with select statements. Try to use correlated sub-query or
derived tables, if you need to perform row-by-row operations.

• Try to avoid the HAVING clause, whenever possible.
The HAVING clause is used to restrict the result set returned by the
GROUP BY clause. When you use GROUP BY with the HAVING clause, the
GROUP BY clause divides the rows into sets of grouped rows and
aggregates their values, and then the HAVING clause eliminates
undesired aggregated groups. In many cases, you can write your select
statement so, that it will contain only WHERE and GROUP BY clauses
without HAVING clause. This can improve the performance of your query.

• If you need to return the total table's row count, you can use
alternative way instead of SELECT COUNT(*) statement.
Because SELECT COUNT(*) statement make a full table scan to return the
total table's row count, it can take very many time for the large
table. There is another way to determine the total row count in a
table. You can use sysindexes system table, in this case. There is
ROWS column in the sysindexes table. This column contains the total
row count for each table in your database. So, you can use the
following select statement instead of SELECT COUNT(*): SELECT rows
FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2 So,
you can improve the speed of such queries in several times.

• Include SET NOCOUNT ON statement into your stored procedures to stop
the message indicating the number of rows affected by a T-SQL statement.
This can reduce network traffic, because your client will not receive
the message indicating the number of rows affected by a T-SQL statement.

• Try to restrict the queries result set by using the WHERE clause.
This can results in good performance benefits, because SQL Server will
return to client only particular rows, not all rows from the table(s).
This can reduce network traffic and boost the overall performance of
the query.

• Use the select statements with TOP keyword or the SET ROWCOUNT
statement, if you need to return only the first n rows.
This can improve performance of your queries, because the smaller
result set will be returned. This can also reduce the traffic between
the server and the clients.

• Try to restrict the queries result set by returning only the
particular columns from the table, not all table's columns.
This can results in good performance benefits, because SQL Server will
return to client only particular columns, not all table's columns.
This can reduce network traffic and boost the overall performance of
the query.
1.Indexes
2.avoid more number of triggers on the table
3.unnecessary complicated joins
4.correct use of Group by clause with the select list
5 In worst cases Denormalization


Index Optimization tips

• Every index increases the time in takes to perform INSERTS, UPDATES
and DELETES, so the number of indexes should not be very much. Try to
use maximum 4-5 indexes on one table, not more. If you have read-only
table, then the number of indexes may be increased.

• Keep your indexes as narrow as possible. This reduces the size of
the index and reduces the number of reads required to read the index.

• Try to create indexes on columns that have integer values rather
than character values.

• If you create a composite (multi-column) index, the order of the
columns in the key are very important. Try to order the columns in the
key as to enhance selectivity, with the most selective columns to the
leftmost of the key.

• If you want to join several tables, try to create surrogate integer
keys for this purpose and create indexes on their columns.

• Create surrogate integer primary key (identity for example) if your
table will not have many insert operations.

• Clustered indexes are more preferable than nonclustered, if you need
to select by a range of values or you need to sort results set with
GROUP BY or ORDER BY.

• If your application will be performing the same query over and over
on the same table, consider creating a covering index on the table.

• You can use the SQL Server Profiler Create Trace Wizard with
"Identify Scans of Large Tables" trace to determine which tables in
your database may need indexes. This trace will show which tables are
being scanned by queries instead of using an index.

• You can use sp_MSforeachtable undocumented stored procedure to
rebuild all indexes in your database. Try to schedule it to execute
during CPU idle time and slow production periods.
sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?')"

Saturday, November 22, 2008

In which Scenario you will go for Interface or Abstract Class

In which Scenario you will go for Interface or Abstract Class

when u want to go for inheritance in so many derived classes but the methods implementations are different for different derived classes then u will make the class as abstract or interface. When all the method's implementations are based on derived class u will go for interface and if few implementations are common and remaining depends on derived class u will go for abstract class where u can have defined as well as declared methods also. Note: abstract and interface classes are used when their methods are mandatory for derived classes and are not optional. They put restriction on derived classes that they cannot skip those methods withoud having them in it.
Abstract class can or cannot have methods in it and it cannot be instatiated.It has to be inherited for use .
Abstract class can be used when you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.

Interface - group of related methods with only signatures of methods .

Interface are implemented whereas Abstract classes are inherited.

When you need some classes to use some methods which you don't want to be included in the class ,then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
But you are forced to implement all the methods defined in the interface , even if you dont need some of them.

Sunday, November 16, 2008

FAQ in Static

1. What is a static class?
static class is a class declared with the keyword static
eg:

public static class Employee()
{

}

you cannot declare an instance member inside a static class
ie static class members also should static
eg:

public static class Employee()
{
private static string _address;

public static String GetName()
{
string x = "Saikat";
return x;
}
}

you cannot create an instance of this static class
so if you want to call the members inside a static class you have to call like

Employee.GetName();
2. What is static member?
A static member is a variable which shares the common memory for every object.Static variable is automatically initialized to zero.We can call static member in three ways

1>directly by specifying variable name.
2>by using class name.
3>by using object also.

Example on static member:

class ABC
{
static int i=2;
public void Increment()
{
i++;
}
public void Display()
{
MessageBox.Show(i.toString());
}
}
private void button1_click()
{
ABC obj;
obj.Increment();
obj.Display();
obj.Display();
}

o/p:3
o/p:4

3. What is static function?
Static function can only access static members. You cannot modify the definition of the function once you intialize.
--------
A static function is a function which contains only static variables.
We can call static function without creating object also.We can call static function in three ways as follows

1>directly by writing function name.
2>by using class name.
3>by using object also.

4. What is static constructor?
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only.
----------
A static constructor will run ONLY once and that once will be when the class is FIRST used.

So, in your case, if anybody goes:

Log log = new Log();

The static constructor will run first, and then the default (or any other constructor) will run. If more instances are created, the static constructor WILL NOT BE CALLED AGAIN.

Now, suppose, in your Log class you have a static method called SayHellokannan();

If anyone calls Log.SayHellokannan() this is what will happen:

If the class Log has not been used before (either instantiated or had a static method called), i.e. the static constructor has not fired yet, then the static constructor will be called. After that, the SayHellokannan method will be called. If the static constructor has already been run once (either by instantiation or by having a static method called), only the SayHellokannan Method will be called.

So, in any case, the static constructor runs only when the class is first used. And it runs before any other method or constructor that first time.

5. How can we inherit a static variable?

We can't inherit a static member or variable.Static member occupies a separate memory and is shared by every object.

6. How can we inherit a static member?

We can't inherit a static member. Static member occupies a separate memory and is shared by every object.

7. Can we use a static function with a non-static variable?

No
Static Function in bound to class. So you can not access non static (instance) variable from that function.
--------

public class Employee
{
private string _empName = "saikat":

public static String GetName()
{
return _empName
}
}

This is not correct. Because i used a nonstatic variable inside a static function. This will make error.

see another eg:

public class Employee
{
private static string _empName = "Saikat":

public static String GetName()
{
return _empName
}
}

This is the correct way

But u can use a nonstatic variable inside a function like this

public class Employee
{

public static String GetName()
{
string _empName = "Saikat":
return _empName
}
}

8. How can we access static variable?

Static variables are assinge to class and not to an instance.
public class A
{
static int var1;
}

public class B
{
A InstOfA = new A();
//But when you want to access static variable use class name
A.var1;
//Do not use InstOfA.var1
}

So Static variable is acessed as ClassName.variableName
The static variables are shared by all the objects of a class where they are declared.so their exits only one copy of a static variable.To access them you use classname. this holds good for static functons also.

classname.static_variablename


class one
{
static i;
int a;
}

class two
{

one o=new one();
one.i=10; // initializing the static variable
o.a=20; // initializing the data member
}

9. Why main function is static?

We are writing main function as static because main function is written inside a class ans also the starting point of the program,so we have to call without creating a object of it that's why we make it static .Static function can be call without creating object also.

ENUM

The enum is used to declare an enumeration.

Example
enum Numbers{Zero, One, Two, Three};

Enum is a type consisting of a set of named constants called the enumerator list. By default, the first has the value 0, and the value of each successive is increased by 1.

Here Zero = 0, One = 1, Two = 2 ...

But you can force the Starting Value like

enum Numbers{Zero=10, One, Two, Three};

Here Zero = 10, One = 11, Two = 12 ...

Saturday, November 15, 2008

Properties

Properties
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.
In this example, the class TimePeriod stores a time period. Internally the class stores the time in seconds, but a property called Hours is provided that allows a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

class TimePeriod
{
private double seconds;
public double Hours
{
get
{
return seconds / 3600;
}
set
{
seconds = value * 3600;
}
}}
class Program{
static void Main()
{
TimePeriod t = new TimePeriod(); // Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = 24; // Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine("Time in hours: " + t.Hours);
}}
Time in hours: 24

Interface Properties
public interface ISampleInterface
{ // Property declaration:
string Name
{
get;
set;
}}

Tuesday, November 11, 2008

ASP.NET Inerview Questions

1. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.

inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

2. What’s the difference between Response.Write() andResponse.Output.Write()?

Response.Output.Write() allows you to write formatted output.
3. What methods are fired during the page load?

Init() - when the page is instantiatedLoad() - when the page is loaded into server memoryPreRender() - the brief moment before the page is displayed to the user as HTMLUnload() - when page finishes loading.


4. When during the page processing cycle is ViewState available?

After the Init() and before the Page_Load(), or OnLoad() for a control.

5. What namespace does the Web page belong in the .NET Framework class hierarchy?

System.Web.UI.Page
6. Where do you store the information about the user’s locale?System.Web.UI.Page.Culture
7. What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?

CodeBehind is relevant to Visual Studio.NET only.
8. What’s a bubbled event?

When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.
9. Suppose you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler?

Add an OnMouseOver attribute to the button. Example: btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");
10. What data types do the RangeValidator control support?

Integer, String, and Date.
11. Explain the differences between Server-side and Client-side code?

Server-side code executes on the server. Client-side code executes in the client's browser.
12. What type of code (server or client) is found in a Code-Behind class?

The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.
13. Should user input data validation occur server-side or client-side? Why?

All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user.
14. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?

Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.
15. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

Valid answers are:· A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.· A DataSet is designed to work without any continuing connection to the original data source.· Data in a DataSet is bulk-loaded, rather than being loaded on demand.· There's no concept of cursor types in a DataSet.· DataSets have no current record pointer You can use For Each loops to move through the data.· You can store many edits in a DataSet, and write them to the original data source in a single operation.· Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
16. What is the Global.asax used for?

The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.
17. What are the Application_Start and Session_Start subroutines used for?

This is where you can set the specific variables for the Application and Session objects.
18. Can you explain what inheritance is and an example of when you might use it?

When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class could be derived from the Employee base class.
19. Whats an assembly?

Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN
20. Describe the difference between inline and code behind.

Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.
21. Explain what a diffgram is, and a good use for one?

The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.
22. Whats MSIL, and why should my developers need an appreciation of it if at all?

MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.
23. Which method do you invoke on the DataAdapter control to load your generated dataset with data?

The Fill() method.
24. Can you edit data in the Repeater control?

No, it just reads the information from its data source.
25. Which template must you provide, in order to display data in a Repeater control?

ItemTemplate.
26. How can you provide an alternating color scheme in a Repeater control?

Use the AlternatingItemTemplate.
27. What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control?

You must set the DataSource property and call the DataBind method.
28. What base class do all Web Forms inherit from?

The Page class.
29. Name two properties common in every validation control?

ControlToValidate property and Text property.
30. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?

DataTextField property.
31. Which control would you use if you needed to make sure the values in two different controls matched?

CompareValidator control.
How many classes can a single .NET DLL contain?It can contain many classes.

Sunday, November 9, 2008

Difference between int and Int32

Difference between int and Int32

Int32 is the System.Int32 class, while int is an alias for System.Int32.
The same applies for String (uppercase S) which is System.String, while string (lowercase S) is an alias for System.String.
So basically int is the same thing as Int32, and string is the same thing as Int32. It's down to user's preference which one to use but most prefer to use int and string as they are easier to type and more familiar among C++ programmers.

Its same only.

Thing is int is alias name for Int32.

Saturday, November 1, 2008

I want to Cache based on HTTP header .How can I do that?

<%@OutputCache … VaryByHeader=”UserAgent” %>
or
<%@ OutputCache … VaryByHeader=”Accept-Language” %>