Você está na página 1de 54

Q 1 What is framework and dot net framework

Answer: In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful. .NET framework is an integral part of many applications running on Windows and provides common functionality for those applications to run. This download is for people who need .NET to run an application on their computer. For developers, the .NET Framework provides a comprehensive and consistent programming model for building applications that have visually stunning user experiences and seamless and secure communication.

Q2 Describe how a .Net application is compiled and executed.


From the source code, the compiler generates Microsoft Intermediate Language (MSIL) which is further used for the creation of an EXE or DLL. The CLR processes these at runtime. Thus, compiling is the process of generating this MSIL. The way you do it in .Net is as follows: Right-click and select Build / Ctrl-Shift-B / Build menu, Build command F5 - compile and run the application. Ctrl+F5 - compile and run the application without debugging. Compilation can be done with Debug or Release configuration. The difference between these two is that in the debug configuration, only an assembly is generated without optimization. However, in release complete optimization is performed without debug symbols.

Q3 What are assemblies? Describe the types of assemblies. Assembly is a compiled output of program which are used for easy deployment of an application. They are executables in the form of exe or dll. It also is a collection of resources that were used while building the application and is responsible for all the logical functioning. Types of assemblies: a. Private Assemblies: are accessible by a single application. They reside within the application folder and are unique by name. They can be directly used by copying and pasting them to the bin folder. b. Shared Assemblies: are shared between multiple applications to ensure reusability. They are placed in GAC. c. Satellite Assemblies: are the assemblies to provide the support for multiple languages based on different cultures. These are kept in different modules based on the different categories available

Q4 What is 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 {

Inheritance can be classified to 5 types. 1. 2. 3. 4. Single Inheritance Hierarchical Inheritance Multi Level Inheritance 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.

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.

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

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

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 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.

Q5 Differences between method overloading and method overriding


Method Overloading and Method Overriding are both the techniques used to implement FUNCTIONAL POLYMORPHISM They enhance the methods functionality using their respective features. overloading: 1) It involves having another method with the same name in a class or its derived class. 2)can be implemented with or without inheritance. 3)It is implemented by: a)changing the number of parameters in different methods with same name. b)changing the parameter data types (if the number of parameters are same) c)changing parameter order. 4)applicable to static as well as non static methods:

5)no keywords needed before the method names in C#. 6)also called as COMPILE TIME Polymorphism. example: int add(int a, int b) { return a+b; } int add(int a) { return a*5; }

Overriding: 1) It involves having another method with the same name in a base class and derived class. 2)always needs inheritance. 3)It is implemented by having two methods with same name, same signature, but different implementations (coding)in a base class and derived class 4)applicable to nonstatic, nonprivate methods only.access modifiers of the methods are not changed in the base and derived classes. 5)virtual and override keywords are needed before the method names in base and derived classes. For overriding in firther classes, override keyword will be used, 6)RUN TIME Polymorphism example: class A { public virtual void demo() { } } class B:A { public override void demo() {

} static void Main() { B obj=new B(); obj.demo(); } }

Q 6 Explain different events of Dot net form


Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers. In a typical C# Windows Forms or Web application, you subscribe to events raised by controls such as buttons and list boxes. You can use the Visual C# integrated development environment (IDE) to browse the events that a control publishes and select the ones that you want to handle. The IDE automatically adds an empty event handler method and the code to subscribe to the event. For more information, see How to: Subscribe to and Unsubscribe from Events (C# Programming Guide). Events Overview

Events have the following properties:


The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event. An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers. Events that have no subscribers are never raised. Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces. When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised. To invoke events asynchronously, see Calling Synchronous Methods Asynchronously. In the .NET Framework class library, events are based on the EventHandler delegate and the EventArgs base class.

Q 7 Explain the different types of windows control you can create in .NET Common controls: textbox, button etc Containers: Controls to group other controls, e.g.: GroupBox, Panel etc. Menus & toolbars: various menus, toolstips

Data: dataset, datagridview, BidnignSource Components: Special components for special needs, e.g.: timer, directory searcher, file system watcher. Printing: for printing e.g.: PrintDialog,Page setup,, PrintDocument etc. Dialogs: various dialogboxes, e.g.: colorDialog, FolderBrowser etc WPF Interoperability: provide a ElementHost control for WPF. Reporting: reportviewer controls

Q 8 explain dialog boxes of C .net


Standalone applications typically have a main window that both displays the main data over which the application operates and exposes the functionality to process that data through user interface (UI) mechanisms like menu bars, tool bars, and status bars. A non-trivial application may also display additional windows to do the following:

Display specific information to users. Gather information from users. Both display and gather information.

These types of windows are known as dialog boxes, and there are two types: modal and modeless. A modal dialog box is displayed by a function when the function needs additional data from a user to continue. Because the function depends on the modal dialog box to gather data, the modal dialog box also prevents a user from activating other windows in the application while it remains open. In most cases, a modal dialog box allows a user to signal when they have finished with the modal dialog box by pressing either an OK or Cancel button. Pressing the OK button indicates that a user has entered data and wants the function to continue processing with that data. Pressing the Cancel button indicates that a user wants to stop the function from executing altogether. The most common examples of modal dialog boxes are shown to open, save, and print data. A modeless dialog box, on the other hand, does not prevent a user from activating other windows while it is open. For example, if a user wants to find occurrences of a particular word in a document, a main window will often open a dialog box to ask a user what word they are looking for. Since finding a word doesn't prevent a user from editing the document, however, the dialog box doesn't need to be modal. A modeless dialog box at least provides a Close button to close the dialog box, and may provide additional buttons to execute specific functions, such as a Find Next button to find the next word that matches the find criteria of a word search. Windows Presentation Foundation (WPF) allows you to create several types of dialog boxes, including message boxes, common dialog boxes, and custom dialog boxes. This topic discusses each, and the Dialog Box Sample provides matching examples. This topic contains the following sections.

Message Boxes

Common Dialog Boxes Custom Dialog Boxes Related Topics

Message Boxes

A message box is a dialog box that can be used to display textual information and to allow users to make decisions with buttons. The following figure shows a message box that displays textual information, asks a question, and provides the user with three buttons to answer the question.

To create a message box, you use the MessageBox class. MessageBox lets you configure the message box text, title, icon, and buttons, using code like the following. C# VB
// Configure the message box to be displayed string messageBoxText = "Do you want to save changes?"; string caption = "Word Processor"; MessageBoxButton button = MessageBoxButton.YesNoCancel; MessageBoxImage icon = MessageBoxImage.Warning;

To show a message box, you call the static Show method, as demonstrated in the following code. C# VB
// Display message box MessageBox.Show(messageBoxText, caption, button, icon);

When code that shows a message box needs to detect and process the user's decision (which button was pressed), the code can inspect the message box result, as shown in the following code. C# VB
// Display message box

MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon); // Process message box results switch (result) { case MessageBoxResult.Yes: // User pressed Yes button // ... break; case MessageBoxResult.No: // User pressed No button // ... break; case MessageBoxResult.Cancel: // User pressed Cancel button // ... break; }

