Showing posts with label .NET Framework. Show all posts
Showing posts with label .NET Framework. Show all posts

Enumerate the Steps for creating a Shared Assembly

Step 1: Generate a Strong Name Key:

D:\Project\DLL\sn -k dll.snk

The above statement will write a Kay pair to dll.snk file

Step 2: Associate the Strong Name Key with source code

Step 2.1: Create a program to be used as DLL - First.cs

using System;
using System.Reflection;

[assembly:AssemblyKeyFile("dll.snk")]
public class Employee
{
public string Data()
{
return "Anuj Ranjan";
}
}

a) Save the file as First.cs in D:\Project\DLL\First.cs
b) Compile the program to create a DLL from the Command Prompt as given below:

D:\Project\DLL>csc /t:library First.cs

c) The above statement will create a DLL named First.dll, with the strong name key in it.

Step 2.2: Create another program to implement the DLL - Second.cs

using System;

public class Trial
{
public static void Main()
{
Employee e = new Employee();
Console.WriteLine(e.Data());
}
}

Save the file as Second.cs in D:\Project\Implement\Second.cs

Step 3: Install the DLL in GAC

D:\Project\DLL\GACUTIL -i First.dll

GACUTIL is a command which is used to install a strong named dll in the Global Assembly Cache.

Step 4: Add the reference of the DLL in the program

D:\Project\Implement\csc /r:d:\Project\DLL\First.dll Second.cs

Step 5: Execute the program

D:\Project\Implement\Second

How can you force Garbage Collection

The GC.Collect method of the garbage collection GC class can be used to force garbage collection. The GC.Collect method may be used if there is a significant reduction in the amount of memory being used at a defined point in an application's code.

The garbage collector suspends all threads that are currently in the process of execution, before it performs a collection. Frequent calls to GC.Collect method may create performance issues. In most cases the optimizing engine in the garbage collector (which determines the best time to run a garbage collection) is better at determining the best time to perform a collection. 

In general, calls to any of the collect methods should be avoided, and the garbage collector should be allowed to run independently.

Global Assembly Cache (GAC)

The Global Assembly Cache (GAC) is a machine-wide cache of code. It can be found on every computer where the CLR is installed. The GAC is a storehouse of public/shared assemblies and allows applications to share assemblies instead of having the assembly distributed with each application.

Assemblies must be strong named before being installed in the GAC. The GAC performs integrity checks on all files that make up the assembly (at the time of its installation) to ensure that the assembly has not been tampered with.

Note: Unless explicitly required, do not share an assembly. Keep assembly dependencies private, and locate assemblies in the application directory.

Mention the demerits of installation of an assembly in the GAC

The application can no longer be replicated or installed by using the xcopy command (used to copy the application directory), if one of the assemblies that make up an application is placed in the GAC. The assembly must be moved in the GAC as well.

Mention the benefits of installation of an assembly in the GAC
  • Shared Location – An assembly which has to be used by multiple applications should be placed in the GAC. Add a version policy statement to the Machine.config file which will redirect references to the assembly.
  • File Security – Since it is installed in the systemroot directory, the GAC GAC inherits the Access Control List (ACL). So, only Administrators should be allowed to delete files from the GAC.
  • Side-by-side versioning – The GAC can maintain multiple copies of assemblies with the same name but different version information.
  • Additional search location – Before using the codebase information in the configuration file, the CLR runtime checks the GAC for the requested assembly.

Mention the ways to deploy an assembly into the GAC
  • Use an installer designed to work with the GAC for installing assemblies.
  • Use Gacutil.exe (Global Assembly Cache tool (gacutil.exe) is a developer tool provided by the Windows Software Development Kit (SDK)) to deploy an assembly into the GAC.
    Gacutil.exe does not provide assembly reference counting and other features provided by the Windows Installer. So it should only be used in development environment.

Where is the GAC located?

