e h

Embed Size (px)

Citation preview

  • 8/6/2019 e h

    1/30

    EventsAn event is the outcome of an action. There are two important terms with respectto events. The event source and the event receiver. The object that raises theevent is called event source and the object that responds to the event is calledevent receiver. Did you observe a hitch in the above explanation? O.K. my eventsource raises the event and my event receiver receives it, but what is thecommunication channel between them. Take the instance of you talking with afriend of yours over the telephone. Now you are the event source and your friend isthe event receiver and the telephone cable is the communication channel. Similarlythe communication channel between an event source and an event receiver is thedelegate .

    DelegatesIn C#, delegates act as an intermediary between an event source and an eventdestination.Delegates have other uses in addition to event handling. A delegate class used asan intermediary between an event source and event receiver is called an eventhandler. Types of DelegatesThere are basically two types of delegates. Single Cast delegate and Multi Castdelegate. A single cast delegate can call only one function. when the multi castdelegate is invoked it can call all the functions that form a part of the linked list.Assume that i have several clients who would like to receive notification when aparticular event occurs. Putting all of them in a multi cast delegate can help call allthe clients when a particular event occurs.To support a single cast delegate the base class library includes a special class typecalled System.Delegate . To support multi cast delegates the base class libraryincludes a special class type called System.MultiCastDelegate.

    Single Cast delegateThe signature of a single cast delegate is shown below. The letters in italics can bereplaced with your own names and parameters.

    public delegate Boolean DelegateName (parm1, parm2)

    W hen the compiler compiles the statement above, it internally generates a newclass type. This class is called DelegateName and derives from System.Delegate.Just to make sure just check the ILDisassembler code to check that this ishappening.As an example let us create a single cast delegate named MyDelegate which wouldpoint to a function MyFunction. The code appears as below,

    Collapsepublic delegate Boolean MyDelegate(Object sendingobj, Int32 x);

    public class TestDelegateClass{

    Boolean MyFunction(Object sendingobj, Int32 x){

    //Perform some processing

  • 8/6/2019 e h

    2/30

    return (true);

    }

    public static void main(String [] args){

    //Instantiate the delegate passing the method to invoke in itsconstructor

    MyDelegate mdg = new MyDelegate(MyFunction);

    // Construct an instance of this class

    TestDelegateClass tdc = new TestDelegateClass();

    // The following line will call MyFunction

    Boolean f = mdg(this, 1);

    }}H ow does the above code work?The System.Delegate contains a few fields. The most important of them are Targetand Method.The Target field identifies an object context. In the scenario above this would pointto the TestDelegateClass being created. If the method to be invoked is a staticmethod then this field will be null.The Method field identifies the method to be called. This field always has some

    value. It is never null.To the intelligent reader, if you observe the IL Disassembler code you would seethat the constructor for MyDelegate contains two parameters. But in our case weare passing only one parameter? Any guesses on how this is done? Yeah you areright! It gets done internally by the compiler. The compiler resolves the call aboveto a call passing in the two parameters required. If you observe in C++ withmanaged extension, the object and the address of the function have to be passedexplicitly. But in VB and C# we have done away with this with the compiler filling inthe necessary details.In the code sample above we saw,

    CollapseBoolean f = mdg(this, 1);W hen the compiler comes across this line, this is what happens,The compiler identifies that mdg is a delegate object.The delegate object has the target and method fields as described above.The compiler generates code that calls the Invoke method of the System.Delegatederived class i.e MyDelegate.The Invoke method internally uses the MethodInfo type identified by the delegate'sMethod field and calls the MethoidInfo's invoke method.

  • 8/6/2019 e h

    3/30

    The MethodInfo's invoke method is passed the delegates Target field whichidentifies the method and an array of variants which contains the parameters to themethod to be called. In our case, the array of variants would be an Object and anInt32 value.The above discussion would have made you clear about what happens internallywhen a method gets called through a Single Cast delegate.

    Multi Cast delegateThe signature of a mutli cast delegate is shown below. The letters in italics can bereplaced with your own names and parameters.

    public delegate void DelegateName (parm1, parm2)

    W hatever has been explained with respect to Single cast delegate holds good evenin the context of a Multi Cast Delegate. There is a small addition here. Since a multicast delegate represents a linked list, there is an additional field called prev whichrefers to another Multi Cast Delegate. This is how the linked list is maintained.The return type if you have observed has changed from Boolean to void. Have youguessed the reason as to why it happens? The reason is that since several multicast delegates get called consecutively we cannot wait to get the return value fromeach of these methods being called.The code shown in the example for single cast delegate will work in the case of multi cast delegate too. The only difference is that the delegate signature needs tobe changed, the method signature needs to be changed to return void instead of Boolean.The power of multi cast delegates come in when you combine delegates to form alinked list. The Combine method is available in the System.Delegate class as astatic method. The function signature as follows.

    Collapsepublic static Delegate Combine(Delegate a, Delegate b);W hat the above method does is that it combines the two delegates a and b andmakes b's prev field point to a. It returns the head of the linked list. This in turnhas to be type casted to our delegate type.Similar to the Combine method we have a remove method which removes adelegate from the linked list and gives you the modifies smaller linked list with apointer to the head. The signature of the remove method is as follows,

    Collapsepublic static Delegate Remove(Delegate source, Delegate value);Here's a small sample that illustrates the use of a multi cast delegate,

    Collapseusing System;

    class MCD1{

    public void dispMCD1(string s){

    Console. W riteLine("MCD1");}

  • 8/6/2019 e h

    4/30

    }

    class MCD2{

    public void dispMCD2(string s){

    Console. W riteLine("MCD2");}

    }

    public delegate void OnMsgArrived(string s);

    class TestMultiCastUsingDelegates{

    public static void Main(string [] args){

    MCD1 mcd1=new MCD1();MCD2 mcd2=new MCD2();

    // Create a delegate to point to dispMCD1 of mcd1 object

    OnMsgArrived oma=new OnMsgArrived(mcd1.dispMCD1);

    // Create a delegate to point to dispMCD2 of mcd2 object

    OnMsgArrived omb=new OnMsgArrived(mcd2.dispMCD2);

    OnMsgArrived omc; // Combine the two created delegates. Now omc would point to the head of a

    linked list

    // of delegates

    omc=(OnMsgArrived)Delegate.Combine(oma,omb);

    Delegate [] omd; // Obtain the array of delegate references by invoking GetInvocationList()

    omd=omc.GetInvocationList();

    OnMsgArrived ome; // Now navigate through the array and call each delegate which in turn would

    call each of the

    // methods

  • 8/6/2019 e h

    5/30

    for(int i=0;i

    All of the above HTTP modules are used by ASP.NET to provide services likeauthentication and authorization, session management and output caching. Sincethese modules have been registered in machine.config file, these modules areautomatically available to all of the W eb applications.Implementing an HTTP Module for Providing Security ServicesNow we will implement an HTTP module that provides security services for our W ebapplication. Our HTTP module will basically provide a custom authentication service.It will receive authentication credentials in HTTP request and will determinewhether those credentials are valid. If yes, what roles are the user associated with?Through the User.Identity object, it will associate those roles that are accessible toour W eb application pages to the user's identity.Following is the code of our HTTP module.

    using System;using System. W eb;

  • 8/6/2019 e h

    6/30

    using System.Security.Principal;

    namespace SecurityModules{ /// /// Summary description for Class1. ///

    public class CustomAuthenticationModule : IHttpModule{public CustomAuthenticationModule(){}public void Init(HttpApplication r_objApplication){ // Register our event handler with Application object.r_objApplication.AuthenticateRequest +=

    new EventHandler(this.AuthenticateRequest) ;}

    public void Dispose(){ // Left blank because we dont have to do anything.}

    private void AuthenticateRequest(object r_objSender,EventArgs r_objEventArgs)

    {

    // Authenticate user credentials, and find out user roles.1. HttpApplication objApp = (HttpApplication) r_objSender ;2. HttpContext objContext = (HttpContext) objApp.Context ;3. if ( (objApp.Request["userid"] == null) ||4. (objApp.Request["password"] == null) )5. {6. objContext.Response. W rite("Credentials not provided") ;7. objContext.Response.End() ;8. }

    9. string userid = "" ;10. userid = objApp.Request["userid"].ToString() ;11. string password = "" ;12. password = objApp.Request["password"].ToString() ;

    13. string[] strRoles ;14. strRoles = AuthenticateAndGetRoles(userid, password) ;15. if ((strRoles == null) || (strRoles.GetLength(0) == 0))16. {17. objContext.Response. W rite(" W e are sorry but we could not

  • 8/6/2019 e h

    7/30

  • 8/6/2019 e h

    8/30

    therefore, these credentials are not valid. So, an error message is sent to the clientand the request is completed.Line 20 and Line 21 are very important because these lines actually inform theASP.NET HTTP runtime about the identity of the logged-in user. Once these linesare successfully executed, our aspx pages will be able to access this information byusing the User object.Now let's see this authentication mechanism in action. Currently we are onlyallowing the following users to log in to our system:User id = Steve, Password = 15seconds, Role = AdministratorUser id = Mansoor, Password = mas, Role = UserNote that user id and password are case-sensitive.First try logging-in without providing credentials. Go tohttp://localhost/webapp2/index.aspx and you should see the following message.

    Now try logging-in with the user id "Steve" and password "15seconds". Go tohttp://localhost/webapp2/index.aspx?userid=Steve&password=15seconds and youshould see the following welcome message.

    Now try to log-in with the user id "Mansoor" and password "15seconds". Go tohttp://localhost/webapp2/index.aspx?userid=Mansoor&password=mas and youshould see the following welcome page.

  • 8/6/2019 e h

    9/30

    Now try to log-in with the wrong combination of user id and password. Go tohttp://localhost/webapp2/index.aspx?userid=Mansoor&password=xyz and youshould see the following error message.

    This shows our security module in action. You can generalize this security moduleby using database-access code in the AuthenticateAndGetRoles method.For all of this to work, we have to perform some changes in our web.config file.First of all, since we are using our own custom authentication, we don't need anyother authentication mechanism. To specify this, change the nodein web.config file of webapp2 to look like this:

    Similarly, don't allow anonymous users to our W eb site. Add the following toweb.config file:

    Users should at least have anonymous access to the file that they will use for

    providing credentials. Use the following configuration setting in the web.config filefor specifying index.aspx as the only anonymously accessible file:

  • 8/6/2019 e h

    10/30

    ConclusionAs you might have realized with HTTP handlers and modules, ASP.NET has put a lotof power in the hands of developers. Plug your own components into the ASP.NETrequest processing pipeline and enjoy the benefits.This article should at least get you started with these components. As an exercise,you might want to go and make this sample authentication module more flexibleand tune it according to your needs.

    U nderstanding Event H andling in .NE T

    In general terms, an event is the resultant outcome of an action. In theprogramming terms, when the user does some action such clicks a button then theuser is directed to some other window or dialog box.

    If clicking a button is an action thenthe outcome of that action is known

    as event. In .NET Framework an event enables objects in a class to notify otherobjects that an action has been performed and they should react to this. Events in.NET Framework are based on publisher-subscriber model. The class that issues orpublishes an event is called the publisher of the event and the class that registersto the published event is called the subscriber of the event.

    W hen talking about events you should be aware of three most important conceptsof events. They are event handlers, event arguments, and delegates. An event

    handler is a process of what and how the outcome should be displayed in responseto the event notification. The event handlers take parameters similarly to the valuesthat an event generates. By default the event handlers take two parameters andreturn no data. The first parameter describes the object on which the eventoccurred and the second parameter contains the event arguments.

    The event arguments describe the data associated with an event. This data issufficient enough to handle the event. The event arguments are of types EventArgs.W hen an event is raised, means when some button is clicked, the event argumentsare transferred to the event handlers. Delegates in .NET Framework are used toattach code to the events. A delegate is a class that allows you to create objectsthat store the reference to methods that does not return any value and that acceptstwo arguments. Delegates can be compared to function pointers in other languages.

    In ASP.NET you can handle events through three ways. These are: By overriding the virtual method of the base class By creating a delegate to the event By AutoEvent W ireUp of the Page class

  • 8/6/2019 e h

    11/30

    W hat is P roperties?

    Attribute of object is called properties. Eg1:- A car has color as property.Example of using properties in .Net:

    private string m_Color;;

    public string Color{get{return m_Color;}set{m_Color = value;}}

    Car Maruti = new Car();Maruti.Color= W hite;Console. W rite(Maruti.Color);

    Advantage of using Properties You might have question Isn't it better to make afield public than providing its property with both set { } and get { } block? After allthe property will allow the user to both read and modify the field so why not usepublic field instead?

    Not always! Properties are not just to provide access to the fields; rather, they aresupposed to provide controlled access to the fields of our class. As the state of theclass depends upon the values of its fields, using properties we can assure that noinvalid (or unacceptable) value is assigned to the fields. Example explaining howProperties are usefulprivate int age;

    public int Age{get{return age;}set{if(value 100)

    //throw exceptionelseage = value;

  • 8/6/2019 e h

    12/30

    }}

    You should give the follwoing query in the select statement,

    1. select * from yourtable;

    2. datareader will have only one value at a time, so add it to arraylist whenever youget it.

    while (dr.Read()) {

    empleaveformtogetdesignation.Emp_id = dr.GetString(0);

    empleaveformtogetdesignation.Emp_name = dr.GetString(1);

    // add to the array list here

    }You are getting only the last row, because same instance is being used so the valueis getting replaced everytime.The best approach would be to create a businessentity class in your project called Employee as shown below.

    public class Employee {

    private string _empId; public string EmpId {

    get{return _empId;} set{_empId = value;}

    } private string _empName; public string EmpName {

    get{return _empName;} set{_empName = value;}

    } }

    If you are using ASP.NET 2.0 and higher versions, then useSystem.Collections.Generic.List as shown below

    connString.Open(); SqlDataReader dr = cmd.ExecuteReader(); List empList = new List(); Employee employee = null; while (dr.Read())

  • 8/6/2019 e h

    13/30

  • 8/6/2019 e h

    14/30

    connString.Close();

    AS P .NE T P erformance T ip4 - while using ajax updatepanel

    If you have multiple update panels in web page, make sure that you put

    updatemode for update panel to Conditional to prevent loading of other updatepanels in any asynchronous post back.

    By default update panel will have the updatemode property to always means if anyasynchronous pushback is done for any of the update panel it loads all the updatepanels in the page. This is against to partial post back rendering.

    So it is always a best practice to set updatemode property to conditional tooptimize update panel performance wise and to load best results.

    Disable Session State

    AS P .NE T P erformance Optimization T ips

    1. Disable View State if not used

    2. Disable Session State if not required

    3. Use using keyword to define scope for objects dispose

    4. Set Updatepanel updatemode to conditional

    W hat is Singleton Design P attern? H ow did you implement it?

    Singleton Design Pattern class and maintains that single instance throughout thelifetime of the program. It can easily access that single object instance withoutcreating multiple instances. The single instance provides a global point of access toit.

    You need to create a private constructor to implement it

    class Singleton{

    //declare only onceprivate static Singleton Instance = new Singleton();public static Singleton Ins(){

  • 8/6/2019 e h

    15/30

    //reuse declared instancereturn Instance;}

    private Singleton(){

    //No public access allowed //Private constructor}}

    static means shared that help to create only one instance.

    There are 2 tips in singleton design pattern implementation

    1. Create private constructor

    2. Create static methods to reuse single instance of the static object.

    There are situations in real world where we need only to create one instance of theobject and shared across the clients.

    W here exactly it can be used in real time ?

    Singleton design patter can be used in Banking, Financial or Travel basedapplications where the singleton object consists of the network related information.

    if our application is an online store that allows each seller to have a customized

    store, if implementation of the store is a singleton object, then the singletoninstance will be created for each user . This will avoid a seller creating multiplestores,

    An ASP.NET W eb Farm (multiple server deployment) is also based on the Singletonpattern. In a W eb Farm, the web application uses on several web servers. Thesession state ( OUTPROC) is handled by a Singleton object in the form of exe file.This exe file interacts with the ASP.NET worker process(aspnet_wp.exe) running oneach web server. Even if one of the web servers shutting down, the singleton objectstill maintains the session state information across all web servers in the web farm.Singleton pattern as a LoadBalancing object. W e can have single instance per

    application, per user, per role or other criteria.

    Unload is called after the page has been fully rendered, sent to the client, and isready to be discarded. At this point, page properties such as Response andRequest are unloaded and any cleanup is performed.

    U se List to save values in the Listarray

  • 8/6/2019 e h

    16/30

    List EmpID = new List ();

    List EmpName = new List ();

    connString.Open();SqlDataReader dr = cmd.ExecuteReader();while (dr.Read()){

    EmpID.Add(dr.GetString(0)); // Array to save values;EmpName.Add(dr.GetString(1));

    }connString.Close();

    1. W rite a simple W indows Forms MessageBox statement.System. W indows.Forms.MessageBox.Show(" H ello, W indowsForms");

    2. Can you write a class without specifying namespace? W hichnamespace does it belong to by default? ?Yes, you can, then the class belongs to global namespace which has noname. For commercial products, naturally, you wouldnt want globalnamespace.

    3. You are designing a G UI application with a window and severalwidgets on it. T he user then resizes the app window and sees a lot of grey space, while the widgets stay in place. W hats the problem? Oneshould use anchoring for correct resizing. Otherwise the default property of awidget on a form is top-left, so it stays at the same location when resized.

    4. H ow can you save the desired properties of W indows Formsapplication? .config files in .NET are supported through the API to allowstoring and retrieving information. They are nothing more than simple XMLfiles, sort of like what .ini files were before for W in32 apps.

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

    6. Can you automate this process? In Visual Studio yes, use Dynamic

    Properties for automatic .config creation, storage and retrieval.7. My progress bar freezes up and dialog window shows blank, when

    an intensive background process takes over . Yes, you shouldve multi-threaded your GUI, with taskbar and main form being one thread, and thebackground process being the other.

    8. W hats the safest way to deploy a W indows Forms app? W ebdeployment: the user always downloads the latest version of the code; theprogram runs within security sandbox, properly written app will not require

  • 8/6/2019 e h

    17/30

    additional security privileges.9. W hy is it not a good idea to insert code into I nitializeComponent

    method when working with Visual Studio? The designer will likely throwit away; most of the code inside InitializeComponent is auto-generated.

    10. W hats the difference between W indowsDefaultLocation and

    W indowsDefaultBounds? W

    indowsDefaultLocation tells the form to startup at a location selected by OS, but with internally specified size.W indowsDefaultBounds delegates both size and starting position choices tothe OS.

    11. W hats the difference between Move and LocationChanged? Resizeand SizeChanged? Both methods do the same, Move and Resize are thenames adopted from VB to ease migration to C#.

    12. H ow would you create a non-rectangular window, lets say anellipse? Create a rectangular form, set the TransparencyKey property to thesame value as BackColor, which will effectively make the background of theform transparent. Then set the FormBorderStyle to FormBorderStyle.None,which will remove the contour and contents of the form.

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

    14. H ows anchoring different from docking? Anchoring treats thecomponent as having the absolute size and adjusts its location relative tothe parent form. Docking treats the component location as absolute anddisregards the component size. So if a status bar must always be at thebottom 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

    H ow do I set Custom Date Format in Date T ime P icker ( W inForms)?Use this code -

    this.dateTimePicker1.Format =System. W indows.Forms.DateTimePickerFormat.Custom;this.dateTimePicker1.CustomFormat = "dd/MM/yyyy";this.dateTimePicker1.ShowUpDown = false;

    H ow can I use a T extBox to enter a password?Set the TextBox.PasswordChar property to the character that you want to use forpassword -textBox1.PasswordChar = '\u25CF';

    H ow can I run an EXE from within my application?

    Use the Process class found in the System.Diagnostics namespace.

    Process proc = new Process();proc.StartInfo.FileName = @"Notepad.exe";proc.StartInfo.Arguments = "";proc.Start();

    H ow do I dynamically load a control from a DLL?

  • 8/6/2019 e h

    18/30

    Use System.Reflection. Assembly to dynamically load a control. If the DLL isnamed "DLLControls.DLL" and the class you want is "DLLControls.ColorControl",then use the code like -

    // load the assembly

    System.Reflection.Assembly assembly = Assembly.LoadFrom("DLLControls.DLL");

    // get the typeType t = assembly.GetType("MyControls.MyControl");

    // create an instance and add it.Control c = (Control)Activator.CreateInstance(t);parent.Controls.Add(c);

    W hat is Global Assembly Cache ?GAC is an area of memory reserved for storing the assemblies of all .Netapplications running on a given computer. The GAC is required by side-by-sideexecution as well as for sharing assemblies among multiple .Net applications. Anassembly must have a strong name and be publicshared assemblyto beinstalled in the GAC. The Global Assembly Cache Tool adds and removesassemblies from the GAC.

    H ow many Formats are supported by Date T ime P icker?Formats supported by DateTimePicker are -

    LongShortTimeCustom

    H ow to set Date T ime P icker MinDate and MaxDate ( W informs)?dateTimePicker1.MinDate = DateTime.Today;dateTimePicker1.MaxDate = DateTime.Today.AddYears( 1 );

    W hat is Local assembly cache ?Assembly cache that stores compiled classes and methods specific to anapplication. Each application directory contains a \bin subdirectory containing localassembly cache files. Also known as the application assembly cache.

    W hat is Global Assembly Cache T ool ?.Net programming tool (GACUtil.exe) for installing, list the contents, anduninstalling to the Global Assembly Cache. It can be called from batch files andscripts.

    W hat does it mean by docking of controls?Docking is the property of the control to attach itself to a particular edge of the

  • 8/6/2019 e h

    19/30

    window (or other containing control). You can either dock a control to an edge orto fill the available space in the parent control or window.

    Common examples of docking includes menu bar and toolbars which dockthemselves at the top of the window so that they may remain at top regardless of

    the size and of the window.

    W hat base class do all W informs inherit from?System. W indows.Forms.Form

    H ow do I prevent the beep when the user presses the Enter key in aT extBox?You can prevent the beep when the enter key is pressed in a TextBox by derivingthe TextBox and overriding OnKeyPress -

    public class CustomTextBox : TextBox {

    protected override void OnKeyPress( KeyPressEventArgs e ){if ( e.KeyChar == (char) 13 )e.Handled = true;elsebase.OnKeyPress( e );} }

    H ow do I load a picture into the P ictureBox control?To load a Picture into the PictureBox control drag a PictureBox control and aCommand Button from the Toolbox. W hen you click the Command Button, the

    picture you specified will be loaded into the Picturebox. The following code is ademonstration -

    PictureBox1.Image=Image.FromFile("C:\images\image.gif") //Assuming you havea folder named images in C: drive and a gif image in that

    H ow do I make a T extBox use all upper-case (or lower-case) characters?Use the CharacterCasing property of the TextBox.

    textBox1.CharacterCasing = CharacterCasing.Upper;textBox2.CharacterCasing = CharacterCasing.Lower;

    H ow do I add custom drawing to a Button?Subclass Button and add a custom Paint event handler that does you customdrawing.

    public class CustomButton : Button{public CustomButton()

  • 8/6/2019 e h

    20/30

    {Paint += new PaintEventHandler( ButtonPaint );}

    private void ButtonPaint( object sender, PaintEventArgs e )

    {Pen pen = new Pen( Color.Red );pen. W idth = 8;e.Graphics.DrawLine( pen, 7, 4, 7, Height - 4 );pen. W idth = 1;e.Graphics.DrawEllipse( pen, W idth - 16 , 6, 8, 8 );}}H ow do I resize a Button to fit its T ext?Get a Graphics object for the button and use its MeasureString method to computethe width you need.

    using ( Graphics g = button1.CreateGraphics() )float w = g.MeasureString( button1.Text, button1.Font ). W idth;button1. W idth = (int) w + 12; // 12 is for the margins

    H ow do I put a bitmap or icon on a Button?You can use the Button.Image property to add an image to a button face. Use theButton.ImageAlign (and possibly Button.TextAlign) to layout your button face.

    You can also implement custom drawing on a button face.

    H ow do I trigger a Button Click event?Use the Button's public method PerformClick().W hat are the fundamental and common properties of .Net controls?Almost all the controls have some similar properties like Location, Size, Enabled,Visible, TabIndex, Name, Text, BacKColor, ForeColor, Font, etc. The TabIndexproperty is very important. It describes the sequence followed by the windows focuswhen the user presses the Tab button of keyboard

    H ow can I add a control to a W indow Form at runtime?To add a control at runtime, you do three steps:

    1. Create the control2. Set control properties3. Add the control to the Forms Controls collection

    Here are code snippets that create a textBox at runtime.

    //step 1TextBox tb = new TextBox();

  • 8/6/2019 e h

    21/30

    //step2tb.Location = new Point( 10, 10);tb.Size = new Size(100, 20);tb.Text = "I was created at runtime";

    //step3this.Controls.Add(tb);

    W hat control do I use to insert Separator lines between Controls in myDialog?Use the Label Control with the BorderStyle set to Fixed3D and height set to 2.

    W hats the difference between const and readonly? You can initializereadonly variables to some runtime values. Lets say your program uses currentdate and time as one of the values that wont change. This way you declarepublic readonly string DateT = new DateTime().ToString().

    H ow do you turn off SessionState in the web.config file? In the

    system.web section of web.config, you should locate the httpmodule tag and yousimply disable session by doing a remove tag with attribute name set to session.

    W hat are valid signatures for the Main function?

    y public static void Main()y public static int Main()y

    public static void Main( string[] args )y public static int Main(string[] args )

    W hats the C# syntax to catch any possible exception?A catch block that catches the exception of type System.Exception. You can alsoomit the parameter data type in this case and just write catch {}.

    W hen should you call the garbage collector in .NE T ? As a good rule, you should not call the garbage collector. However, you could callthe garbage collector when you are done using a large object (or set of objects) toforce the garbage collector to dispose of those very large objects frommemory. However, this is usually not a good practice.

    12.1.1 H ow do I read from a text file?First, use a System.IO.FileStream object to open the file:FileStream fs = new FileStream( @"c:\test.txt", FileMode.Open, FileAccess.Read );FileStream inherits from Stream, so you can wrap the FileStream object with aStreamReader object. This provides a nice interface for processing the stream lineby line:

  • 8/6/2019 e h

    22/30

    StreamReader sr = new StreamReader( fs );string curLine;while( (curLine = sr.ReadLine()) != null )

    Console. W riteLine( curLine );Finally close the StreamReader object:

    sr.Close();Note that this will automatically call Close() on the underlying Stream object, so anexplicit fs.Close() is not required.12.1.2 H ow do I write to a text file?Similar to the read example, except use Stream W riter instead of StreamReader.12.1.3 H ow do I read / write binary files?Similar to text files, except wrap the FileStream object with a BinaryReader/ W riterobject instead of a StreamReader/ W riter object.MVC Architecture Model I n AS P .NE T W hen developing ASP.NET applications the need of reducing code duplicationincreases along with their complexity. This is because testing and performingchanges become very difficult tasks when having many different sources of codewith the same functionality.MVC OverviewModel View Controller architecture aims to separate an application into three parts:Model: It is the business logic of an application. From an object orientedperspective it would consist of a set of classes that implement the criticalfunctionality of an application from a business point of view.View: It can consist of every type of interface given to the user. In ASP.NET theview is the set of web pages presented by a web application.Controller: This part of the architecture is the most difficult to explain, hence themost difficult to implement in many platforms. The controller is the object thatallows the manipulation of the view. Usually many applications implement Model-

    Controller tiers that contain the business logic along with the necessary code tomanipulate a user interface. In an ASP.NET application the controller is implicitlyrepresented by the code-behind or the server side code that generates the HTMLpresented to the user.Implementing MVC in ASP.NETA basic diagram that would help us understand perfectly the specific parts thatimplement the Model View Controller architecture in an ASP.NET application ispresented below:

  • 8/6/2019 e h

    23/30

    MVC Model ImplementationW hen implementing the business logic of an application it is a must to use a ClassLibrary project in order to generate a .dll file that will encapsulate all thefunctionality. This is critical as we as professional developers would not like to

    jeopardize the source code of a software product by placing the actual .cs files as areference in a web application.This type of project can be easily created in Visual Studio 2005 under the VisualC# or Visual Basic tabs:

    As a tutorial example we will develop a simple calculator under a new namespacewe will call "Math".Once the project is created we will add a class called Calculator:

  • 8/6/2019 e h

    24/30

    As the code is very simple and a sample is provided in this tutorial we will not getinto much detail as far as how it is developed. The only important thing we need tomention is the way errors have to be handled in this class. Take a look at thefollowing code:1. protected float Divide( float fNumber1, float fNumber2)2. {3. if (fNumber2 == 0)4. {5. throw new Exception ( "Second number cannot be equal to zero." );6. }

    7. return (fNumber1 / fNumber2);8. }

    W hen implementing the Divide function we need to ensure that the user would notbe able to set the "fNumber2" parameter (line 1) to zero as a division betweenzero does not exist. The validation statement in lines 3-6 takes care of this casebut the important fact we need to notice is that this class will NEVER use specificmethods to present errors like message boxes or writing into labels. Errors

    captured in the model part of the architecture ALW

    AYS have to be presented in theform of exceptions (line 5). This will allow us to use this object in several types of applications like ASP.NET applications, W indows applications, W eb services, etc.Once we have finished coding our Calculator class the project has to be built inorder to get the .dll file we will use in our W eb application.MVC View-Controller ImplementationThe View and the Controller objects will be implemented by using a commonASP.NET W ebsite. Once we have created our project we need to add the reference

  • 8/6/2019 e h

    25/30

    to the .dll file we created before.The option to do this can be found in the context menu when right-clicking theproject in the solution explorer:

    W e can find the file in the path "\bin\Release" (or "\bin\Debug" depending on howyou build your class library) inside our main folder containing the math class libraryproject:

  • 8/6/2019 e h

    26/30

  • 8/6/2019 e h

    27/30

    3. if (pbValidateNumbers())4. {5. Calculator cOperator = new Calculator ();6. try7. {

    8. txtResult.Text =cOperator.Operate( float .Parse(txtNumber1.Text.Trim()),float .Parse(txtNumber2.Text.Trim()),Convert .ToInt16(rblOperations.SelectedValue)).ToString();9. lbError.Text = "" ;10. }11. catch ( Exception ex)12. {13. txtResult.Text = "" ;14. lbError.Text = ex.Message;15. }16. }17.}In line 3 we call the bool function "pbValidateNumbers" that will return true if thenumbers typed in both textboxes are valid. These types of validations have to beperformed by the controller object as they allow the interface to work properly andhave nothing to do with the business logic.In line 5 we create an instance of our Calculator class so we can perform thearithmetic operation. W e call the method "Operate" (line 8) and return the value inanother textbox. An important thing to mention is that we have to use a try-catchstatement (lines 6-15) to handle any exception that could be thrown by ourmethod "Operate" as every error caught in our Calculator class is handled bythrowing a "digested" exception that is readable to the user.

    In the code above we can appreciate how well encapsulated the business logic is,hence it can be reused in several applications without having to code it again.Advantages of using MVC in AS P .NE T There's no duplicated code.The business logic is encapsulated; hence the controller code is transparent andsafer.The business logic can be used in several front ends like W eb pages, W eb services,W indows applications, services, etc.Exception handling is well managed showing the user only digested errormessages.Testing every part of an application is easier as it can be done separately usingautomated methods.Application changes are easier to apply as they are focused in one part of thearchitecture only.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 DataSetobject contents to XML. A good use is reading database data to an XML file to besent to a W eb Service.W hat is the lifespan for items stored in ViewState? Item stored in ViewState exist for the life of the current page. This includes

  • 8/6/2019 e h

    28/30

    postbacks (to the same page).

    1. W hat is the role of the DataReader class in ADO.NE T connections?It returns a read-only, forward-only rowset from the data source. A

    DataReader provides fast access when a forward-only sequential read isneeded.

    2. W hat are advantages and disadvantages of Microsoft-provided dataprovider classes in ADO.NE T ?SQLServer.NET data provider is high-speed and robust, but requires SQLServer license purchased from Microsoft. OLE-DB.NET is universal foraccessing other sources, like Oracle, DB2, Microsoft Access andInformix. OLE-DB.NET is a .NET layer on top of the OLE layer, so its not asfastest and efficient as SqlServer.NET.

    3. W hat is the wildcard character in SQL?Lets say you want to query database with LIKE for all employees whosename starts with La. The wildcard character is %, the proper query withLIKE would involve La%.

    4. Explain AC I D rule of thumb for transactions.A transaction must be:1. Atomic - it is one unit of work and does not dependent on previousand following transactions.2. Consistent - data is either committed or roll back, no in-between case where something has been updated and something hasnt.3. Isolated - no transaction sees the intermediate results of the current

    transaction).4. Durable - the values persist if the data had been committed even if the system crashes right after.

    5. W hat connections does Microsoft SQL Server support?W indows Authentication (via Active Directory) and SQL Serverauthentication (via Microsoft SQL Server username and password).

    6. Between W indows Authentication and SQL Server Authentication,which one is trusted and which one is untrusted? W indows Authentication is trusted because the username and password arechecked with the Active Directory, the SQL Server authentication isuntrusted, since SQL Server is the only verifier participating in thetransaction.

    7. W hat does the I nitial Catalog parameter define in the connectionstring? The database name to connect to.

    8. W hat does the Dispose method do with the connection object?

  • 8/6/2019 e h

    29/30

    Deletes it from the memory.T o Do: answer better. The current answer is not entirely correct.

    9. W hat is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection,

    where every parameter is the same, including the security settings. Theconnection string must be identical.

    Assembly Questions

    1. H ow is the DLL H ell problem solved in .NE T ?Assembly versioning allows the application to specify not only the library itneeds to run (which was available under W in32), but also the version of theassembly.

    2. W hat are the ways to deploy an assembly?An MSI installer, a CAB archive, and XCOPY command.

    3. W hat is a satellite assembly? W hen you write a multilingual or multi-cultural application in .NET, and wantto distribute the core application separately from the localized modules, thelocalized assemblies that modify the core application are called satelliteassemblies.

    4. W hat namespaces are necessary to create a localized application?System.Globalization and System.Resources.

    5. W hat is the smallest unit of execution in .NE T ? an Assembly.

    6. W hen should you call the garbage collector in .NE T ? As a good rule, you should not call the garbage collector. However,you could call the garbage collector when you are done using a large object(or set of objects) to force the garbage collector to dispose of those verylarge objects from memory. However, this is usually not a good practice.

    7. H ow do you convert a value-type to a reference-type? Use Boxing.

    8. W hat happens in memory when you Box and U nbox a value-type? Boxing converts a value-type to a reference-type, thus storing the object onthe heap. Unboxing converts a reference-type to a value-type, thus storingthe value on the stack.

  • 8/6/2019 e h

    30/30

    .