For more information on using message boxes, see MessageBox, MessageBox Sample, and Dialog Box Sample. Although MessageBox may offer a simple dialog box user experience, the advantage of using MessageBox is that is the only type of window that can be shown by applications that run within a partial trust security sandbox (see Security (WPF)), such as XAML browser applications (XBAPs). Most dialog boxes display and gather more complex data than the result of a message box, including text, selection (check boxes), mutually exclusive selection (radio buttons), and list selection (list boxes, combo boxes, drop-down list boxes). For these, Windows Presentation Foundation (WPF) provides several common dialog boxes and allows you to create your own dialog boxes, although the use of either is limited to applications running with full trust. Common Dialog Boxes

Windows implements a variety of reusable dialog boxes that are common to all applications, including dialog boxes for opening files, saving files, and printing. Since these dialog boxes are implemented by the operating system, they can be shared among all the applications that run on the operating system, which helps user experience consistency; when users are familiar with the use of an operating system-provided dialog box in one application, they don't need to learn how to use that dialog box in other applications. Because these dialog boxes are available to all applications and because they help provide a consistent user experience, they are known as common dialog boxes. Windows Presentation Foundation (WPF) encapsulates the open file, save file, and print common dialog boxes and exposes them as managed classes for you to use in standalone applications. This topic provides a brief overview of each.

Open File Dialog

The open file dialog box, shown in the following figure, is used by file opening functionality to retrieve the name of a file to open.

The common open file dialog box is implemented as the OpenFileDialog class and is located in the Microsoft.Win32 namespace. The following code shows how to create, configure, and show one, and how to process the result. C# VB
// Configure open file dialog box Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = "Document"; // Default file name dlg.DefaultExt = ".txt"; // Default file extension dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension // Show open file dialog box Nullable<bool> result = dlg.ShowDialog(); // Process open file dialog box results if (result == true) { // Open document string filename = dlg.FileName; }

For more information on the open file dialog box, see Microsoft.Win32.OpenFileDialog. Note OpenFileDialog can be used to safely retrieve file names by applications running with partial trust (see Security (WPF)). Save File Dialog Box

The save file dialog box, shown in the following figure, is used by file saving functionality to retrieve the name of a file to save.

The common save file dialog box is implemented as the SaveFileDialog class, and is located in the Microsoft.Win32 namespace. The following code shows how to create, configure, and show one, and how to process the result. C# VB
// Configure save file dialog box Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = "Document"; // Default file name dlg.DefaultExt = ".text"; // Default file extension dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension // Show save file dialog box Nullable<bool> result = dlg.ShowDialog();

// Process save file dialog box results if (result == true) { // Save document string filename = dlg.FileName; }

For more information on the save file dialog box, see Microsoft.Win32.SaveFileDialog. Print Dialog Box

The print dialog box, shown in the following figure, is used by printing functionality to choose and configure the printer that a user would like to print data to.

The common print dialog box is implemented as the PrintDialog class, and is located in the System.Windows.Controls namespace. The following code shows how to create, configure, and show one. C# VB
// Configure printer dialog box System.Windows.Controls.PrintDialog dlg = new System.Windows.Controls.PrintDialog();

dlg.PageRangeSelection = PageRangeSelection.AllPages; dlg.UserPageRangeEnabled = true; // Show save file dialog box Nullable<bool> result = dlg.ShowDialog(); // Process save file dialog box results if (result == true) { // Print document }

For more information on the print dialog box, see System.Windows.Controls.PrintDialog. For detailed discussion of printing in WPF, see Printing Overview. Custom Dialog Boxes

While common dialog boxes are useful, and should be used when possible, they do not support the requirements of domain-specific dialog boxes. In these cases, you need to create your own dialog boxes. As we'll see, a dialog box is a window with special behaviors. Window implements those behaviors and, consequently, you use Window to create custom modal and modeless dialog boxes. Creating a Modal Custom Dialog Box

This topic shows how to use Window to create a typical modal dialog box implementation, using the Margins dialog box as an example (see Dialog Box Sample). The Margins dialog box is shown in the following figure.

Configuring a Modal Dialog Box

The user interface for a typical dialog box includes the following:

The various controls that are required to gather the desired data.

Showing an OK button that users click to close the dialog box, return to the function, and continue processing. Showing a Cancel button that users click to close the dialog box and stop the function from further processing. Showing a Close button in the title bar. Showing an icon. Showing Minimize, Maximize, and Restore buttons. Showing a System menu to minimize, maximize, restore, and close the dialog box. Opening above and in the center of the window that opened the dialog box. Dialog boxes should be resizable where possible so, to prevent the dialog box from being too small, and to provide the user with a useful default size, you need to set both default and a minimum dimensions respectively. Pressing the ESC key should be configured as a keyboard shortcut that causes the Cancel button to be pressed. This is achieved by setting the IsCancel property of the Cancel button to true. Pressing the ENTER (or RETURN) key should be configured as a keyboard shortcut that causes the OK button to be pressed. This is achieved by setting the IsDefault property of the OK button true.

The following code demonstrates this configuration. XAML


<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.MarginsDialogBox" xmlns:local="clr-namespace:SDKSample" Title="Margins" Height="190" Width="300" MinHeight="10" MinWidth="300" ResizeMode="CanResizeWithGrip" ShowInTaskbar="False" WindowStartupLocation="CenterOwner" FocusManager.FocusedElement="{Binding ElementName=leftMarginTextBox}"> <Grid> ... <!-- Accept or Cancel --> <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="4"> <Button Name="okButton" Click="okButton_Click" IsDefault="True">OK</Button> <Button Name="cancelButton" IsCancel="True">Cancel</Button> </StackPanel> </Grid >

</Window>

C# VB
using System.Windows; // Window, RoutedEventArgs, IInputElement, DependencyObject using System.Windows.Controls; // Validation using System.Windows.Input; // Keyboard namespace SDKSample { public partial class MarginsDialogBox : Window { public MarginsDialogBox() { InitializeComponent(); } ... } }

The user experience for a dialog box also extends into the menu bar of the window that opens the dialog box. When a menu item runs a function that requires user interaction through a dialog box before the function can continue, the menu item for the function will have an ellipsis in its header, as shown here. XAML
<!--Main Window--> ... <MenuItem Name="formatMarginsMenuItem" Header="_Margins..." Click="formatMarginsMenuItem_Click" />

When a menu item runs a function that displays a dialog box which does not require user interaction, such as an About dialog box, an ellipsis is not required. Opening a Modal Dialog Box

A dialog box is typically shown as a result of a user selecting a menu item to perform a domainspecific function, such as setting the margins of a document in a word processor. Showing a window as a dialog box is similar to showing a normal window, although it requires additional dialog box-specific configuration. The entire process of instantiating, configuring, and opening a dialog box is shown in the following code.