.NET Framework 4 & above – The default location for GAC is %windir%\Microsoft.NET\assembly
Versions earlier to .NET Framework 4 – The default location for GAC is %windir%\assembly

Friend Assemblies

A friend assembly can access another assembly's Friend (Visual Basic) or internal (C#) types and members. If an assembly is identified as a friend assembly, the types and members no longer have to be marked as public in order to be accessed by other assemblies.

How can you identify friend assemblies for a given assembly?

The attribute InternalsVisibleToAttribute can be used to identify one or more friend assemblies for a given assembly. The InternalsVisibleToAttribute class specifies that types that are ordinarily visible only within the current assembly are visible to a specified assembly.

Note: When an assembly that will access internal types or internal members of another assembly is compiled, the name of the output file (.exe or .dll) must be explicitly specified by using the /out compiler option.
Explicit naming of output file is required because at the time of binding to external references, the compiler has not yet generated the name for the assembly it is building.

Example: The following example uses the InternalsVisibleToAttribute attribute in assembly A and specifies assembly AssemblyB as a friend assembly. This gives assembly AssemblyB access to all types and members in assembly A that are marked as Friend (Visual Basic) or internal (C#).

using System.Runtime.CompilerServices;
using System;

[assembly: InternalsVisibleTo("AssemblyB")]

// The class is internal by default.
class FriendClass
{
    public void Test()
    {
        Console.WriteLine("Sample Class");
    }
}

// Public class that has an internal method.
Public class ClassWithFriendMethod
{
    internal void Test()
    {
        Console.WriteLine("Sample Method");
    }
} 
Validation Rules for friend assembly name passed to the InternalsVisibleToAttribute attribute (If assembly A declares B as a friend assembly)
  • If assembly A is strong named, assembly B must also be strong named. The friend assembly name that is passed to the attribute must consist of the assembly name and the public key of the strong-name key that is used to sign assembly B (the assembly version, culture, architecture, or public key token should not be included).
  • If assembly A is not strong named, the friend assembly name should consist of only the assembly name.
  • If assembly B is strong named, you must specify the strong-name key for assembly B by using the project setting or the command-line /keyfile compiler option.

Hub-and-Spoke model & Satellite Assemblies

The .NET Framework uses a hub-and-spoke model to locate and retrieve localized resources, which requires that resources must be placed in specific locations so that they can be easily located and used.

If the resources are not compiled and named as expected, or not placed in correct locations, the CLR will not be able to locate them and will use the resources of the default culture instead.

The hub is the main assembly that contains the non-localizable executable code and the resources for a single culture, which is called the neutral or default culture. The default culture is the fallback culture for the application and is used when no localized resources are available. You use the NeutralResourcesLanguageAttribute attribute to designate the culture of the application's default culture.

Each spoke connects to a satellite assembly that contains the resources for a single localized culture but does not contain any code. Satellite assemblies are not part of the main assembly. The resources of satellite assemblies that correspond to a specific culture can easily be updated or replaced without replacing the main assembly for the application.

The .NET Framework Resource Manager, represented by a ResourceManager object, is used to automatically access localized resources and has the following requirements:
  • A single satellite assembly must include all the resources for a particular culture.
  • There must be a separate subdirectory in the application directory for each localized culture that stores that culture's resources. The subdirectory name must be the same as the culture name.
    Alternately, you can store your satellite assemblies in the GAC. In this case, the culture information component of the assembly's strong name must indicate its culture.
    If your application includes resources for subcultures, place each subculture in a separate subdirectory under the application directory.
  • The satellite assembly must have the same name as the application, and must use the file name extension ".resources.dll". Ex: If an application is named Example.exe, the name of each satellite assembly should be Example.resources.dll.
  • Information about the culture of the satellite assembly must be included in the assembly's metadata. To store the culture name in the satellite assembly's metadata, you specify the /culture option when you use Assembly Linker to embed resources in the satellite assembly.

What are the different types of assemblies in .NET

There are three different types of assemblies in .NET:

Private Assemblies – Private Assemblies are normally used by a single application and is stored in the application's directory (the folder containing the application's executable file). Private Assemblies are deployed with the application and is available for the exclusive use of that application (they are not shared by other assemblies). Private assemblies must be designed to work side-by-side with other versions of the assembly on the system.

