jQuery Show Popup on Page Load

17 Sep 2012

Stop auto-fill in browsers for textbox


Today’s browsers like Chrome, Firefox, Internet Explorer and Safari has functionality of auto complete values in TextBoxes. If you have enabled this features in your browser, then each and every time when you start to enter value in TextBox you get a drop down of prefilled values in that TextBox. This feature of browser can be disabled by the programming for a specific web form like payment form and other confidential information form of a web application.
In chrome browser, we can enable auto-fill as shown below:
Suppose we have a below form for online payment of product by credit card or debit card then it is mandatory to stop auto complete functionality of browser so that browser doesn’t save the confidential information of a customer’s credit card or debit card.
We can turn off auto-fill for our complete form by setting autocomplete attribute value to off as shown below:
<form id="Form1" method="post" runat="server" autocomplete="off">
</form>
We can also turn off auto-fill for a particular TextBox by setting autocomplete attribute value to off as shown below:
<asp:TextBox Runat="server" ID="txtConfidential" autocomplete="off">
</form>
We can also do this from code behind also like as:
txtConfidential.Attributes.Add("autocomplete", "off");










16 Sep 2012

Maintain Scroll Position on Postback in ASP.NET 2.0


This article shows how to allows pages to automatically maintain the current scroll position across postbacks.
The MaintainScrollPositionOnPostback page directive attribute allows to do that.
This feature is useful for large pages where scrolling is necessary to view input controls down further on the page.
There are three ways of applying the property to a web page.
  1. You can set it programmatically 
    Page.MaintainScrollPositionOnPostBack = true;
  2. In the page declaration 
    <%@ Page MaintainScrollPositionOnPostback="true" %>
  3. Or in the web.configs <system.web> section. 
    <pages maintainScrollPositionOnPostBack="true" />
This feature is an absolute must-have on large web pages built for postback scenarios.
A simple but very useful feature.
Smartnavigation = true  implemented the same feature in 1.1 framework 
SmartNavigation only had "issues" and it only worked in IE but the new MaintainScrollPositionOnPostback apparently works in most common browsers. 

12 Sep 2012

Sealed classes and Sealed methods in C#.NET


Sealed classes and Sealed methods in C#.NET



Sealed Classes


When you want to restrict your classes from being inherited by others you can create the class as sealed class.

To create a class as sealed class, create the class using the keyword sealed.

[Access Modifier] sealed class classname
{
}

Sealed Methods 
The virtual nature of a method persists for any number of levels of inheritance.

For example there is a class “A” that contains a virtual method “M1”. Another class “B” is inherited from “A” and another class “C” is inherited from “B”. In this situation class “C” can override the method “M1” regardless of whether class “B” overrides the method “M1”.

At any level of inheritance, if you want to restrict next level of derived classes from overriding a virtual method, then create the method using the keyword sealed along with the keywordoverride.

[Access Modifier] sealed override returntype methodname([Params])
{
}

Different Types of Inheritance

Creating a new class from existing class is called as inheritance.

What is Inheritance in C#

Inheritance can be classified to 5 types.
  1. Single Inheritance
  2. Hierarchical Inheritance
  3. Multi Level Inheritance
  4. Hybrid Inheritance
  5. Multiple Inheritance
1. Single Inheritance

when a single derived class is created from a single base class then the inheritance is called as single inheritance.


Different types of inheritance

Single Inheritance Example Program

2. Hierarchical Inheritance
when more than one derived class are created from a single base class, then that inheritance is called as hierarchical inheritance.

Hierarical Inheritance


3. Multi Level Inheritance
when a derived class is created from another derived class, then that inheritance is called as multi level inheritance.

Multi level Inheritance


4. Hybrid Inheritance
Any combination of single, hierarchical and multi level inheritances is called as hybrid inheritance.


Hybrid inheritance in C#


5. Multiple Inheritance
when a derived class is created from more than one base class then that inheritance is called as multiple inheritance. But multiple inheritance is not supported by .net using classes and can be done using interfaces.

Multiple inheritance in C#

  Multiple Inheritance Example

