Thursday, 14 November 2013

Generics



Generics
Generics is a new concept in .net 2.0 and this is similar to templates in C++. By using generics, you can create generic methods and generic classes.

Generic Methods
A generic method is a method that can operate on any type of data. For most of the algorithms, logic is same whatever the type of data is. Hence instead of creating one method for every data type, you can create only one method that can accept any type of arguments, which is called as generic method. To create a method as generic method, syntax is as follows.
            [Access Modifier] returntype MethodName<GenericTypes>([Parameters])
            {
           
            }
After creating a generic method, to call the generic method syntax is as follows.
                                    MethodName<DataType>([Arguments])

Example : The following example creates a method Swap() as a generic method that can swap two values that can be of any type.

namespace Generics
{
    class Program
    {
        public static void Swap<MyType>(ref MyType X, ref MyType Y)
        {
            MyType T;
            T = X;
            X = Y;
            Y = T;
        }
        static void Main(string[] args)
        {
            int A = 10, B = 20;
            float F1 = 3.5F, F2 = 5.5F;
            string S1 = "Naresh", S2 = "Microsoft";
            Swap<int>(ref A, ref B);
            Swap<float>(ref F1, ref F2);
            Swap<string>(ref S1, ref S2);
            Console.WriteLine("After Swap ...");
            Console.WriteLine("A = {0}\tB = {1}", A, B);
            Console.WriteLine("F1 = {0}\tF2 = {1}", F1, F2);
            Console.WriteLine("S1 = {0}\tS2 = {1}", S1, S2);
        }
    }
}
Constraints On Generic Types
A generic type by default can accept any type of data. But there are some situations where you have to restrict your generic type to accept only certain types and for this you have to specify constraints on generic types. To specify constraints on generic types, you have to use the keyword where at the end of the method declaration as follows

[Access Modifier] returntype MethodName<GT>([Parameters]) where GT : constraints
{
           
}

You can specify the following constraints on generics.
  1. Struct : this makes the generic type accept only value types.
  2. Class : this makes the generic type accept only reference types.
  3. <classname> : this makes the generic type accept only that particular class and its derived classes.
  4. <interfacename> : this makes the generic type accept only the types that implement that interface.
  5. You can specify multiple constraints on generic types by separating them with comma(,). But combination of constraints like struct and class are not allowed as there is no type in .net that is both value type and reference type.

Example : The following example creates a method Sort() as generic method that can sort any type of array.