Private assemblies can be installed by any installation method that can copy the assembly's file into this folder, such as the xcopy command.

Note that the steps for creating a private assembly are identical to those for creating a shared assembly with two exceptions:
  • A private assembly is not required to be signed, and publickeyToken is not required in the assemblyIdentity element of the assembly manifest.
  • Private assemblies can be installed into the application's folder using any installation technology. Private assemblies are not required to be installed using the Windows Installer.
Public / Shared AssembliesShared Assemblies are available for use by multiple applications on the computer. They have version constraint and are stored in the Global Assembly Cache (GAC). GAC is the storehouse of public/shared assemblies and is maintained by the .NET runtime. A shared assembly must be strongly named.

Satellite Assemblies An assembly with culture information is automatically assumed to be a satellite assembly. These assemblies contain resource files pertaining to a locale (Culture+Language). These assemblies are used in deploying Global application for different languages.

Satellite assemblies are used to build multi-linguistic applications. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language.


Satellite assemblies are not part of the main assembly. The resources of satellite assemblies that correspond to a specific culture can easily be updated or replaced without replacing the main assembly for the application.

What is an Assembly Manifest

An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with MSIL code or in a standalone PE file that contains only assembly manifest information.

Functions of the Assembly Manifest
  • The manifest lists the files that make up the assembly.
  • It governs how references to the assembly's types and resources map to the files that contain their declarations and implementations.
  • It lists other assemblies on which the assembly depends.
  • It provides a level of indirection between consumers of the assembly and the assembly's implementation details.
  • It makes the assembly self-describing.

Contents of the Assembly Manifest

Given below are the details of the information contained in as Assembly Manifest:
  • Assembly Name – Name of the assembly.
  • Version numberA major and minor version number, and a revision and build number. The CLR uses these numbers to enforce version policy.
  • Culture – Information on the culture or language the assembly supports.
  • Strong name information – The public key from the publisher if the assembly has been given a strong name.
  • List of all files in the assembly - A hash of each file contained in the assembly and a file name.
  • Type reference information – Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.
  • Information on referenced assemblies – A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly's name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named.

Differentiate between Single-file assembly and Multifile assembly

When the components of an assembly is grouped in a single physical file, it is known as Single-file assembly.

When the components of an assembly is contained in several files, it is known as Multifile assembly. These files can be modules of compiled code (.netmodule), resources (such as .bmp or .jpg files), or other files required by the application. The files that make up a multifile assembly are not physically linked by the file system. Rather, they are linked through the assembly manifest and the CLR manages them as a unit.

Multifile assembly is usually created when there is a requirement to combine modules written in different languages and to optimize downloading an application by putting seldom used types in a module that is downloaded only when needed.

Components of an Assembly

There are four components of an assembly:
  • Assembly Manifest
  • Type Metadata
  • MSIL code
  • Resources
Out of the above four components, only assembly manifest is required. However, rest of the types or resources are needed to give the assembly any meaningful functionality.

Differentiate between Static and Dynamic Assemblies

Static Assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files.

Dynamic Assemblies are run directly from memory and are not saved to disk before execution. However, dynamic assemblies can be saved to disk later, after they have executed. These binaries are created on the fly in the memory using SYSTEM.REFLECTION.EMIT namespace.

Assembly

An assembly as a collection of types and resources that form a logical unit of functionality. It is a fundamental unit deployment, version control, reuse, activation scoping, and security permissions for a .NET application. Assemblies are the building blocks of the .NET Framework and can take the form of an executable (.exe, also known as process assembly) file or dynamic link library (.dll, also known as library assembly) file. Assemblies are the smallest versionable unit in the CLR.