Handling the complexity that causes due to multiple inheritance is very complex. Hence it was not supported in dotnet with class and it can be done with interfaces.

Senior Level Interview Question and Answer .Net C Sharp


Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them. For more information, see Attributes.

Here's a simple example of Reflection using the static method GetType - inherited by all types from the Object base class - to obtain the type of a variable:

// Using GetType to obtain type information:
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);

The output is:


System.Int32


In this example, Reflection is used to obtain the full name of a loaded assembly:












// Using Reflection to get information from an Assembly:
System.Reflection.Assembly o = System.Reflection.Assembly.Load("mscorlib.dll");
System.Console.WriteLine(o.GetName());

The output is:

mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089











************************************************************************************************************
Method Overloading in C#.NET
The process of creating more than one method in a class with same name or creating a method in derived class with same name as a method in base class is called as method overloading.
In VB.net when you are overloading a method of the base class in derived class, then you must use the keyword “Overloads”. 
But in C# no need to use any keyword while overloading a method either in same class or in derived class.  While overloading methods, a rule to follow is the overloaded methods must differ either in number of arguments they take or the data type of at least one argument.
Example for Method Overloading
using System; namespace ProgramCall{     class Class1    {         public int Sum(int A, int B)        {            return A + B;        }         public float Sum(int A, float B)        {            return A + B;        }    }     class Class2 : Class1    {        public int Sum(int A, int B, int C)        {            return A + B + C;         }    }     class MainClass    {        static void Main()        {             Class2 obj = new Class2();             Console.WriteLine(obj.Sum(10, 20));             Console.WriteLine(obj.Sum(10, 15.70f));             Console.WriteLine(obj.Sum(10, 20, 30));             Console.Read();        }     }}
Output
3025.760
Note Method overloading provides more than one form for a method. Hence it is an example for polymorphism. 
In case of method overloading, compiler identifies which overloaded method to execute based on number of arguments and their data types during compilation it self. Hence method overloading is an example for compile time polymorphism.
*****************************************************************
Method Overriding in C#.NET
Creating a method in derived class with same signature as a method in base class is called as method overriding.
Same signature means methods must have same name, same number of arguments and same type of arguments. Method overriding is possible only in derived classes, but not within the same class.  When derived class needs a method with same signature as in base class, but wants to execute different code than provided by base class then method overriding will be used.
To allow the derived class to override a method of the base class, C# provides two options,virtual methods and abstract methods.
Examples for Method Overriding in C#
using System; namespace methodoverriding {     class BaseClass    {         public virtual  string YourCity()         {             return "New York";         }     }     class DerivedClass : BaseClass    {         public override string YourCity()         {             return "London";         }     }     class Program    {                  static void Main(string[] args)         {             DerivedClass obj = new DerivedClass();             string city = obj.YourCity();             Console.WriteLine(city);             Console.Read();         }     } }
Output London Example - 2 implementing abstract method
using System; namespace methodoverridingexample {     abstract class BaseClass    {         public abstract  string YourCity();              }     class DerivedClass : BaseClass    {         public override string YourCity()   //It is mandatory to implement absract method        {             return "London";         }         private int sum(int a, int b)         {             return a + b;         }     }     class Program    {                  static void Main(string[] args)         {             DerivedClass obj = new DerivedClass();             string city = obj.YourCity();             Console.WriteLine(city);             Console.Read();         }     } }
Output London
*****************************************************************Inheritance in C#
Creating a new class from existing class is called as inheritance. 
    //All the car properties can be used by the supercar
    class SuperCar : car
    {
  
    }
When a new class needs same members as an existing class, then instead of creating those members again in new class, the new class can be created from existing class, which is called as inheritance. Main advantage of inheritance is reusability of the code. During inheritance, the class that is inherited is called as base class and the class that does the inheritance is called as derived class and every non private member in base class will become the member of derived class. If you want the base class members to be accessed by derived class only , you can apply access modifier Protected to the base class member. There are 5 Different types of inheritance. Syntax
[Access Modifier] class ClassName : baseclassname
{ 
}

C# Inheritance Example

//Example program demonstrates singular inheritance
using System;
namespace ProgramCall
{
    class BaseClass
    {
        //Method to find sum of give  2 numbers
        public int FindSum(int x, int y)
        {
            return (x + y);
        }
        //method to print given 2 numbers
        //When declared protected , can be accessed only from inside the derived class
        //cannot access  with the instance of  derived class
        protected void Print(int x, int y)
        {
            Console.WriteLine("First Number: " + x);
            Console.WriteLine("Second Number: " + y);
        }
    }
    class Derivedclass : BaseClass
    {
        public void Print3numbers(int x, int y, int z)
        {
            Print(x, y); //We can directly call baseclass members
            Console.WriteLine("Third Number: " + z);
        }
    }
 
    class MainClass
    {
        static void Main(string[] args)
        {
            //Create instance for derived class, so that base class members              // can also  be accessed
            //This is possible because  derivedclass is inheriting base class
            Derivedclass instance = new Derivedclass();
            instance.Print3numbers(30, 40, 50); //Derived class internally calls base class method.
            int sum = instance.FindSum(30, 40); //calling base class method with derived class instance
            Console.WriteLine("Sum : " + sum);
            Console.Read();
        }
    }
}
Output First Number: 30 Second Number: 40  Third Number: 50  Sum : 70
***********************************************************

What are Value Types and Reference Types in .Net

           According to MSDN,   A data type is a value type if it holds the data within its own memory allocation. A reference type contains a pointer to another memory location that holds the data. All the data types in .net are classified in to value types and reference types.  
  • The data types whose values are directly stored in stack memory area are called as value types and the data types whose values are stored in heap memory area and its address is stored in a variable in stack memory area are called as reference types.
  • Among all built in data types of .net string and object are reference type and all other data types are value types.
  • Among user defined data types, class, interface, delegate and arrays are reference type while structure and enumeration are value type.
Value Types---------------- Value types include the following:
  • All numeric data types
  • Boolean, Char, and Date
  • All structures, even if their members are reference types
  • Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong
Reference Types ----------------------Reference types include the following:
  • String
  • All arrays, even if their elements are value types
  • Class types
  • Delegates
***************************************************************************

Assembly in .NET


What is a .Net Assembly?
The .NET assembly is the standard for components developed with the Microsoft.NET. Dot NET assemblies may or may not be executable, i.e., they might exist as the executable (.exe) file or dynamic link library (DLL) file. All the .NET assemblies contain the definition of types, versioning information for the type, meta-data, and manifest. The designers of .NET have worked a lot on the component (assembly) resolution.
There are two kind of assemblies in .NET;
  • private 
  • shared

Private assemblies are simple and copied with each calling assemblies in the calling assemblies folder.
Shared assemblies (also called strong named assemblies) are copied to a single location (usually the Global assembly cache). For all calling assemblies within the same application, the same copy of the shared assembly is used from its original location. Hence, shared assemblies are not copied in the private folders of each calling assembly. Each shared assembly has a four part name including its face name, version, public key token and culture information. The public key token and version information makes it almost impossible for two different assemblies with the same name or for two similar assemblies with different version to mix with each other.
An assembly can be a single file or it may consist of the multiple files. In case of multi-file, there is one master module containing the manifest while other assemblies exist as non-manifest modules. A module in .NET is a sub part of a multi-file .NET assembly. Assembly is one of the most interesting and extremely useful areas of .NET architecture along with reflections and attributes, but unfortunately very few people take interest in learning such theoretical looking topics.

What are the basic components of .NET platform?

The basic components of .NET platform (framework) are:  
                  .Net Applications
        (Win Forms,Web Applications,Web Services)
         Data(ADO.Net) and XML Library
          FrameWork Class Library(FCL)      
        (IO,Streams,Sockets,Security,Reflection,UI)
       Common Language Runtime(CLR)
             (Debugger,Type Checker,JITer,GC)
                    Operating System
          (Windows,Linux,UNIX,Macintosh,etc.,)

Common Language Runtime (CLR):

The most important part of the .NET Framework is the .Net Common Language Runtime (CLR) also called .Net Runtime in short. It is a framework layer that resides above the Operating System and handles/manages the execution of the .NET applications. Our .Net programs don't directly communicate with the Operating System but through CLR. 

MSIL (Microsoft Intermediate Language) Code:

When we compile our .Net Program using any .Net compliant language like (C#, VB.NET, C++.NET) it does not get converted into the executable binary code but to an intermediate code, called MSIL or IL in short, understandable by CLR. MSIL is an OS and H/w independent code. When the program needs to be executed, this MSIL or intermediate code is converted to binary executable code, called native code. The presence of IL makes it possible the Cross Language Relationship as all the .Net compliant languages produce the similar standard IL code. 

Just In Time Compilers (JITers):

When our IL compiled code needs to be executed, CLR invokes JIT compilers which compile the IL code to native executable code (.exe or .dll) for the specific machine and OS. JITers in many ways are different from traditional compilers as they, as their name suggests, compile the IL to native code only when desired e.g., when a function is called, IL of function's body is converted to native code; just in time of need. So, the part of code that is not used by particular run is not converted to native code. If some IL code is converted to native code then the next time when its needed to be used, the CLR uses the same copy without re-compiling. So, if a program runs for sometime, then it won't have any just in time performance penalty. As JITers are aware of processor and OS exactly at runtime, they can optimize the code extremely efficiently resulting in very robust applications. Also, since JITer knows the exact current state of executable code, they can also optimize the code by in-lining small function calls (like replacing body of small function when its called in a loop, saving the function call time). Although, Microsoft stated that C# and .Net are not competing with languages like C++ in efficiency, speed of execution, JITers can make your code even faster than C++ code in some cases when program is run over extended period of time (like web-servers).

Framework Class Library (FCL):

.NET Framework provides huge set of Framework (or Base) Class Library (FCL) for common, usual tasks. FCL contains thousands of classes to provide the access to Windows API and common functions like String Manipulation, Common Data Structures, IO, Streams, Threads, Security, Network Programming, Windows Programming, Web Programming, Data Access, etc. It is simply the largest standard library ever shipped with any development environment or programming language. The best part of this library is they follow extremely efficient OO design (design patterns) making their access and use very simple and predictable. You can use the classes in FCL in your program just as you use any other class and can even apply inheritance and polymorphism on these.

Common Language Specification (CLS):

Earlier we used the term '.NET Compliant Language' and stated that all the .NET compliant languages can make use of CLR and FCL. But what makes a language '.NET compliant language'? The answer is Common Language Specification (CLS). Microsoft has released a small set of specification that each language should meet to qualify as a .NET Compliant Language. As IL is a very rich language, it is not necessary for a language to implement all the IL functionality, rather it meets the small subset of it, CLS, to qualify as a .NET compliant language, which is the reason why so many languages (procedural and OO) are now running under .Net umbrella. CLS basically addresses to language design issues and lays certain standards like there should be no global function declaration, no pointers, no multiple inheritance and things like that. The important point to note here is that if you keep your code within CLS boundary, your code is guaranteed to be usable in any other .Net language.

Common Type System (CTS):

.NET also defines a Common Type System (CTS). Like CLS, CTS is also a set of standards. CTS defines the basic data types that IL understands. Each .NET compliant language should map its data types to these standard data types. This makes it possible for the 2 languages to communicate with each other by passing/receiving parameters to/from each other. For example, CTS defines a type Int32, an integral data type of 32 bits (4 bytes) which is mapped by C# through int and VB.Net through its Integer data type.

Garbage Collector (GC):

CLR also contains Garbage Collector (GC) which runs in a low-priority thread and checks for un-referenced dynamically allocated memory space. If it finds some data that is no more referenced by any variable/reference, it re-claims it and returns the occupied memory back to the Operating System; so that it can be used by other programs as necessary. The presence of standard Garbage Collector frees the programmer from keeping track of dangling data.