Monday, May 21, 2007
Deploying Windows Applications
Deployment is the process of installing applications to the target systems. Traditionally such an installation has been done by invoking a setup program. If hundred or thousand clients must be installed, the installation can be very time consuming. To alleviate this, the system admin can create batch scripts to automate this activity.
What is DLL Hell problem?
DLL hell describes the problems that happen when each of several installed applications require different versions of the same DLL. If one application installs a DLL that overwrites a different version of the same DLL, applications requiring the overwritten DLL might break.
How is the .NET DLL Hell avoided?
The .NET DLL hell is avoided by using the private and shared assemblies. Private assemblies are copied with every application, so there cannot be a conflict with assemblies from other applications. Shared assemblies have strong name that includes the version number. Multiple versions of the same assembly can coexist on the same system.
No-touch Deployment: the .NET 1.0 supported a technology known as no-touch deployment. With no-touch deployment, it was possible for the user to automatically install an application by clicking a link on a Web page. However, .NET 1.0 no-touch deployment had some complexity because of security issues, and it was missing many features that are required with many client applications – clearly this was a version 1 release. These issues are solved with the ClickOnce deployment technology that is new with .NET 2.0.
xcopy deployment: Simple application can be installed with a simple xcopy deployment, but for installation to hundreds of clients, an xcopy deployment is not really useful. For this you have two options:
1. ClickOnce deployment
2. Microsoft Installer
ClickOnce deployment: with this the application can be installed automatically by clicking a link inside a Web page. The user on the client system doesn’t need administrative privileges, as the application is installed in a user-specific directory.
· With ClickOnce you can install applications with a rich user interface.
· After the application is installed to the client, the client can be offline – there is no need for the client to access the server where application was installed from
· Application can be used offline
· The updates can happen automatically when the client application starts or as a background task while the client application is running.
· The installation can be done from a website, a UNC share, or a file location.
· The application is installed on the client system, it is available with Start menu shortcuts, and it can be uninstalled from the Add/Remove Programs dialog.
ClickOnce deployment is described by manifest files.
· The application manifest describes the application and permissions required by the application.
· The deployment manifest describes deployment configuration such as update policies.
Successfully deploying the assembly across the network requires that the manifest that is used with the installation must have a certificate associated. The certificate shows for the user installing the application about the organization that created the installation program.
How is the ClickOnce deployment different to no-touch deployment?
With the ClickOnce deployment, an application icon is available from the Start menu, the security issues are easier to solve, and the application can easily be uninstalled.
What are the restrictions with the ClickOnce deployment?
ClickOnce cannot be used
· if you need to install shared components in the GAC
· if the application needs COM Components that require Registry settings
· if you want the user to decide in what directory the application should be installed.
In all the above restriction cases, you must use the Windows Installer. The Windows Installer is the traditional way to install windows applications.
Why do you need to create a Test Certificate that is associated with the ClickOnce manifests?
A certificate is used that the user installing the application can identify the creator of the installation package. By reading the certificate, the user can decide if he can trust the installation to approve the security requirements.
Note: with the test certificate, if the user doesn’t get real trust information and receives a warning that “this certificate cannot be trusted”. Such certificate is for testing only. Before you make the application ready for deployment, you have to get a real certificate from a certification authority such as Verisign. If the application is deployed only within the Intranet, you can also get a certificate from a local certificate server. For ex: the MS Certificate server can be installed with Windows Server 2003.
How are the required permissions defined with ClickOnce deployment?
How do you Calculate Permissions that is associated with the ClickOnce Security Settings?
The .NET uses evidence-based security to define what assemblies are allowed to do.
· Resources should be secured (Exs of resources are: files, directories, networking sockets, and environmental variables. For all these resources, .NET permissions exist that allow access to them. Ex is the FileIOPermission class, which is used to allow access to the complete file system or to specific files and directories.
· Must define who is allowed to use these resources. Exs of such groups are assemblies that are installed locally, or loaded from the n/w.
With the Calculate Permissions from the Security Properties of VS, analyzes the code used by the application to check the application’s permission requirements.
Note: with the defined security requirements, you can start to publish the application by creating a deployment manifest. This can easily be done with the Publish Wizard.
What does the Publish Wizard do?
The Publish Wizard creates a website on the local Internet Information Services Web server. The assemblies of the application (exe & dlls) as well as the application and deployment manifests, a set.exe and a sample webpage, publish.htm are copied to the webserver
Note: the application will be available online or offline by selecting its option. This way the application is installed on the client system and can be accessed from the start menu.
If you select that the application to be available only online, the user must always click the Website link to load the application from the server and start it locally.
What is an Update Policy?
The Update Policy is defined by a setting in the deployment manifest with the XML element >update>. You can change the update policy by clicking the Updates… button with the Publish Settings.
In the Application Updates dialog, you can define whether the client should look for updates. If updates should be checked, you can define whether the check should happen before the application starts or if the update should occur in the background while the application is running. If the update should occur in the background, you can set the time interval for them, with every start of the application or with a specific number of hours, days, or weeks.
What template is used for deploying Windows Applications?
In the Add New Project dialog, Other Project Types > Setup and Deployment > the Setup Project template is the one you will use. This template is used to create Windows Installer Packages, so it can be used for deploying Windows Applications.
Note: the Web Setup Project template is used to install Web applications.
When is the Merge Module Project template used?
The Merge Module Project template is used to create Windows Installer merge modules. A merge module is n installer file that can be included in multiple Microsoft Installer installation packages. For components that should be installed with more than one installation program, a merge module can be created to include this module in the installation package.
Ex is: .NET runtime itself. It is delivered in a merge module; therefore the .NET runtime can be included with the installer package of an application. You will use a merge module in the sample application.
When is the Setup Wizard template used?
The Setup Wizard is a step-by-step way to choose the other templates.
When is the Can Project template used?
The can project template allows you to create cabinet files. Cabinet files can be used to merge multiple assemblies into a single file and compress it. Since the cabinet files can be compressed, a Web client can download a smaller file from the server.
When is the Smart Device Cab Project template used?
The Smart Device Cab Project template can be used to create an installer package for smart applications.
Windows Installer Terms:
1. Packages
2. Features
3. Components
Note: In the Context of the Windows Installer, a component is not the same as a component in the .NET Framework. A Windows Installer component is just a single file (or multiple files that are logically belong together). Such a file can be an executable, a DLL or even a simple text file.
Package: consists of one or more features. A package is a single MS Installer database (MSI db).
Feature: is the user’s view of the capabilities of a product and can consist of features and components.
Component: is the developer’s view of the installation; it is the smallest unit of installation and consists of one or more files.
Differnce b/w features and components is:
· Single component can be included within multiple features
· A single feature cannot be included within multiple features
What are the advantages of the Windows Installer?
· Features can be installed, not installed, or advertised
· If an application becomes corrupt, it can self-repair through the repair feature of Windows Installer package
· An automatic rollback will be done if the installation fails. After the installation fails everything is left as before: no additional Registry Keys, no files, and so on, are left on the system
· With uninstall, all relevant files, Registry keys, and so on are removed—the application can be completely uninstalled. No temporary files are left out, and the Registry is also reinstated.
Note: you can read the tables of the MSI db files to find information about such things as what files are copied and what Registry keys are written.
What are the different files and directories should we use for building the installation program?
1. Files needed for the application
1. Documentation file
2. Readme.txt file
3. License file
4. Document template
5. Pictures
6. Configuration files
2. Directories should be used?
1. Application files should be installed in Program Files\Application name
2. With the installer, you can use a special predefined folder to put files in the Program Files directory.
Note: Under no circumstances should the directories be hard-coded. The Simple Editor will have the executable in the default application directory unless the installing user selects a different path.
3. How should the user access the application?
1. You can put a shortcut to the executable in the Start menu, or place an icon on the desktop.
Note: With Windows XP, the guideline is to have the desktop as clean as possible.
4. What is the distribution media?
1. Put the installation packages in a CD, floppy, disks or a network share.
5. What questions should the user answer?
1. Accept the license information
2. Show a ReadMe file
3. logo
4. Enter the path (directory) to install
When is it necessary to use the windows installer?
· if you need to install shared components in the GAC
· if the application needs COM Components that require Registry settings
· if you want the user to decide in what directory the application should be installed.
In all the above restriction cases, you must use the Windows Installer. The Windows Installer is the traditional way to install windows applications.
What are the different packaging options of the files that are installed?
The files that are to be installed are packaged with three options:
· As loose uncompressed files à stores all program and data files as they are. No compressing takes place
· In setup file à merges and compresses all the files into the MSI file. This file can be overridden for single components in the package.
· In Cabinet file(s) à with this method, the MSI file is used just to load and install the CAB files. With CAB files, it is possible to set file sizes that enable installations on CDs or floppy disks.
What different editors can you use to create a Windows Installer package using Visual Studio?
With a VS 2005 Setup Project you have six editors available. They are as follows:
1. File System Editor à is used to add files to the installation package.
2. Registry Editor à you can create Registry keys for the application.
3. File Types Editor à allows you to register specific file extensions for an application.
4. User Interface Editor à you can add and configure dialogs that are shown during installation of the product.
5. Custom Actions Editor à allows you to start custom programs during installation and uninstallation.
6. Launch Conditions Editor à you can specify requirements for your application, for ex, that the .NET runtime already has to be in place.
What is File System Editor?
With the File System Editor, you can add files to the installation package and configure the locations where they should be installed.
The editor is opened with the menu options View à Editor à File System.
What are the predefine special Folders in the File System Editor?
Some of the predefined special folders are automatically opened and they are:
· Application Folder
· User’s Desktop
· User’s Programs Menu
1. The Application Folder is used to store the executables and libraries. The location is defined as:
[ProgramFilesFolder]\[Manufacturer]\[ProductName]
2. The User’s Desktop Folder can be used to place the icon on the desktop. The default path to this folder is:
C:\Documents and Settings\username\Desktop à if the installation is done for single user
[or]
C:\Documents and Settings\All Users\Desktop à if the installation is done for all users
3. User’s Program Menu Folder: The user will usually start a program by starting it from the All Programs menu. The default path is:
C:\ Docuements and Settings\username\Start Menu\Programs
You can put a shortcut to the application menu. The shortcut should have a name that includes the company and the application name, so that the user can easily identify the application.
Note: do not put the uninstall program and help file in this menu.
Note: You can set the following properties of file in a folder:
1. Condition
2. Exclude
3. PackageAs
4. Permanent
5. ReadOnly
6. Vital
For Ex: You may want the readme file to be available for the user to read before the installation is started.
· So set the property PackageAs to vsdpaLoose, do that this readme file will not be compressed into the Installer package.
· Also set the ReadOnly property to true so that this file cannot be changed.
What is File Types Editor?
If your application uses custom file types and you want to register file extensions for files that should start your application when a user double-clicks them, you can use the File Types Editor.
The Editor can be started with View à Editor à File Types.
With the File Types Editor, you can configure a file extension that should be handled from your application. The extension has the following properties:
· Name
· Command
· Description
· Extension
· Icon
What is Launch Condition Editor?
With the Launch Editor you can specify some requirements that the target system must have before the installation can take place.
You can start the Launch Editor by selecting the menu View à Editor à Launch Conditions
This editor has two sections to specify the requirements:
· Search Target Machine à Specify what specific file or Registry key to search for
· Launch Conditions à defines the error message if the search is not successful
What are the different Launch Conditions you can define using the Action Menu?
1. File Launch Condition à searches the target system for a file you define before the installation starts.
2. Registry Launch Condition à allows you to require a check of Registry keys before the installation starts.
3. Windows Installer Launch Condition à search for Windows Installer components that must be present.
4. .NET Framework Launch Condition à checks if the .NET Framework is already installed on the target system.
5. Internet Information Services Launch Condition à checks for the installed IIS. Adding this launch conditions adds a Registry Search for a specific Registry Key that is defined when IIS is installed, and adds a condition to check for a specific version.
Note: By default, a .NET Framework Launch Condition is included, and its properties have been set to predefined values: the Message property is set to [VSDNETMSG], which is a predefined error message. If the .NET Framework is not installed, a message informing the user to install the .NET Framework pops up.
What is User Interface Editor?
With the User Interface Editor, you can define the dialogs the user sees when configuring the installation. Here, you can inform the user about license agreements and ask for installation paths and other information to configure the application.
You can start the User Interface Editor by selecting the menu View à Editor à User Interface
What are the two installation modes available in the User Interface Editor?
· Install Mode à used to install the application on a target system
· Administrative Install à install an image of the application on a network share. Afterward a user can install the application from the network.
What are the Default Dialogs in the User Interface Editor?
· Start
o Welcome
o Installation Folder
o Confirm Installation
· Progress
o Progress
· End
Note: The Default Dialogs will show up automatically at installation time, even if you never opened the User Interface Editor in the solution. But you should configure these dialogs so that useful messages for your application are displayed.
How do you add Additional or Custom Dialogs to the User Interface Editor?
You cannot design a custom dialog and add it to the installation sequence with the VS installer.
A more sophisticated tool such as InstallShield or Wise for Windows is required to do this – but with the VS installer, you can add and customize many of the predefined dialogs in the Add Dialog screen.
Selecting the Start Sequence in the User Interface Editor and choosing the menu options Action à Add Dialog, causes the Add Dialog to be displayed. All these dialogs are configurable. You can configure these dialogs by setting their properties.
Garbage Collection
The garbage collector is .NET’s answer to memory management, and in particular to the question of what to do about reclaiming memory that running application ask for. Up until now two techniques have been used on the Windows platform for deallocating memory that processes have dynamically requested from the system.
· Make the application code do it all manually.
· Make objects maintain reference counts.
When should you call the garbage collector in .NET?
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 very large objects from memory. However, this is usually not a good practice.
Is there a way to force garbage collection?
Yes, set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().
CLR, CTS, CLS, JIT, MSIL, Managed Code
The .NET Framework provides a runtime environment called the Common Language Runtime or CLR (similar to the Java Virtual Machine or JVM in Java), which handles the execution of code and provides useful services for the implementation of the program. CLR takes care of code management at program execution and provides various beneficial services such as memory management, thread management, security management, code verification, compilation, and other system services. The managed code that targets CLR benefits from useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging. Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution. The CLS is simply a specification that defines the rules to support language integration in such a way that programs written in any language, yet can interoperate with one another, taking full advantage of inheritance, polymorphism, exceptions, and other features. These rules and the specification are documented in the ECMA proposed standard document, "Partition I Architecture", http://msdn.microsoft.com/net/ecma/
Is .NET a runtime service or a development platform?Ans: It's both and actually a lot more. Microsoft .NET includes a new way of delivering software and services to businesses and consumers. A part of Microsoft.NET is the .NET Frameworks. The .NET frameworks SDK consists of two parts: the .NET common language runtime and the .NET class library. In addition, the SDK also includes command-line compilers for C#, C++, JScript, and VB. You use these compilers to build applications and components. These components require the runtime to execute so this is a development platform. What is MSIL, IL?When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Microsoft intermediate language (MSIL) is a language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler. The common language runtime includes a JIT compiler for converting MSIL to native code.
Can I write IL programs directly?
Yes. Peter Drayton posted this simple example to the DOTNET mailing list:
.assembly MyAssembly {}
.class MyApp {
.method static void Main() {
.entrypoint
ldstr "Hello, IL!" c
all void System.Console::WriteLine(class System.Object)
ret
}
}
Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.
Can I do things in IL that I can't do in C#?
Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays.
What is JIT (just in time)? how it works?
Before Microsoft intermediate language (MSIL) can be executed, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler.
Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as it is needed during execution and stores the resulting native code so that it is accessible for subsequent calls.
The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and executed.
As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code can be determined to be type safe, which means that it is known to access only the memory locations it is authorized to access.
Define CLR (Common Language Runtime)?
Central to the .NET Framework is its runtime execution environment, known as the Common Language Runtime (CLR) or the .NET runtime.
Example: A Jagged Array can be used is to create a table in which the lengths of the rows are not same. This Array is declared using square brackets ( [ ] ) to indicate each dimension.The following code demonstrates the creation of a two-dimensional jagged array.
What is managed code (IL)?
Code running under the control of the CLR is often termed as managed code.The C# code will be compiled into IL before it is executed (i.e. the C# compiler only compiles to managed code)
Explain the compilation process by the CLR?
Any source code that is developed needs to be compiled. Compilation occurs in two steps:
1. Compilation of source code to IL
2. Compilation of the IL to platform-specific code by the CLR
What are the Advantages of Managed Code?
1. Platform Independence
2. Performance Improvement: the IL is always Just-In-Time compiled (known as JIT compilation). Instead of compiling the entire application in one go (which could lead to a slow start-up time), the JIT compiler simply compiles each portion of code as it is called (just-in time). When code has been compiled once, the resultant native executable is stored until the application exists, so that it does not need to be recompiled the next time that portion of code is run.
3. Language Interoperability: The use of IL not only enables platform independence; it also facilitates language interoperability. You can compile to IL from one language, and this compiled code should then be interoperable with code that has been compiled to IL from another language.
What are the important features of the IL?
1. Object orientation and use of interfaces
2. Strong distinction between value and reference types
3. Strong data typing
4. Error handling through the use of exceptions
5. Use of attributes.
What is MSIL, and why should my developers need an appreciation of it at all?Microsoft Intermeidate lanaguage. which is the out put for all the .net supported languages after comiplation will produce. Appreciation for cross language support.
What is Common Language Specification (CLS)?
The CLS works with the CTS to ensure language interoperability. The CLS is a set of minimum standards that all compilers targeting .NET must support.
.NET Data Types
Different Data Types are as follows:
1. Types
a. Value Type
1. Built in Value Types
2. Enumerations
3. User-defined Value Types
b. Reference Type
1. Interface Types
2. Pointer Types
3. Self-describing Types
· Self-describing Types
· Class Types
i. Delegates
ii. Boxed Value Types
iii. User-defined Reference Types
· Arrays
Type - Base class that represents any type
Value Type - Base class that represents any value type
Reference Types - Any data types that are accessed through a reference and stored on the heap
Built-in Value Types - Includes most standard primitive types, which represent number, Boolean values, or characters
Enumerations - Sets of enumerated values
User-defined Value Types - Types that have been defined in source code and are stored as value types. In C#, this means any struct
Interface Types - Interfaces
Pointer Types - Pointers
Self-describing Types - Data Types that provide information about themselves for the benefit if the garbage collector.
Arrays - Any type that contain an array of objects
Class Types - Types that are self-describing but are not arrays
Delegates - Types that are designed to hold references to methods
User-defined Reference Types - Types that have been defined in source code and are sorted as reference types. In C# terms, this means any class.
Boxed Value Types - A value type that is temporarily wrapped in a reference so that it can be stored on the heap.
Distinct Value and Reference Types?
As with any programming language, IL provides a number of predefined primitive data types. One characteristic of IL, is that it makes a strong distinction between value and reference types.
1. Values Types: are those for which a variable directly stores data
2. Reference Types: are those for which variable simply stores the address at which the corresponding data can be found.
What is the difference between "Value Types" and "Reference Types"?
Many programming languages provide built-in data types such as integers and floating-point numbers. These are copied when they are passed in to arguments i.e. they are passed "By Value". In .NET terms, these are called Value Types".
The RunTime supports two kinds of Value Types:
1. Built-in value types: The .NET Framework defines built-in value types such as System.Int32 and System.Boolean which correspond and are identical to primitive data types used in programming languages.
2. User-defined value types: The language you are using will provide functionality to define your own Value Types. These user defined Types derive from System.ValueType. If you want to define a Type representing a value that is a complex number (two floating-point numbers), you might choose to define it as a value type. Why? Because you can pass the Value Type efficiently "By Value". If the Type you are defining could be more efficiently passed "By Reference", you should define it as a class instead. Variables of Reference Types are referred to as objects. These store references to the actual data.
The following are the Reference Types:
· class
· interface
· delegate
This following are the "built-in" Reference Types:
· object
· string
How do you convert a value type to a reference type?
Use Boxing.
What happens in memory when you Box and Unbox a value-type?
Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.
What is Boxing?
Encapsulating a copy of a value type in an object.
Where are the instances of reference types and the value types stored?
Instances of reference types are always stored in an area of memory known as the managed heap.
Value types are normally stored on the stack (although if value types are declared as fields within reference types they will be stored inline on the heap).
Strong Data Typing
One very important aspect of IL is that it is based on exceptionally strong data typing. That means all variables are clearly marked as being of a particular specific data type.
What is the importance of strong data typing for language interoperability?
If a class is to derive from or contains instances of other classes, it needs to know about all the data types used by other classes. This is why strong data typing is so important.
How are the data type problems solved in .NET?
The data type problem is solved in .NET through the use of the Common Type System (CTS). The CTS defines the predefined data types that are available in IL, so that all languages that target the .NET Framework will produce compiled code that is ultimately based on these types.
What is the difference between “Value Types” and “Reference Types”?
Many programming languages provide built-in data types such as integers and floating-point numbers. These are copied when they are passed in to arguments i.e. they are passed "By Value". In .NET terms, these are called Value Types".
The RunTime supports two kinds of Value Types:
1. Built-in value types
The .NET Framework defines built-in value types such as System.Int32 and System.Boolean which correspond and are identical to primitive data types used in programming languages.
2. User-defined value types
The language you are using will provide functionality to define your own Value Types. These user defined Types derive from System.ValueType. If you want to define a Type representing a value that is a complex number (two floating-point numbers), you might choose to define it as a value type. Why? Because you can pass the Value Type efficiently "By Value". If the Type you are defining could be more efficiently passed "By Reference", you should define it as a class instead. Variables of Reference Types are referred to as objects. These store references to the actual data.
The following are the Reference Types:
· class
· interface
· delegate
This following are the "built-in" Reference Types:
· object
· string
How to convert a string numeric value of an Enum to an enumerated object?
You can use the Parse method of the Enum object.
For Example, say this is the enum defined:enum Colors {Red=1, Green=2, Blue=4}
string mystring="Red";
Colors myEnum=(Colors)Enum.Parse(typeof(Colors),mystring);
Console.WriteLine("My Color is : {0}", myEnum.ToString());
How do I have an object notify me of any changes in real time?
Events provide a generally useful way for objects to signal state changes that may be useful to clients of that object. In order to support this, you need to create an event of type EventHandler with the name
The event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:
A class that holds the event data.
This class must derive from the base class EventArgs.
A delegate that points to a method that provides the response to the event.
Example:public delegate void EventHandler(Object sender, EventArgs e);public event EventHandler DataChangedEventHandler;
Does anyone have an example of how to create an ArrayList of objects?
It's like adding any other item to an ArrayList, and then retrieving that. For example, if you wanted to add a Hashtable to an ArrayList, then you would do this: // An array list. ArrayList arrayList = new ArrayList();
// Add hashtables.
for (int index = 0; index < 10; index++)
{
// Add a hashtable.
arrayList.Add(new Hashtable());
}
How do I get type information on an object?
You can get type information using reflection-
Reflection is the process by which a program can read its own metadata. A program is said to reflect on itself, extracting metadata from its assembly and using that metadata either to inform the user or to modify its own behavior.
All .NET assemblies contain type information which describes the structure of every internal and external type. Many methods in the .NET base class libraries require you to pass in type information for a given item. When you need to obtain type information for a given method invocation, you have numerous approaches.
First, all types inherit the public System.Object.GetType() method: // obtain type information from a variable.MyType c = new MyType();Type t = c.GetType();GetTypeInfo(t);
Or simply use: // obtain type information via typeof.GetTypeInfo(typeof(MyType));
0
Reflections
Reflection is the feature in .NET, which allows to get some information about object in runtime. That information contains data of the class. Also it can get the names of the methods that are inside the class and constructors of that object.
To write a C#.NET program which uses the reflection, the program should use the namespace System.Reflection.
· To get the object type or the class name of our object, the typeof operator can be used.
· GetType() method can be used for retrieving the type information of a class or to get the data about objects
In addition to reading the types defined within a given assembly, you can also generate (emit) your own assemblies and types using the services of System.Reflection.Emit or System.CodeDom.
What is Reflection?
A compiler for the common language runtime (CLR) will generate metadata during compilation and store the metadata (in a binary format) directly into assemblies and modules to avoid irregularities.
Reflection is the ability to read metadata at runtime. Reflection is a collection of classes, which allow you to query assembly (classes/objects) metadata at runtime (ability to read metadata at runtime). Using reflection you can also create new types and their instances at runtime and invoke methods on these new type instances.
There are other uses for reflection. Compilers for languages such as JScript use reflection to construct symbol tables.
Using reflection, it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. Reflection also allows us to create new types at runtime.
Reflection generally begins with a call to a method present on every object in the .NET framework: GetType. The GetType method is a member of the System.Object class, and the method returns an instance of System.Type. System.Type is the primary gateway to metadata. System.Type is actually derived from another important class for reflection: the MemeberInfo class from the System.Reflection namespace. MemberInfo is a base class for many other classes who describe the properties and methods of an object, including FieldInfo, MethodInfo, ConstructorInfo, ParameterInfo, and EventInfo among others. As you might suspect from their names, you can use these classes to inspect different aspects of an object at runtime.
When reflection is useful in any application?
Reflection package is used in an application of you want to know the methods, variables, used in the class.
What is reflection in Microsoft.NET Context?
The REFLECTION is used to read the metadata information like (type, reference and methods). Which is derived from system.assembly.reflection class object.
The simple meaning is to read assembly information by using this system.assembly.reflection class.
How do you retrieve attributes on classes and methods defined within an assembly?
Using Reflections.
What is the tool that uses reflection to inspect assemblies?
Reflector tool uses reflection to inspect assemblies. All the classes derive from System.Attribute namespace.
What is Reflection in .NET? Namespace? How will you load an assembly which is not referenced by current assembly? All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries.Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).
Reflection
Assemblies store metadata, including details of all the types and members of these types that are defined in the assembly. This technique is known as reflection.
Custom Attributes
A custom Attribute is simply a special class that must comply with these two specification:
· A custom attribute must derive from System.Attribute
· The Constructors for an attribute may only contain types that can be resolved at compile time – such as strings and integers.
The invented Attributes are:
· TestCaseAttribute à Links the code used to test a class to the class itself
· BugFixAttribute à Records who altered what and when within the source code
· DatabaseTableAttribute and DataBaseColumn Attribute à shows how to produce database schemas from .NET classes
What are the steps to create a custom attribute?
· Create a class derived from System.Attribute
· Create the constructor(s) and public properties as required
· Attribute the class to define where it is valid to use your custom attribute.
Explain the TestCaseAttribute?
When unit-testing s/w it is common to define a set of test classes that exercise your classes to ensure that they perform as expected. This is especially true in regressing testing, where you want to ensure that by fixing a bug or adding extra functionality, you have not broken something else.
Note: When working with the regulated customers (under strict controls from govt agencies), it is necessary to provide the cross-references between code and tests. The TestCaseAttribute presented here can help to trace between a class and its test class.
All you need to do here is create a class derived from System.Attribute:
Public class TestCaseAttribute: Attribute
{
}
Explain the BugFixAttribute?
The BugFix attribute constructor takes a bug number and a comment string and is marked with AllowMultiple=true to indicate that it can be used as follows:
[BugFix(“101”,”Created some methods”)]
public class MyBuggyCode
{
}
Explain the DatabaseTableAttribute?
The attribute consists of a constructor that accepts the name of the Table as a string and is marked with the Inherited=false and AllowMultiple=false modifiers. Within the attribute class, you store the name of the table as a field rather than a property.
Explain the DatabaseColumnAttribute?
This attribute is designed to be placed on public properties of the DataRow class and is used to define the name of the column that the property will link to, together with such things as whether the column can contain the null value.
Built-In Attributes
.NET Framework includes a number of attributes such as:
· DebuggableAttribute
· AssemblyTitleAttribute
· System.Diagnostics.ConditionalAttribute
· System.ObsoleteAttribute
· System.SerializableAttribute
· System.Reflection.AssemblyDelaySignAttribute
Explain the System.Diagnostics.ConditionalAttribute?
It permits sections of code to be included or excluded based on the definition of a symbol at compilation time. This attribute is contained within the System.Diagnostics namespace, which includes classes for debug, trace output, event logging, performance counters, and process information.
Notice that the defaults for a Debug build are to check both the DEBUG and TRACE options.
Note: the Conditional attribute can be used only on methods that return void – otherwise removing the call world mean that no value was returned; however, you can attribute a method that has out or ref parameters – the variables will retain their original value.
Explain the System.ObsoleteAttribute?
The Obsolete attribute can be used to mark a class, method, or any other entry in an assembly as being no longer used.
This attribute would be useful for ex, when publishing a library of classes. The Obsolete attribute provides a useful way to hint that a particular feature of your classes should no longer be used.
To do this all you should do is add the Obsolete attribute as shown here:
[Obsolete (“newname instead.”)]
public void oldname()
{
}
When you compile for debug or release, you will receive a warning from the C# compiler that you are using an obsolete method as follows:
Obsolete.cs(20, 1): warning CS0618: ‘Developer.oldname()’ is obsolete: ‘newname instead’.
Eventually, if you want to entirely drop support for oldname() method, so you need to add an extra parameter to the Obsolete attribute as follows:
[Obsolete (“you must newname instead.”, true)]
public void oldname()
{
}
When user attempts to compile this method, the compiler will generate an error and halt the compilation with the following message:
Obsolete.cs(20, 1): error CS0619: ‘Developer.oldname()’ is obsolete: ‘you must newname instead’.
What is Serialization?
Serialization is the name for storing and retrieving an object, with in a disk file, memory, or anywhere else you can think of. When serialized, all instance data is persisted to the storage medium, and when deserialized, the object is reconstructed and is indistinguished from its original instance.
What is Deserialization?
The data is read from the storage medium, and this data is assigned to instance variables of the class.
You can mark the NonSerializable attribute to mark data that does not need to be serialized, such as data that can be recomputed or calculated when necessary
To do this all you should do is add the Serializable attribute as shown here:
[Serializable]
public class Person()
{
public Person()
{
}
public int Age;
[NonSerializable]
public int WeightInPounds;
}
Explain the System.SerializableAttribute?
The SerializableAttribute is used for storing and retrieving instance data. All you need to do is add the Serializable attribute to the class, and the .NET runtime will do the rest for you.
When the runtime receives a request to serialize an object, it checks if the object’s class implements the ISerializable interface, and if it does not then the runtime checks if the class is attributed with the Serializable attribute.
If the Serializable attribute is found on the class, the .NET uses reflection to get all instance data whether public, private, or protected and to store this as the representation of the object.
To do this all you should do is add the Serializable attribute as shown here:
[Serializable]
public class Person()
{
public Person()
{
}
public int Age;
public int WeightInPounds;
}
When do you use the Formatter Object?
To store an instance of the class, use a Formatter Object – which converts the data stored within your class into a stream of bytes. The system comes with two default formatters and these Formatters have their own namespaces as follows:
· BinaryFormatter à System.Runtime.Serialization.Formatters.Binary
· SoapFormatter à System.Runtime.Serialization.Formatters.Binary
Explain the System.Reflection.AssemblyDelaySignAttribute?
The .NET Framework also permits you to delay-sign an assembly, which means that you can register it in the GAC for testing without a private key.
One scenario in which you might use delayed signing is when developing commercial software. Each assembly that is developed in-house needs to be signed with your company’s private key before being shipped to your customers. So when you compile your assembly you reference the key file before you can register the assembly in the GAC.
AssemblyDelaySign attribute defines whether the assembly will be fully signed or delay signed
What is the AssemblyKeyFile?
The AssemblyKeyFile attribute defines the file where the key is to be found. This can be either the public key file or the file containing both the public and private keys.
Registering in the GAC:
Attempting to use the Gacutil tool to register a delay-signed assembly in the GAC will generate an error message similar to this:
Microsoft ® .NET Global Assembly Cache Utility. Version 2.0.50214.0
Copyright © Microsoft Corporation. All rights reserved.
Failure adding assembly to the cache: Strong name signature could not be verified. Was the assembly built delay-signed.
The assembly is only partially signed at the moment, and by default the GAC and VS.NET will only accept assemblies with a complete strong name. You can however, instruct the GAC to skip verification of the strong name on a delay signed assembly by using the sn utility.