An assembly can contain one or more modules. Assemblies provide the CLR with the information it needs to be aware of type implementations.

Properties of an Assembly
  • An assembly is implemented as .exe or .dll file.
  • An assembly can be shared between applications by putting it in the Global Assembly Cache (GAC). Assemblies must be strong-named before they can be included in the Global Assembly Cache.
  • Information about an assembly can be obtained programmatically by using Reflection.
  • Assembly contains code that the CLR executes.
  • MSIL code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest.
  • Each assembly can have only one entry point (DllMain, WinMain, or Main).
  • An assembly is the unit at which permissions are requested and granted. Thus, it forms a Security Boundary.
  • It forms a Type Boundary. Every type's identity includes the name of the assembly in which it resides.
  • An assembly forms a Reference Scope Boundary. The assembly's manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends.
  • It forms a Version Boundary. The assembly is the smallest versionable unit in the CLR; all types and resources in the same assembly are versioned as a unit.
  • It forms a Deployment Unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes, can be retrieved on demand.
  • It is the unit at which side-by-side execution is supported.

Explain the services provided by the .Net Framework

The .NET Framework is a managed execution environment that provides a variety of services to its running applications. It consists of two major components: the Common Language Runtime (CLR), which is the execution engine that handles running applications; and the .NET Framework Class Library, which provides a library of tested, reusable code that developers can call from their own applications.
The services that the .NET Framework provides to running applications include the following:


  • Memory Management - In .NET Framework applications, the CLR is responsible for allocating and releasing memory and for handling object lifetimes on behalf of the application.
  • Common Type System - In the .NET Framework, basic types are defined by the .NET Framework type system and are common to all languages that target the .NET Framework. This fecilitates cross-language interoperability.
  • Extensive Class Library - Programmers can use a readily accessible library of types and their members from the .NET Framework Class Library, instead of writing vast amounts of code to handle common low-level programming operations.
  • Development Frameworks and Technologies - The .NET Framework includes libraries for specific areas of application development, such as ASP.NET for web applications, ADO.NET for data access, and Windows Communication Foundation for service-oriented applications.
  • Language Interoperability - Language compilers that target the .NET Framework emit an intermediate code named Common Intermediate Language (CIL), which, in turn, is compiled at run time by the Common Language Runtime. With this feature, routines written in one language are accessible to other languages, and programmers can focus on creating applications in their preferred language or languages.
  • Version Compatibility - With rare exceptions, applications that are developed by using a particular version of the .NET Framework can run without modification on a later version.
  • Side-by-Side Execution - The .NET Framework helps resolve version conflicts by allowing multiple versions of the common language runtime to exist on the same computer. This means that multiple versions of applications can also coexist, and that an application can run on the version of the .NET Framework with which it was built.
  • Multitargeting - By targeting the .NET Framework Portable Class Library, developers can create assemblies that work on multiple .NET Framework platforms, such as Windows 7, Windows 8, Windows Phone, and Xbox 360.

Glossary