C# VB
using using using using using System; // EventArgs System.ComponentModel; // CancelEventArgs System.Windows; // Window, MessageBoxXxx, RoutedEventArgs System.Windows.Controls; // TextChangedEventArgs Microsoft.Win32; // OpenFileDialog

namespace SDKSample { public partial class MainWindow : Window { ... void formatMarginsMenuItem_Click(object sender, RoutedEventArgs e) { // Instantiate the dialog box MarginsDialogBox dlg = new MarginsDialogBox(); // Configure the dialog box dlg.Owner = this; dlg.DocumentMargin = this.documentTextBox.Margin; // Open the dialog box modally dlg.ShowDialog();

... } ... } }

Here, the code is passing default information (the current margins) to the dialog box. It is also setting the Window.Owner property with a reference to the window that is showing the dialog box. In general, you should always set the owner for a dialog box to provide window staterelated behaviors that are common to all dialog boxes (see WPF Windows Overview for more information). Note You must provide an owner to support user interface (UI) automation for dialog boxes (see UI Automation Overview).

After the dialog box is configured, it is shown modally by calling the ShowDialog method. Validating User-Provided Data

When a dialog box is opened and the user provides the required data, a dialog box is responsible for ensuring that the provided data is valid for the following reasons:

From a security perspective, all input should be validated. From a domain-specific perspective, data validation prevents erroneous data from being processed by the code, which could potentially throw exceptions. From a user-experience perspective, a dialog box can help users by showing them which data they have entered is invalid. From a performance perspective, data validation in a multi-tier application can reduce the number of round trips between the client and the application tiers, particularly when the application is composed of Web services or server-based databases.