namespace Generics
{
    class GenSort
    {
        public static void Sort<MyType>(params MyType[] A) where MyType : IComparable
        {
            MyType T;
            for (int i = 0; i < A.GetLength(0); i++)
            {
                for (int j = i + 1; j < A.GetLength(0); j++)
                {
                    if (A[i].CompareTo(A[j]) > 0)
                    {
                        T = A[i];
                        A[i] = A[j];
                        A[j] = T;
                    }
                }
            }
        }
        static void Main()
        {
            int[] A = { 23, 9, 17, 12, 3 };
            float[] F = { 27.32F, 56.66F, 32.21F, 17.76F, 21.21F };
            string[] S = { "Microsoft", "Sun", "Oracle", "Adobe", "Ibm" };
            Sort<int>(A);
            Sort<float>(F);
            Sort<string>(S);
            Console.WriteLine("After Sort Values In Arrays Are...");
            foreach (int n in A)
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
            foreach (float n in F)
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
            foreach (string n in S)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Multiple Generic Types
There may be a situation where you have to take more than one parameter for a generic method that are of different type. In this case generic method can be created with more than one generic type. Syntax is as follows.

[Access Modifier] returntype MethodName<GT1,GT2,…>([Parameters])
            {
           
            }

After creating a generic method with multiple generic types, to call the generic method syntax is as follows.

                        MethodName<DataType1,DataType2,…>([Arguments])

Example : The following example creates a method with the name Print() as a generic method that accepts two parameters of two different types.

namespace Generics
{
    class MultiGen
    {
        public static void Print<MyType1, MyType2>(MyType1 X, MyType2 Y)
        {
            Console.WriteLine("X = {0}\tY = {1}", X, Y);
        }
        static void Main()
        {
            Print<int, float>(10, 14.5F);
            Print<float, string>(23.34F, "Naresh");
            Print<string, string>("Microsoft", "Naresh");
        }
    }
}
Generic Methods With Parameters of Standard types
When the method is declared as generic method then it is not compulsory that every parameter of that method must be of generic type. A generic method can have the parameters of standard type and for these parameters you must pass only that particular type of arguments.

Example : the following example creates a method with the name “Print” as a generic method that takes one generic type parameter and one int parameter.

namespace Generics
{
    class StandardTypes
    {
        static void Print<MyType>(MyType X, int N)
        {
            for (int i = 0; i < N; i++)
            {
                Console.Write("{0}\t", X);
            }
            Console.WriteLine();
        }
        static void Main()
        {
            Print<int>(3, 5);
            Print<string>("*", 5);
            Print<double>(5.7, 3);
        }
    }
}

Generic Classes
Not only methods, classes can also be created as generic classes. A generic class is a class whose instances each can work on a different type of data. For creating a class as generic class syntax is as follows.

                        [Access Modifier] class classname<generictypes>
                        {
                        }
After creating generic class, to create an instance for the generic class, syntax is as follows.

            Classname<Datatypes> ObjName = new classname<datatypes>();

Example : The following example creates a class with the name Test as generic class

namespace Generics
{
    class Test<MyType>
    {
        MyType A, B;
        public Test(MyType X, MyType Y)
        {
            A = X;
            B = Y;
        }
        public void Print()
        {
            Console.WriteLine("A = {0}\tB = {1}", A, B);
        }
    }
    class GenricClass
    {
        static void Main()
        {
            Test<int> T1 = new Test<int>(10, 20);
            Test<float> T2 = new Test<float>(3.5F, 4.5F);
            Test<string> T3 = new Test<string>("C#.Net", "VB.Net");
            T1.Print();
            T2.Print();
            T3.Print();
        }
    }
}

You can specify constraints on generic types in generic classes also and for this purpose syntax is as follows.

                        [Access Modifier] class classname<GT> where GT : constraints
                        {

                        }

A generic class can also be created with more than one generic type same as a generic method and has the following syntax.

                        [Access Modifier] class classname<GT1,GT2,…>
                        {

                        }

When a generic class is created with more than one generic type then an instance is created for that class as follows.

Classname<DT1,DT2,…> Objname = new classname<DT1,DT2,…>();

Exception Handling


Exception Handling

Errors in any language are classified into Compile Time Errors, Runtime Errors and Logical Errors.

Compile Time Errors
Compile time errors are the errors that are found during compilation. In general these errors are syntactical errors in the program. It is not possible to execute the program without rectifying the compile time errors. Hence exception handling is not related to compile time errors.

Runtime Errors
Runtime errors are the errors that occur at runtime i.e. while executing the program. These are also called exceptions. When an exception occurs then the program will be terminated abnormally without giving a proper message to the user regarding the exception. Exception handling is used to handle exceptions and give proper message to the user regarding exception and avoid abnormal termination of the program. Exception handling in C# was based on the keywords try , catch, finally and throw.

Try block is used to write the statements that may cause an exception. When an exception was raised in the try block, then control will be taken to catch block where we have to write the exception handling code. Once control reaches the catch block it is not possible to take it back to try. The complete code in the try block will be executed only when there is no exception raised and the code in catch block is executed only when an exception was raised. But you may have the code to be executed both when an exception was raised and no exception was raised. Finally block is used to write this type of code that needs to be executed both when an exception was raised and no exception was raised. Throw is used to raise exceptions manual.

                                    Try
                                    {
                                               
                                    }
Catch
{

}
Finally
{

}
Example : The following example accepts two integers and performs division. If the value given for denominator is zero then an exception will be raised and the program handles this exception with exception handling.

namespace ExceptionHandling
{
    class Program
    {
        static void Main(string[] args)
        {
            int A, B, R;
            Console.WriteLine("Enter Two Integers");
            A = int.Parse(Console.ReadLine());
            B = int.Parse(Console.ReadLine());
            try
            {
                R = A / B;
                Console.WriteLine("Ratio Of {0} And {1} Is {2}", A, B, R);
            }
            catch (DivideByZeroException Ex)
            {
                Console.WriteLine("Division With Zero Not Possible");
            }
        }
    }
}

Handling Multiple Exceptions
Within a method there is possibility for more than one exception. In this case no need to write separate try…catch for each exception and related to a single try block you can create any number of catch blocks, one for each type of exception.

Example : The following example handles two exceptions dividebyzero exception and overflow exception that will be raised when the value given for variable is out of range for its data type.

namespace ExceptionHandling
{
    class MultipleExceptions
    {
        static void Main()
        {
            int A, B, R;
            Console.WriteLine("Enter Two Integers");
            try
            {
                A = int.Parse(Console.ReadLine());
                B = int.Parse(Console.ReadLine());
                R = A / B;
                Console.WriteLine("Ratio Of {0} And {1} Is {2}", A, B, R);
            }

           catch (DivideByZeroException Ex)
            {
                Console.WriteLine("Division With Zero Not Possible");
            }
            catch (OverflowException Ex)
            {
            Console.WriteLine("Value Must Be Within The Range Of Integer");
            }
                        catch (FormatException Ex)
            {
                Console.WriteLine("Value Must Be Numeric");
            }

            Console.Read();
        }
    }
}

Handling Any Type of Exception
A programmer will write the exception handling code for all the exceptions that are up to his expectation. But there is possibility for an exception that was not up to the expectation of the programmer. Hence exception handling will be complete only when there is a catch block that can catch any type of exception. For this you have to create the catch block by specifying the exception type as Exception. Every exception in .net is inherited from Exception class and hence it can catch any type of exception. This type of catch block must be the last catch in a series of catch blocks.

Example : The following example handles three exceptions dividebyzeroexception , overflowexception and FormatException and can also handle any other type of exception.

namespace ExceptionHandling
{
    class AnyException
    {
        static void Main()
        {
            int A, B, R;
            Console.WriteLine("Enter Two Integers");
            try
            {
                A = int.Parse(Console.ReadLine());
                B = int.Parse(Console.ReadLine());
                R = A / B;
                Console.WriteLine("Ratio Of {0} And {1} Is {2}", A, B, R);
            }
            catch (DivideByZeroException Ex)
            {
                Console.WriteLine("Division With Zero Not Possible");
            }
            catch (OverflowException Ex)
            {
            Console.WriteLine("Value Must Be Within The Range Of Integer");
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
            }
            Console.Read();
        }
    }
}

User Defined Exceptions
There may be a situation where system will not raise an exception for your requirement and you want to raise the exception manual. In this case you have to create a class for your exception and it must be inherited from Exception class. To raise the exception, use throw keyword.

Example : The following example creates a user defined exception that will be raised when user enters a negative value for either A or B.

namespace ExceptionHandling
{
    class MyException : Exception
    {
        public string MyMessage;
        public MyException(string Mes)
        {
            MyMessage = Mes;
        }
    }
    class UserExceptions
    {
        static void Main()
        {
            int A, B, R;
            Console.WriteLine("Enter Two Integers");
            try
            {
                A = int.Parse(Console.ReadLine());
                if(A<0)
                    throw new MyException("-ve Values Are Not Allowed");
                B = int.Parse(Console.ReadLine());
                if(B<0)
                    throw new MyException("-ve Values Are Not Allowed");
                R = A / B;
                Console.WriteLine("Ratio Of {0} And {1} Is {2}", A, B, R);
            }
            catch (DivideByZeroException Ex)
            {
                Console.WriteLine("Division With Zero Not Possible");
            }
            catch (OverflowException Ex)
            {
            Console.WriteLine("Value Must Be Within The Range Of Integer");
            }
            catch(MyException Ex)
            {
                Console.WriteLine(Ex.MyMessage);
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
            }           
            Console.Read();
        }
    }
}

Logical Errors
Logical error is an error that will not be found during compilation or at runtime and will cause the program output to be wron. To find and rectify the logical errors tracing and debugging is used. Executing the program step by step and finding logical errors is called as tracing and debugging. To execute the program step by step shortcut is F11.

Break Point
When you don’t want to execute entire program step by step and you want to execute only a particular method step by step then break points are used. When a break point is placed in the program then during execution when control reaches the break point then program will enter in to debug mode and from there you can execute the program step by step. Shortcut to place or remove a break point is F9.

Debug Tools
For debugging a .net application, debugging tools are provided and are as follows.

Watch Window : This can be used to add a variable to it and observe how the value of that variable changes while executing the program step by step. VS.net provides four watch windows and shortcuts to open watch windows are
CTRL + ALT + W, 1
CTRL + ALT + W, 2             
CTRL + ALT + W, 3
CTRL + ALT + W, 4
For adding a variable to the watch window, select the variable, right click on it and then choose add watch. Otherwise select the variable and drag and drop it in watch window. You can also modify the value of a variable in watch window. For this right click on the variable in watch window and choose edit value.

Locals Window : This is used to observe how the values of local variables of current method are changed as the program is executed step by step. There is no need to add variables to locals window and all local variables of the current method are automatically added to the locals window. Shortcut to open locals window is CTRL + ALT + V, L. Same as  watch window in locals window also you can edit the value of a variable.

Immediate Window : This is used to print the values of variable or expressions and even to change the values of variables. “?” is used to print the value of a variable or expression within the immediate window. To change the value of a variable, write the assignment statement. Shortcut to open immediate window is CTRL + ALT + I. advantage of this is you can execute your own expressions and it is available even at design time. But watch and locals windows are available only at runtime and they can be used only to observe values of variables and we cant write our own expressions.

Sunday, 10 November 2013

ASP.NET Page lifecycle


When the Page is requested for the first time
The Life Cycle of a page when requested for the first time:
Initializing: During this phase, the server creates an instance of the server control
Loading: During this phase, the instance of the control is loaded onto the page object in which it is defined.
PreRendering: During this phase, the control is updated with the changes made to it. This prepares the control for rendering.
Saving: During this phase, the state information of the control is saved. For example, if a value is set for the control during the Load event, it is embedded in the HTML tag that will be returned to the browser.
Rendering: During this phase, the server creates the corresponding HTML tag for the control.
Disposing: During this phase, all cleanup tasks, such as closing files and database connections opened by the control are performed.
Unloading: During this phase, all cleanup tasks, such as destroying the instances of server control are performed. This is the final event in the life cycle of a server control


Saturday, 9 November 2013

Remoting



Remoting

What distributed process frameworks outside .NET do you know?
Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model  (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).

What are possible implementations of distributed applications in .NET?
 .NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in  System.Runtime.Remoting and System.Web.Services.

When would you use .NET Remoting and when Web services?
Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for     open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.

What's a proxy of the server object in .NET Remoting?
 It's a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the  communication between real server object and the client object. This process is also known as marshaling.

Friday, 8 November 2013

Winforms



What base class do all Web Forms inherit from?
System.Windows.Forms.Form

What is the difference between Debug.Write and Trace.Write? When should each be used?
The Debug.Write call won't be compiled when the DEBUGsymbol is not defined (when doing a release build). Trace.Write calls will be compiled. Debug.Write is for information you want only in debug builds, Trace.Write is for when you want it in release build as well.

Difference between Anchor and Dock Properties?
Dock Property->Gets or sets which edge of the parent container a control is docked to. A control can be docked to one edge of its parent container or can be docked to all edges and fill the parent container. For example, if you set this property to DockStyle.Left, the left edge of the
control will be docked to the left edge of its parent control. Additionally, the docked edge of  the control is resized to match that of its container
control.
Anchor Property->Gets or sets which edges of the control are anchored to the edges of its container.  A control can be anchored to one or more edges of its parent container. Anchoring a control to its parent ensures that the anchored edges remain in the same position relative to the edges of the parent container when the parent container is resized.

When would you use ErrorProvider control?
ErrorProvider control is used in Windows Forms application. It is like Validation Control for ASP.NET pages. ErrorProvider control is used to provide validations in Windows forms and display user friendly messages to the user if the validation fails.
 E.g
 If we went to validate the textBox1 should be empty, then we can validate as below
 1). You need to place the errorprovide control on the form
 private void textBox1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
ValidateName();
}
private bool ValidateName()
{
bool bStatus = true;
if (textBox1.Text == "")
{
errorProvider1.SetError (textBox1,"Please enter your Name");
bStatus = false;
}
else
errorProvider1.SetError (textBox1,"");
return bStatus;
}
 it check the textBox1 is empty . If it is empty, then a message Please enter your name is displayed.

Can you write a class without specifying namespace? Which namespace does it belong to by default??
Yes, you can, then the class belongs to global namespace which has no name. For commercial products, naturally, you  wouldn't want global namespace.

You are designing a GUI application with a windows and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What's the problem? 
One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at  the same location when resized.

How can you save the desired properties of Windows Forms application? 
.config files in .NET are supported through the API to allow storing and retrieving information. They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.

So how do you retrieve the customized properties of a .NET application from XML .config file? 
Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.

Can you automate this process? 
In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.

My progress bar freezes up and dialog window shows blank, when an intensive background process takes over. 
Yes, you should've multi-threaded your GUI, with taskbar and main form being one thread, and the background process being the other.

What's the safest way to deploy a Windows Forms app?
Web deployment: the user always downloads the latest version of the code, the program runs within security sandbox, properly written app will not require additional security privileges.

Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio? 
The designer will likely through it away, most of the code inside InitializeComponent is auto-generated.

What's the difference between WindowsDefaultLocation and WindowsDefaultBounds?
WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.

What's the difference between Move and LocationChanged? Resize and SizeChanged? 
Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.

How would you create a non-rectangular window, let's say an ellipse? 
Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.

How do you create a separator in the Menu Designer? 
A hyphen '-' would do it. Also, an ampersand '&\' would underline the next letter.

How's anchoring different from docking? 
Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking  treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring.

How do you trigger the Paint event in System.Drawing?
Invalidate the current form, the OS will take care of repainting. The Update method forces the repaint.

With these events, why wouldn't Microsoft combine Invalidate and Paint, so that you wouldn't have to tell it to repaint, and then to force it to repaint?
Painting is the slowest thing the OS does, so usually telling it to repaint, but not forcing it allows for the process to take place in the background.

How can you assign an RGB color to a System.Drawing.Color object?
Call the static method FromArgb of this class and pass it the RGB values.

What class does Icon derive from? 
Isn't it just a Bitmap with a wrapper name around it? No, Icon lives in System.Drawing namespace. It's not a Bitmap by default, and is treated separately by .NET. However, you can use ToBitmap method to get a valid Bitmap object from a valid Icon object.

Before in my VB app I would just load the icons from DLL. How can I load the icons provided by .NET dynamically? 
By using System.Drawing.SystemIcons class, for example System.Drawing.SystemIcons.Warning produces an Icon with a  warning sign in it.

When displaying fonts, what's the difference between pixels, points and ems? 
A pixel is the lowest-resolution dot the computer monitor supports. Its size depends on user's settings and monitor size. A point is always 1/72 of an inch. An em is the number of pixels that it takes to display the letter M.

Popular Posts