Term
Definition
.NET Framework
The .NET Framework is a component of the Windows operating system that provides the programming model for building, deploying and running Web-based applications, smart client applications and Web services. The .NET Framework consists of the common language runtime (CLR) and a unified class library.
Active Directory
The Windows directory service that provides a unified, hierarchical view of complex networks.
ADO.NET
The suite of data access technologies included in the .NET Framework class libraries
ASP.NET
The development component for building server-based Web applications. An evolution of ASP into the .NET Framework.
Assembly
The primary building block—also the unit of deployment and versioning—of a .NET Framework application. An assembly includes an assembly manifest, which describes the contents of the assembly
C#
A new ECMA-approved programming language designed for the .NET Framework. C#, which is an evolution of C and C++, is type safe and object oriented. Because it is compiled as managed code, it benefits from the services of the common language runtime, such as language interoperability, enhanced security, and garbage collection.
Class Library, .NET Framework
A library of classes, interfaces, and value types that are included in the Microsoft .NET Framework and can be used from any CLS-compliant language. The .NET Framework class library provides access to system functionality and is designed to be the foundation on which .NET Framework applications, components, and controls are built.
Common Language Runtime (CLR)
The engine at the core of .NET Framework-managed code execution. The runtime supplies managed code with services such as cross-language integration, code access security, object lifetime management, and debugging and profiling support.
Common Language Specification (CLS)
A subset of .NET Framework features that are supported by a broad set of compliant languages and tools. CLS-compliant languages and tools are guaranteed to interoperate with other CLS-compliant languages and tools.
ECMA
A European standards body created in 1961. Internationally accredited ECMA has fast-track approval for ISO and is the forum for successful standards such as ECMAScript.
Evidence-Based Security
The .NET Framework introduces the concept of evidence-based security, referring to inputs to the security policy about code—such as from what site, security zone, or URL was an assembly obtained, what is its strong name, and whether it has a digital signature and from whom. Based on these and other answers—which can come from multiple sources depending on where the code is run—the appropriate security policy can be applied, and the appropriate permissions may be granted to the assembly..
Extensible Markup Language (XML)
A subset of Standard Generalized Markup Language (SGML) that is optimized for delivery over the Web. XML provides a uniform method for describing and exchanging structured data that is independent of applications or vendors.
Garbage Collection (GC)
The process of transitively tracing through all pointers to actively used objects to locate all objects that can be referenced and then arranging to reuse any heap memory that was not found during this trace. The CLR garbage collector also compacts the memory that is in use to reduce the working space needed for the heap.
HTTP
Hyper Text Transfer Protocol is a standard Internet protocol for transfer of information between servers and between clients and servers.
IDL
Interface Definition Language. A language used by applications to specify the various interfaces they intend to offer to other applications.
Microsoft intermediate language (MSIL)
A language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler, which produces native code. MSL defines an abstract, stack-based execution model.
JIT
An acronym for "just-in-time", a phrase that describes an action that is taken only when it becomes necessary, such as just-in-time compilation or just-in-time object activation.
Loosely Coupled Architecture
A distributed application in which you can change the implementation of one tier without affecting any of the other tiers. Contrast tightly coupled architecture.
Managed Code
Managed code supplies the metadata necessary for the CLR to provide services, such as memory management, cross-language integration, code access security, and automatic lifetime control of objects. All code based on MSIL executes as managed code.
Manifest
An integral part of every assembly that renders the assembly self-describing via metadata. The metadata describes which modules and resource files are part of a particular assembly, which types are exported, and which other assemblies are referenced. It also specifies which security permissions are required to run, what additional permissions are optionally requested, and what permissions the assembly refuses.
Metadata
Data (or information) about data. Many different systems use metadata—for example, type libraries in COM provide metadata and databases have schemas. In the CLR, metadata is used to describe assemblies and types. It is stored with them in the executable files, and is used by compilers, tools, and the runtime to provide a wide range of services. Metadata is essential for runtime type information and dynamic method invocation.
Native Code
Code that has been compiled to processor-specific machine code.
n-tier
System architecture that separates presentation, business logic, data access, and database (or other persistence mechanism) tiers.
Reflection
.NET Framework technology that allows you to examine metadata that describes types and their members. Reflection can be used to create, invoke, and access type instances at run time.
Serviced Component
The mechanism that enables COM+ services to be available to .NET Framework classes.
Side-by-Side Execution
The ability to run multiple versions of the same assembly simultaneously. This can be on the same computer or in the same process or application domain. Allowing assemblies to run side-by-side is essential to support robust versioning in the common language runtime. Side-by-side is also used to describe to describe two versions of the .NET Framework running simultaneously on the same computer.
SOAP
Simple Object Access Protocol, a W3C standard. A lightweight protocol for exchange of information in a decentralized, distributed environment. It is an XML-based protocol for exchanging structured and type information on the Web. The SOAP protocol contains no application or transport semantics, which makes it highly modular and extensible.
Tightly Coupled Architecture
A distributed application where a change to any tier affects some or all the other remaining tiers. Contrast loosely coupled architecture.
UDDI
Universal Description, Discovery, and Integration (UDDI) specification. An initiative that creates a global, platform-independent, open framework to enable Web service providers to advertise the existence of their Web services and for Web service consumers to locate Web services of interest.
Unmanaged Code
Code that was created without knowledge for the conventions and requirements of the .NET Framework. Unmanaged code executes in the .NET Framework environment with minimal services (for example, no garbage collection, limited debugging, and no declarative security).
Web forms
The ASP.NET page framework, which supports server-side controls that render HTML user interface on Web browsers.
Web services
A programming model that provides the ability to exchange messages in a scalable, loosely coupled, and platform-neutral environment using standard protocols such as HTTP, XML, XSD, SOAP, and WSDL. The SOAP-based XML messages exchanged between a Web service and its clients can be structured and typed, or loosely defined. The flexibility of using a text format such as XML enables the message exchange to evolve over time in a loosely coupled way. Because they are based on standard protocols and are platform neutral, Web services enable communication with a broad variety of implementations, platforms, and devices.
Web Services Description Language (WSDL)
An XML-based contract language for describing network services offered by a server.
Windows Forms
A rich Windows client library that encapsulates native Win32 APIs and exposes secure, managed classes for creating smart Windows client applications. The Windows Forms class library provides many controls, such as buttons, check boxes, drop-down lists, combo boxes, data grid, and others, that encapsulate user-interface and other client-side functionality.
Windows Management Instrumentation (WMI)
A component of the Windows operating system that provides management information and control in an enterprise environment using industry-wide standards.
WSDL
(see Web Services Description Language)
XML
(see Extensible Markup Language).
XML Schema Definition (XSD)
A W3C Recommendation that specifies how to formally describe the elements of an XML document. The schema can be used to verify the conformance of elements in an XML document.