To validate a bound control in WPF, you need to define a validation rule and associate it with the binding. A validation rule is a custom class that derives from ValidationRule. The following example shows a validation rule, MarginValidationRule, which checks that a bound value is a Double and is within a specified range. C# VB
using System.Globalization; using System.Windows.Controls; namespace SDKSample { public class MarginValidationRule : ValidationRule { double minMargin; double maxMargin; public double MinMargin { get { return this.minMargin; } set { this.minMargin = value; } } public double MaxMargin { get { return this.maxMargin; } set { this.maxMargin = value; } } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { double margin;

// Is a number? if (!double.TryParse((string)value, out margin)) { return new ValidationResult(false, "Not a number."); } // Is in range? if ((margin < this.minMargin) || (margin > this.maxMargin)) { string msg = string.Format("Margin must be between {0} and {1}.", this.minMargin, this.maxMargin); return new ValidationResult(false, msg); } // Number is valid return new ValidationResult(true, null); } } }

In this code, the validation logic of a validation rule is implemented by overriding the Validate method, which validates the data and returns an appropriate ValidationResult. To associate the validation rule with the bound control, you use the following markup. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.MarginsDialogBox" xmlns:local="clr-namespace:SDKSample" Title="Margins" Height="190" Width="300" MinHeight="10" MinWidth="300" ResizeMode="CanResizeWithGrip" ShowInTaskbar="False" WindowStartupLocation="CenterOwner" FocusManager.FocusedElement="{Binding ElementName=leftMarginTextBox}"> <Grid>

... <Label Grid.Column="0" Grid.Row="0">Left Margin:</Label> <TextBox Name="leftMarginTextBox" Grid.Column="1" Grid.Row="0"> <TextBox.Text> <Binding Path="Left" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <local:MarginValidationRule MinMargin="0" MaxMargin="10" /> </Binding.ValidationRules>

</Binding> </TextBox.Text> </TextBox> ... </Window>

Once the validation rule is associated, WPF will automatically apply it when data is entered into the bound control. When a control contains invalid data, WPF will display a red border around the invalid control, as shown in the following figure.

WPF does not restrict a user to the invalid control until they have entered valid data. This is good behavior for a dialog box; a user should be able to freely navigate the controls in a dialog box whether or not data is valid. However, this means a user can enter invalid data and press the OK button. For this reason, your code also needs to validate all controls in a dialog box when the OK button is pressed by handling the Click event. C# VB
using System.Windows; // Window, RoutedEventArgs, IInputElement, DependencyObject using System.Windows.Controls; // Validation using System.Windows.Input; // Keyboard namespace SDKSample { public partial class MarginsDialogBox : Window { ... void okButton_Click(object sender, RoutedEventArgs e) { // Don't accept the dialog box if there is invalid data

if (!IsValid(this)) return; ... } // Validate all dependency objects in a window bool IsValid(DependencyObject node) { // Check if dependency object was passed if (node != null) { // Check if dependency object is valid. // NOTE: Validation.GetHasError works for controls that have validation rules attached bool isValid = !Validation.GetHasError(node); if (!isValid) { // If the dependency object is invalid, and it can receive the focus, // set the focus if (node is IInputElement) Keyboard.Focus((IInputElement)node); return false; } } // If this dependency object is valid, check all child dependency objects foreach (object subnode in LogicalTreeHelper.GetChildren(node)) { if (subnode is DependencyObject) { // If a child dependency object is invalid, return false immediately, // otherwise keep checking if (IsValid((DependencyObject)subnode) == false) return false; } } // All dependency objects are valid return true; } } }

This code enumerates all dependency objects on a window and, if any are invalid (as returned by GetHasError, the invalid control gets the focus, the IsValid method returns false, and the window is considered invalid. Once a dialog box is valid, it can safely close and return. As part of the return process, it needs to return a result to the calling function.

Setting the Modal Dialog Result

Opening a dialog box using ShowDialog is fundamentally like calling a method: the code that opened the dialog box using ShowDialog waits until ShowDialog returns. When ShowDialog returns, the code that called it needs to decide whether to continue processing or stop processing, based on whether the user pressed the OK button or the Cancel button. To facilitate this decision, the dialog box needs to return the user's choice as a Boolean value that is returned from the ShowDialog method. When the OK button clicked, ShowDialog should return true. This is achieved by setting the DialogResult property of the dialog box when the OK button is clicked. Note that setting the DialogResult property also causes the window to close automatically, which alleviates the need to explicitly call Close. When the Cancel button is clicked, ShowDialog should return false, which also requires setting the DialogResult property. C# VB
using System.Windows; // Window, RoutedEventArgs, IInputElement, DependencyObject using System.Windows.Controls; // Validation using System.Windows.Input; // Keyboard namespace SDKSample { public partial class MarginsDialogBox : Window { ... void cancelButton_Click(object sender, RoutedEventArgs e) { // Dialog box canceled this.DialogResult = false; } ... } }

When a button's IsCancel property is set to true and the user presses either the Cancel button or the ESC key, DialogResult is automatically set to false. The following markup has the same effect as the preceding code, without the need to handle the Click event.

XAML
<Button Name="cancelButton" IsCancel="True">Cancel</Button>

A dialog box automatically returns false when a user presses the Close button in the title bar or chooses the Close menu item from the System menu. Processing Data Returned from a Modal Dialog Box

When DialogResult is set by a dialog box, the function that opened it can get the dialog box result by inspecting the DialogResult property when ShowDialog returns. C# VB
using using using using using System; // EventArgs System.ComponentModel; // CancelEventArgs System.Windows; // Window, MessageBoxXxx, RoutedEventArgs System.Windows.Controls; // TextChangedEventArgs Microsoft.Win32; // OpenFileDialog

namespace SDKSample { public partial class MainWindow : Window { ... void formatMarginsMenuItem_Click(object sender, RoutedEventArgs e) { ... // Process data entered by user if dialog box is accepted if (dlg.DialogResult == true) { // Update fonts this.documentTextBox.Margin = dlg.DocumentMargin; } } ... } }

If the dialog result is true, the function uses that as a cue to retrieve and process the data provided by the user.

Note After ShowDialog has returned, a dialog box cannot be reopened. Instead, you need to create a new instance. If the dialog result is false, the function should end processing appropriately. Creating a Modeless Custom Dialog Box

A modeless dialog box, such as the Find Dialog Box shown in the following figure, has the same fundamental appearance as the modal dialog box.

However, the behavior is slightly different, as described in the following sections. Opening a Modeless Dialog Box

A modeless dialog box is opened by calling the Show method. XAML


<!--Main Window-->

C# VB
using using using using using System; // EventArgs System.ComponentModel; // CancelEventArgs System.Windows; // Window, MessageBoxXxx, RoutedEventArgs System.Windows.Controls; // TextChangedEventArgs Microsoft.Win32; // OpenFileDialog

namespace SDKSample { public partial class MainWindow : Window { ... void editFindMenuItem_Click(object sender, RoutedEventArgs e) { // Instantiate the dialog box

FindDialogBox dlg = new FindDialogBox(this.documentTextBox); // Configure the dialog box dlg.Owner = this; dlg.TextFound += new TextFoundEventHandler(dlg_TextFound); // Open the dialog box modally dlg.Show(); } ... } }

Unlike ShowDialog, Show returns immediately. Consequently, the calling window cannot tell when the modeless dialog box is closed and, therefore, does not know when to check for a dialog box result or get data from the dialog box for further processing. Instead, the dialog box needs to create an alternative way to return data to the calling window for processing. Processing Data Returned from a Modeless Dialog Box

In this example, the FindDialogBox may return one or more find results to the main window, depending on the text being searched for without any specific frequency. As with a modal dialog box, a modeless dialog box can return results using properties. However, the window that owns the dialog box needs to know when to check those properties. One way to enable this is for the dialog box to implement an event that is raised whenever text is found. FindDialogBox implements the TextFoundEvent for this purpose, which first requires a delegate. C# VB
using System; namespace SDKSample { public delegate void TextFoundEventHandler(object sender, EventArgs e); }

Using the TextFoundEventHandler delegate, FindDialogBox implements the TextFoundEvent. C# VB


using using using using System; // EventArgs System.Windows; // Window, MessageBoxXxx, RoutedEventArgs System.Windows.Controls; // TextBox, TextChangedEventArgs System.Text.RegularExpressions; // Regex

namespace SDKSample { public partial class FindDialogBox : Window

{ public event TextFoundEventHandler TextFound; protected virtual void OnTextFound() { TextFoundEventHandler textFound = this.TextFound; if (textFound != null) textFound(this, EventArgs.Empty); } ... } }

Consequently, Find can raise the event when a search result is found. C# VB
using using using using System; // EventArgs System.Windows; // Window, MessageBoxXxx, RoutedEventArgs System.Windows.Controls; // TextBox, TextChangedEventArgs System.Text.RegularExpressions; // Regex

namespace SDKSample { public partial class FindDialogBox : Window { ... void findNextButton_Click(object sender, RoutedEventArgs e) { ... // Text found this.index = match.Index; this.length = match.Length; OnTextFound(); ... } ... }

The owner window then needs to register with and handle this event. C# VB
using using using using using System; // EventArgs System.ComponentModel; // CancelEventArgs System.Windows; // Window, MessageBoxXxx, RoutedEventArgs System.Windows.Controls; // TextChangedEventArgs Microsoft.Win32; // OpenFileDialog

namespace SDKSample { public partial class MainWindow : Window { ... void dlg_TextFound(object sender, EventArgs e) { // Get the find dialog box that raised the event FindDialogBox dlg = (FindDialogBox)sender; // Get find results and select found text this.documentTextBox.Select(dlg.Index, dlg.Length); this.documentTextBox.Focus(); } } }

Closing a Modeless Dialog Box

Because DialogResult does not need to be set, a modeless dialog can be closed using system provide mechanisms, including the following:

Clicking the Close button in the title bar. Pressing ALT+F4. Choosing Close from the System menu.

Alternatively, your code can call Close when the Close button is clicked. C# VB
using using using using System; // EventArgs System.Windows; // Window, MessageBoxXxx, RoutedEventArgs System.Windows.Controls; // TextBox, TextChangedEventArgs System.Text.RegularExpressions; // Regex

namespace SDKSample

{ public partial class FindDialogBox : Window { ... void closeButton_Click(object sender, RoutedEventArgs e) { // Close dialog box this.Close(); } } }

Q 9 Explain properties with its types


Creating your own Properties in VB .NET Classes

You can add your own Properties to your Class. A Property, remember, is something that changes or sets a value. Examples are, setting the Text in a textbox, changing the background colour of a Form, and setting a Button to be Enabled. You can Get values from a Property or Set them. So for a Textbox, you can Set the text to appear in the textbox, or you can Get what text is inside of the textbox. You use these same words, Get and Set, when you're creating your own Properties. An example might clear things up. Before you do the following, download the image you will need for this tutorial: Download the image for these tutorials (WinZip file) Once you have the images on your hard drive, do the following:

Add a Picture Box control to your Form Set the SizeMode Property of the Picture box to StretchImage Click on the Image Property, and add the planet.jpg image that you downloaded above Add two textboxes to the form. Change the Name of the first one to txtHeight, and the second one to txtWidth. Enter 300 as a the text for both textboxes Add two labels to the form. Set the Text of the first one to Height, and the second one to Width. Move them next to the textboxes Add a new button to your form. Set the Text property to Change Height and Width

What well do is to give our object the capability of setting a Height and Width property. When the object has done its work, the height and width of the picture box will change to the values from the textboxes. Off we go then.

VB needs to know that you want to set up a Property for your Class. The way you do this is type "Public Property End Property". Access the code for your Class. Type a few lines of space between the End Sub of your DoMessageBox Method, and the line that reads "End Class". On a new line, type the following: Public Property ChangeHeight() As Integer ChangeHeight is the name of our property, and it's something we made up ourselves. After a pair of round brackets, you add the type of value that will be returned (Just like a function). Here, we want to return an Integer value. When you press the return key after typing that line, VB finishes off the rest of the code stub for you: Public Property ChangeHeight() As Integer Get End Get Set(ByVal Value As Integer) End Set End Property Before the code is explained, add a new variable right at the top of your code, just below "Public Class changeHeightWidth". Add this: Private intHeight As Integer The Private word means that only code inside of the Class can see this variable. You can't access this code directly from a button on a Form, for example. The reason the variable is right at the top is so that other chunks of code can see and use it.

No more reading these lessons online - get the eBook here!

But your coding window should now look something like this next image:

With the Get and Set parts, the Property stub is this: Public Property PropertyName() As VaraibleType End Property The reason the Get and Set are there is so that you can Set a value for your property, and get a value back out. To Set a value, the code inside of Property is this: Set( ByVal Value As Integer ) End Set The Set word is followed by a pair of round brackets. Inside of the round brackets is ByVal Value As Integer. The is just like a Sub, when you hand over a value to it. The name of the variable, Value, is a default name. You can change this to anything you like. The type of variable, As Integer, is also a default. You don't have to pass numbers to you property. If you want your Property to handle text you might have something like this: Set( ByVal MyText As String )

But you couldn't do this: Set( ByVal Value As Integer, ByVal MyString As String ) In other words, you can't pass two values to your property. You can only pass one value. But we want to pass a number to our property. For us, this value will come from the textbox on the form. Whatever number is inside of the textbox will get handed over to our Property. Set( ByVal Value As Integer ) But we need to use this value being handed over. We can assign it to that variable we set up at the top of the Class. So add this to your code (The new line is in bold): Set(ByVal Value As Integer) intHeight = Value End Set Whenever our Property is called into action, we're setting a Value, and then handing that value to a variable called intHeight. This is known as Writing to a Property. To read from a Property, you use Get. This will Get a value back out of your Property. The code stub is this: Get End Get You don't need any round brackets for the Get part. You're just fetching something to be read. Add the line in bold text to your Get statement. Get ChangeHeight = intHeight End Get All you're doing here is returning a value, just like you do with a function. You're handing a value to whatever name you called your property. We called ours ChangeHeight. It's an Integer. So we can pass whatever value was stored inside of intHeight over to the variable called ChangeHeight: ChangeHeight = intHeight

You can also use the Return keyword. Like this: Get Return intHeight End Get Let's see how to use our new Property. (It's not a terribly useful property, by the way. A Picture box already has a Height and Width property that you can use. So ours is a bit redundant. But we're keeping it simple so that you can understand how to create your own properties. And it's not a good idea to put this Property into the code for your ConvertPostcode Class. After all, what has the height and width of a picture box got to do with postcodes? But we've added it here just for convenience sake.)

Q 10 Access Specifiers

Access Modifiers (Access Specifiers) describes as the scope of accessibility of an Object and its members. All C# types and type members have an accessibility level . We can control the scope of the member object of a class using access specifiers. We are using access modifiers for providing security of our applications. When we specify the accessibility of a type or member we have to declare it by using any of the access modifiers provided by CSharp language. C# provide five access specifiers , they are as follows : public, private , protected , internal and protected internal . public : public is the most common access specifier in C# . It can be access from anywhere, that means there is no restriction on accessibility. The scope of the accessibility is inside class as well as outside. The type or member can be accessed by any other code in the same assembly or another assembly that references it. private : The scope of the accessibility is limited only inside the classes or struct in which they are declared. The private members cannot be accessed outside the class and it is the least permissive access level.

protected : The scope of accessibility is limited within the class or struct and the class derived (Inherited )from this class. internal : The internal access modifiers can access within the program that contain its declarations and also access within the same assembly level but not from another assembly. protected internal : Protected internal is the same access levels of both protected and internal. It can access anywhere in the same assembly and in the same class also the classes inherited from the same class . Q 11 number is prime or not program
using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace ConsoleApplication20jan { class Class5 { static void Main() { Console.WriteLine("Enter number : "); int n = Convert.ToInt32(Console.ReadLine()); for (int a = 2; a <= n / 2; a++) { if (n % a== 0) { Console.WriteLine("Number is not prime");

return; } } Console.WriteLine("Number is Prime");

} } }

Q 12 Program to Check a Perfect Number in C#

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Perfect { static void Main() { int no, i = 1, sum = 0; try { Console.WriteLine("enter a number:"); no = int.Parse(Console.ReadLine()); while (i < no) { if (no % i == 0) { sum = sum + i; } i++; } if (no == sum) Console.WriteLine("This is Perfect"); else Console.WriteLine("This is not Perfect"); } catch (FormatException e) {

Console.WriteLine("Input should be integer type"); } } } }

Q15 what is the difference between data adapter and data reader?
A DataReader is an object returned from the ExecuteReader method of a DbCommand object. It is a forward-only cursor over the rows in the each result set. Using a DataReader, you can access each column of the result set, read all rows of the set, and advance to the next result set if there are more than one. A DataAdapter is an object that contains four DbCommand objects: one each for SELECT, INSERT, DELETE and UPDATE commands. It mediates between these commands and a DataSet though the Fill and Update methods. Datareader is connected mode. and read and forward-only Data. DataAdapter is Bridge between Database and DataSet.

OR
Data Reader: It take the data sequentially from the command object and requies the connection should be open while it is getting data. Data Adapter: It fetch all the required data from database and pass it to DataSet. DataSet: It get all the required data from Data Adapter. It contains data in the form of Data Table. DataSet : it is a disconnected Articeture... Connected Architecture : Means that while SqlDataReader reads the data from database and also reading data from SqlDataReader to any variable the connection to database should be open. Also once you read some data from SqlDataReader, you should save them becouse it is not possible to go back and read it again. DataReader : it is a Connected Articeture... Disconnected Architecture : It is followed by Dataset. In this once the data has been read by Dataset from SqlDataAdapter, we can close the connection to database and retirve the data from

Dataset where ever we want. Dataset hold the data in the form of table and do not interact with Datasouse.

Q 16 Validation Controls: This set of controls provide Rapid Application Development (RAD) features for automatically checking the specified validity of user inputs. These controls are available in the System.Web.UI.WebControls namespace. One of the most tiresome tasks when building interactive web applications is the requirement for validating values that the user enters into the input controls. This is particularly the case if we need to perform client-side as well as server side validation. Mostly, we use JavaScript for client side coding. Help is at hand with the range of validation controls that are included in ASP.NET. They cover almost all the validation scenarios. A validation control enables us to validate an input and display an error message if necessary. It is very much like other server-side controls, with certain additional methods and properties. First, the server treats it as an invisible control. After the user has entered erroneous data, it becomes visible. It is a powerful, rapid application development feature; however, a developer needs to understand its behavior and the methods thoroughly before he or she can appreciate it. All the validation controls inherit from the base class BaseValidator, which is part of the class library namespace. System.Web.UI.WebControls.BaseValidator exposes a series of properties and methods that are common to all the validation controls.

OR
Why we use validation controls? Validation is important part of any web application. User's input must always be validated before sending across different layers of the application. Validation controls are used to: Implement presentation logic. To validate user input data. Data format, data type and data range is used for validation.

Validation is of two types:

1. Client Side 2. Serve Side

Client side validation is good but we have to be dependent on browser and scripting language support. Client side validation is considered convenient for users as they get instant feedback. The main advantage is that it prevents a page from being postback to the server until the client validation is executed successfully. For developer point of view serve side is preferable because it will not fail, it is not dependent on browser and scripting language. You can use ASP.NET validation, which will ensure client, and server validation. It work on both end; first it will work on client validation and than on server validation. At any cost server validation will work always whether client validation is executed or not. So you have a safety of validation check. For client script .NET used JavaScript. WebUIValidation.js file is used for client validation by .NET Validation Controls in ASP.NET An important aspect of creating ASP.NET Web pages for user input is to be able to check that the information users enter is valid. ASP.NET provides a set of validation controls that provide an easy-to-use but powerful way to check for errors and, if necessary, display messages to the user. There are six types of validation controls in ASP.NET

1. 2. 3. 4. 5. 6.

RequiredFieldValidation Control CompareValidator Control RangeValidator Control RegularExpressionValidator Control CustomValidator Control ValidationSummary

The below table describes the controls and their work: Validation Control Description RequiredFieldValidation Makes an input control a required field CompareValidator Compares the value of one input control to the value of another input control or to a fixed value RangeValidator Checks that the user enters a value that falls between two values RegularExpressionValidator Ensures that the value of an input control matches a specified pattern CustomValidator Allows you to write a method to handle the validation of the value entered ValidationSummary Displays a report of all validation errors occurred in a Web page All validation controls are rendered in form as <span> (label are referred as <span> on client by server) Important points for validation controls ControlToValidate property is mandatory to all validate controls. One validation control will validate only one input control but multiple validate control can be assigned to a input control.

Q17 Form navigation methods in in Asp.net


ASP.NET supports following ways to navigate between pages in your application.

Hyperlink control
This is server control use for navigation to another page specified in the NavigateURL property. Hyperlink control doesnt expose any server side event.

Response.Redirect method
This method is used to navigate to another page from code. You can use this method to navigate from a Linkbutton or ImageButton control. For example Private Sub LinkButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkButton1.Click Response.Redirect("Page2.aspx") End Sub

Server.Transfer method
This method can be used only with .aspx file. It allows to retain some information between the requests when its preserveForm argument is set to true.

Server.Execute method
Like Server.Transfer, this method is also used with .aspx file only. This method enables new page execution while still displaying the current web form.

Window.Open method
Display a page in a new browser window on the client. Explain the difference between Server.Transfer and response.Redirect. Redirect and Transfer both cause a new page to be processed. The difference lies in the way the interaction between the client and the server occurs. Response.Redirect messages the client browser asking it to request for another page. e.g. if a browser is on page A which has a Response.Redirect, then it asked to request for another page B by the server. When the client browser requests for it, then it is provided with the requested page B. With Server.Transfer, the browser is not requested to ask for another page. Instead it is directly provided with the page B. In this scenario, the browser address bar continues to show the address of the previous URL.

Q 18 explain intrinsic controls in asp.net

All the controls like label, textbox etc... except Validations controls and Calender Control and AdRototer Controls are called intrinsic controls Calender Control and AdRototer Controls are called Rich Controls In ASP.NET there are two types of controls - HTML server controls and ASP.NET server controls. The HTML ones are known as Intrinsic controls. A HTML Server Control has similar abstraction with its corresponding HTML tag and offers no abstraction. ASP .NET Server Controls have higher level of abstraction. An output of an ASP .NET server control can be the result of many HTML tags that combine together to produce that control and its events. The HTML Server Controls follow the HTML-centric object model. ASP .NET Server Controls have an object model different from the traditional HTML and even provide a set of properties and methods that can change the outlook and behavior of the controls. The HTML Server Controls have no mechanism of identifying the capabilities of the client browser accessing the current page. ASP .NET Server Controls can however detect the target browser's capabilities and render themselves accordingly.

Q 19 State management in asp .net


Introduction
This article looks at the need for state management in ASP.NET applications, what are the various ways of state management in ASP.NET and a comparative analysis of all the state management techniques.

Background
HTTP is a stateless protocol. Once the server serves any request from the user, it cleans up all the resources used to serve that request. These resources include the objects created during that request, the memory allocated during that request, etc. For a guy coming from a background of Windows application development, this could come as a big surprise because there is no way he could rely on objects and member variables alone to keep track of the current state of the application. If we have to track the users' information between page visits and even on multiple visits of the same page, then we need to use the State management techniques provided by ASP.NET. State management is the process by which ASP.NET let the developers maintain state and page information over multiple request for the same or different pages.

Types of State Management


There are mainly two types of state management that ASP.NET provides:
1. Client side state management 2. Server side state management

When we use client side state management, the state related information will be stored on client side. This information will travel back and forth with every request and response. This can be visualized as:

Note: Image taken from Microsoft press' Book. The major benefit of having this kind of state management is that we relieve the server from the burden of keeping the state related information, it saves a lot of server memory. The downside of client side state management is that it takes more bandwidth as considerable amount of data is traveling back and forth. But there is one more problem which is bigger than the bandwidth usage problem. The client side state management makes the information travel back and forth and hence this information can be intercepted by anyone in between. So there is no way we can store the sensitive information like passwords, creditcard number and payable amount on client side, we need server side state management for such things. Server side state management, in contrast to client side, keeps all the information in user memory. The downside of this is more memory usage on server and the benefit is that users' confidential and sensitive information is secure.

Note: Image taken from Microsoft press' Book.

We cannot say that we will use any one type of state management in our application. We will have to find a mix of client side and server side state management depending on the type and size of information. Now let us look at what are the different ways we can manage state on client side and server side. Client side state management techniques

View State Control State Hidden fields Cookies Query Strings

Server side state management techniques


Application State Session State

View State
ASP.NET uses this mechanism to track the values of the controls on the web page between page request for same page. We can also add custom values to view state. ASP.NET framework takes care of storing the information of controls in view state and retrieving it back from viewstate before rendering on postback. If we need to use viewstate to store our information, we just need to remember that the viewstate is a dictionary object. We can have our data stored as key value pair in viewstate (see code below). The controls information is also being hashed into this dictionary during request and populated back during response. Since this information is stored in the web page itself, ASP.NET encrypts the information. We can tweak the encryption related parameters from web.config.
Collapse | Copy Code
<Configuration> <system.web> <pages viewStateEncryptionMode="Always"/> </system.web> </configuration>

or page declarative:
Collapse | Copy Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ViewStateEncryptionMode="Always"%>

Let us now look at a small implementation for viewstate. We have a simple web page with a textbox and a button. The idea is that we will write something in the text box and see how ASP.NET stores this information in view state. We will store our own information in the view state too. When we run the page and write my name in the textbox and press the button, a postback occurs but my name still remains in the textbox. Viewstate made that possible so after postback, the page looks like:

When we look at the source, the view state looks like:


Collapse | Copy Code
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTkwNjc4NTIwMWRkfIZa4Yq8wUbdaypyAjKouH5Vn1Y=" />

Now let us try to add our own information in the viewstate. Let's keep track of users' postback on this page. Whenever user will hit a button, we will add 1 to the stored pot back value. The way to do would be:
Collapse | Copy Code
protected void Page_Load(object sender, EventArgs e) { if(IsPostBack == true) { if (ViewState["number"] != null) //Lets retrieve, increase and store again { ViewState["number"] = Convert.ToInt32(ViewState["number"]) + 1; } else //First postback, lets store the info { ViewState["number"] = 1; } Label1.Text = ViewState["number"].ToString(); } }

When we run the page and hit the button to do a postback, the web will show us the postbacks being done so far which is being stored in viewstate:

View State is enabled by default, but we can disable it by setting the EnableViewState property for each web control to false. This reduces the server processing time and decreases page size.

Control State
We now know what a viewstate is and we also know that we can disable viewstate for controls on the page. But imagine if we are developing a custom control and we internally are using viewstate to store some information but the user of the control can disable the viewstate for our control. To avoid this problem, we can have viewstate like behavior which cannot be disabled by control users and it is called ControlState. Control states lies inside custom controls and work the same as viewstate works. To use control state in a custom control, we have to override the OnInit method and call the RegisterRequiresControlState method during initialization. Then we have to override the SaveControlState and LoadControlState methods.

Hidden Fields
Hidden field are the controls provided by the ASP.NET and they let use store some information in them. The only constraint on hidden filed is that it will keep the information when HTTP post is being done, i.e., button clicks. It will not work with HTTP get. Let us do the same exercise of keeping track of postbacks using HiddenFields now. (Note: ViewState also uses hidden field underneath.)
Collapse | Copy Code
//Store in Hidden Field ---------------------------------------------------------int newVal = Convert.ToInt32(HiddenField1.Value) + 1; //Hidden field default value was 0 HiddenField1.Value = newVal.ToString(); Label2.Text = HiddenField1.Value;

When we run the page and hit the button to do a postback, the web will show us the postbacks being done so far which is being stored in Hiddenfields (See code for details).

Cookies
There are scenarios when we need to store the data between page requests. So far, the techniques we have discussed store the data for the single page requests. Now we look at the techniques that store information between page requests. Cookies are small pieces of information that can be stored in a text file on users' computer. The information can be accessed by the server and can be utilized to store information that is required between page visits and between multiple visits on the same page by the user. Let us do the same exercise of keeping track of postback by using cookies.
Collapse | Copy Code
int postbacks = 0; if (Request.Cookies["number"] != null) //Lets retrieve, increase and store again { postbacks = Convert.ToInt32(Request.Cookies["number"].Value) + 1; } else //First postback, lets store the info { postbacks = 1; } Response.Cookies["number"].Value = postbacks.ToString(); Label3.Text = Response.Cookies["number"].Value;

We cannot keep track of postbacks using cookies as cookies will stay on user machine, so essentially we are looking at the number of times user POSTED back on their page so far since the beginning. When we run the page and hit the button to do a postback, the web will show us the postbacks being done so far which is being stored in Cookies (see code for details). The cookies can have various parameters like how long they are valid and when should they expire. These parameters can be manipulated as:

Collapse | Copy Code


Response.Cookies["number"].Expires = DateTime.Now.AddDays(1);

This cookie will expire after 1 day of its creation.

Query Strings
Query strings are commonly used to store variables that identify specific pages, such as search terms or page numbers. A query string is information that is appended to the end of a page URL. They can be used to store/pass information from one page to another to even the same page. Let us work on storing the postback information in querystrings now:
Collapse | Copy Code
//GetDataItem from querystring if (Request.QueryString["number"] != null) //Lets retrieve, increase and store again { Label4.Text = Request.QueryString["number"]; } //set in query string int postbacks = 0; if (Request.QueryString["number"] != null) //Lets retrieve, increase and store again { postbacks = Convert.ToInt32(Request.QueryString["number"]) + 1; } else //First postback, lets store the info { postbacks = 1; } Response.Redirect("default.aspx?number=" + postbacks);

One thing to notice here is that we can no way store the postback information in the query string we are dealing with same page. The reason is that the query string creates a new URL each time and it will be a fresh request each time we use query strings. SO we are now essentially tracking number of click here. The idea behind query string is to pass small information to OTHER pages that can be used to populate information on that page.

NOTE: The use of cookies and querystring here are just for the purpose of demonstration. In real scenarios, they should never be used to store information required for same page. The Querystrings should be used to store the information between multiple page visits. Cookies should be used to store information between multiple visits to our website from the same computer.

Application State
ASP.NET allows us to save values using application state. A global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. This information will also be available to all the users of the website. In case we need user specific information, then we better use sessionstate. ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors:
Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables. Application_End: Raised when an application shuts down. Use this to free application

resources and perform logging. Application_Error: Raised when an unhandled error occurs. Use this to perform error logging.

Let us now store the information of postbacks in application state:


Collapse | Copy Code
//global.asax void Application_Start(object sender, EventArgs e) { Application["number"] = 0; }

//In web pages Application.Lock(); Application["number"] = Convert.ToInt32(Application["number"]) + 1; Application.UnLock(); Label5.Text = Application["number"].ToString();

When we run the page and hit the button to do a postback, the web will show us the postbacks being done so far which is being stored in ApplicationState. We can use this object to keep track of clicks by all users on the entire website (see code for details).

Session State
Like Application state, this information is also in a global storage that is accessible from all pages in the Web application. Session state is stored in the Sessionkey/value dictionary. This information will be available to the current user only, i.e., current session only.
Collapse | Copy Code
//global.asax void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started Session["number"] = 0; } // Web forms Session["number"] = Convert.ToInt32(Session["number"]) + 1; Label6.Text = Session["number"].ToString();

When we run the page and hit the button to do a postback, the web will show us the postbacks being done so far which is being stored in SessionState. We can use this object to keep track of clicks by the current user, i.e., who owns the session for the entire website (see code for details).

Advantages of Client Side State Management


Better scalability Support for multiple browser

Advantages of Server Side State Management


Better security Reduced bandwidth

Q 20 Explain CODE EXECUTION PROCESS IN ASP.NET

STEP 1: Client sends request for the required file to the IIS (Webserver). STEP 2: IIS will locate the requested file. STEP 3: If requested file is found, IIS will submit that to ISAPI.dll ISAPI.dll is known as ASPX Engine. ISAPI means Internet Services Application Programming Interface. STEP 4: ISAPI.dll will generate a Page Class file, by separating Client side code, Server side code & by adding required methods to execute the server side code. STEP 5: This Page Class is submitted to Compilers (In case of pre-Compilation is not done). STEP 6: Compilers will compile the Source Code & will generate MSIL code. STEP 7: MSIL code will be submitted to CLR. CLR will perform 3 tasks here,
1. Instantiation: Creates object to the respective Page Class 2. Processing: Executes the Result/Code 3. Rendering: Converts the Server side code into Client Understandable format (i.e., HTML and JAVASCRIPT).

STEP 8: CLR will generate complete Execution Result.

STEP 9: Execution Result will be delivered to IIS. STEP 10: IIS will deliver the result to CLIENT. Once the Result is delivered to the client, The Object at the Server will be destroyed.

Shortnotes
Dataset : A DataSet is Disconnected Architecture,means their is no need to always open & close connection.it is cache of data retrieved from database.it is made up of collection of datatable.Dataset can be Typed & UnTyped usually,datasets are typed in Visual basic.A typed dataset is dataset which derived from dataset class & uses information in XML schema file(XSD file).An untyped dataset has no built in schema.it can contain tables,column & rows.but those are exposed only as collections Window Controls : use answer of Q 7

CLR : The .NET Framework provides a run-time environment called the common language runtime, which runs the code and provides services that make the development process easier. Compilers and tools expose the common language runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services. Compilers and tools are able to produce output that the common language runtime can consume because the type system, the format of metadata, and the runtime environment (the virtual execution system) are all defined by a public standard, the ECMA Common Language Infrastructure specification. For more information, see ECMA C# and Common Language Infrastructure Specifications. To enable the runtime to provide services to managed code, language compilers must emit metadata that describes the types, members, and references in your code. Metadata is stored with the code; every loadable common language runtime portable executable (PE) file contains metadata. The runtime uses metadata to locate and load classes, lay out instances in memory, resolve method invocations, generate native code, enforce security, and set run-time context boundaries. The runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. Objects whose lifetimes are managed in this way are called managed data. Garbage collection eliminates memory leaks as well as some other common programming errors. If your code is managed, you can use managed data, unmanaged data, or both managed and unmanaged data in your .NET Framework application. Because language compilers supply their own types, such as primitive types, you might not always know (or need to know) whether your data is being managed.

The common language runtime makes it easy to design components and applications whose objects interact across languages. Objects written in different languages can communicate with each other, and their behaviors can be tightly integrated. For example, you can define a class and then use a different language to derive a class from your original class or call a method on the original class. You can also pass an instance of a class to a method of a class written in a different language. This cross-language integration is possible because language compilers and tools that target the runtime use a common type system defined by the runtime, and they follow the runtime's rules for defining new types, as well as for creating, using, persisting, and binding to types. As part of their metadata, all managed components carry information about the components and resources they were built against. The runtime uses this information to ensure that your component or application has the specified versions of everything it needs, which makes your code less likely to break because of some unmet dependency. Registration information and state data are no longer stored in the registry where they can be difficult to establish and maintain. Instead, information about the types you define (and their dependencies) is stored with the code as metadata, making the tasks of component replication and removal much less complicated. Language compilers and tools expose the runtime's functionality in ways that are intended to be useful and intuitive to developers. This means that some features of the runtime might be more noticeable in one environment than in another. How you experience the runtime depends on which language compilers or tools you use. For example, if you are a Visual Basic developer, you might notice that with the common language runtime, the Visual Basic language has more object-oriented features than before. The runtime provides the following benefits:

Performance improvements. The ability to easily use components developed in other languages. Extensible types provided by a class library. Language features such as inheritance, interfaces, and overloading for object-oriented programming. Support for explicit free threading that allows creation of multithreaded, scalable applications. Support for structured exception handling. Support for custom attributes. Garbage collection. Use of delegates instead of function pointers for increased type safety and security. For more information about delegates, see Common Type System.

OR
As part of Microsoft's .NET Framework, the Common Language Runtime (CLR) is programming that manages the execution of programs written in any of several supported languages, allowing them to share common object-oriented class es written in any of the languages. The Common Language Runtime is somewhat comparable to the Java Virtual Machine that Sun Microsystems furnishes for running programs compiled from the Java language. Microsoft refers to its Common Language Runtime as a "managed execution environment." A program compiled for the CLR does not need a language-specific

execution environment and can easily be moved to and run on any system with Windows 2000 or Windows XP .Programmers writing in any of Visual Basic , Visual C++ , or C# compile their programs into an intermediate form of code called Common Intermediate Language ( CIL ) in a portable execution ( PE ) file that can then be managed and executed by the Common Language Runtime. The programmer and the environment specify descriptive information about the program when it is compiled and the information is stored with the compiled program as metadata . Metadata, stored in the compiled program, tells the CLR what language was used, its version, and what class libraries will be needed by the program. The Common Language Runtime allows an instance of a class written in one language to call a method of a class written in another language. It also provides garbage collecting (returning unneeded memory to the computer), exception handling, and debugging services.

CTS: Common Type System


The common type system defines how types are declared, used, and managed in the runtime, and is also an important part of the runtime's support for cross-language integration. The common type system performs the following functions:

Establishes a framework that helps enable cross-language integration, type safety, and high performance code execution. Provides an object-oriented model that supports the complete implementation of many programming languages. Defines rules that languages must follow, which helps ensure that objects written in different languages can interact with each other.

What is CLR,CTS, CLS CLR this is common language runtime.the code which is in environment of clr is called managed code.every language has runtime in case of .net there is CLR.so that that has some responsibilites that is to tack care of the execution of code other responsibilites garbage collection-in that it remove the object which are not refered for long time.using Idisposable interface with dispose method

Jit compiler also convert IT to native code In that include exception handling.etc

Cls common language spefication thsi is guideline that to communicate smoothly with other CTS common type system this is used to communicate with other language. example in vb we have int and in c++ we have long so that in one case they are not compatiable with each other so that CTS palys important role with using System.int32

CLS :
To fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with. For this reason, the Common Language Specification (CLS), which is a set of basic language features needed by many applications, has been defined. The CLS rules define a subset of the common type system; that is, all the rules that apply to the common type system apply to the CLS, except where stricter rules are defined in the CLS. The CLS helps enhance and ensure language interoperability by defining a set of features that developers can rely on to be available in a wide variety of languages. The CLS also establishes requirements for CLS compliance; these help you determine whether your managed code conforms to the CLS and to what extent a given tool supports the development of managed code that uses CLS features. If your component uses only CLS features in the API that it exposes to other code (including derived classes), the component is guaranteed to be accessible from any programming language that supports the CLS. Components that adhere to the CLS rules and use only the features included in the CLS are said to be CLS-compliant components. Most of the members defined by types in the .NET Framework class library are CLS-compliant. However, some types in the class library have one or more members that are not CLS-compliant. These members enable support for language features that are not in the CLS. The types and members that are not CLS-compliant are identified as such in the reference documentation, and in all cases a CLS-compliant alternative is available. For more information about the types in the .NET Framework class library, see the .NET Framework Reference. The CLS was designed to be large enough to include the language constructs that are commonly needed by developers, yet small enough that most languages are able to support it. In addition, any language construct that makes it impossible to rapidly verify the type safety of code was excluded from the CLS so that all CLS-compliant languages can produce verifiable code if they choose to do so. For more information about verification of type safety, see JIT Compilation.

Window controls In C # .net Refer to Answer of Q7

Você também pode gostar