What are the different types of literals in C#?

  • Boolean literals: True and False are literals of the Boolean type that map to the true and false state, respectively.
  • Integer literals: Used to write values of types int, uint, long, and ulong.
  • Real literals: Used to write values of types float, double, and decimal.
  • Character literals: Represents a single character and usually consists of a character in quotes, such as 'z'.
  • String literals: C# supports two types of string literals, regular string literal and verbatim string literals. A regular string literal consists of zero or more characters enclosed in double quotes, such as "224568". A verbatim string literal consists of an @ character followed by a double–quote character, such as ©"hello".
  • Null literal: Represents the null–type.

Dynamic Language Runtime

The DLR (Dynamic Language Runtime) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages (such as C# and Visual Basic).
The CLR always had dynamic capabilities. You could always use reflection, but its main goal was never to be a dynamic programming environment and there were some features missing. The DLR is built on top of the CLR and adds those missing features to the .NET platform.

Advantages of DLR:

  • Simplifies Porting Dynamic Languages to the .NET Framework
  • Enables Dynamic Features in Statically Typed Languages - Existing .NET Framework languages such as C# and Visual Basic can create dynamic objects and use them together with statically typed objects.
  • Provides Future Benefits of the DLR and .NET Framework
  • Enables Sharing of Libraries and Objects
  • Provides Fast Dynamic Dispatch and Invocation
Examples of dynamic languages are Lisp, Smalltalk, JavaScript, PHP, Ruby, Python, ColdFusion, Lua, Cobra, and Groovy.

Common Language Runtime

The CLR (Common Language Runtime) or the .NET runtime is the runtime execution environment of .NET Framework. Code running under the control of the CLR is often termed managed code and 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. 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.

Runtime can be understood as a collection of external services that are required to execute a given compiled unit of code.

CLR (Common Language Runtime)



CLR Features in .Net 4.0