Professional Documents
Culture Documents
as double) as Double
FnAdd = dblA + dblB
End Function
End Class
Now, lets make use of the method FnAdd defined in the class
above. To use it, first create an object of this class, say
objX. Using this object, we can invoke the methods of this
class. See code below...
Property - A property is a thing that describes the features of an object. A property is a piece of
data contained within a class that has an exposed interface for reading/writing. Looking at that
definition, you might think you could declare a public variable in a class and call it a property.
While this assumption is somewhat valid, the true technical term for a public variable in a class
is a field. The key difference between a field and a property is in the inclusion of an interface.
Event - An action that an object does. When something happens, we say an event has happened.
For example, when a button is clicked, we say it is the click( ) event. When a mouse hovers on an
image, we say the mouseover( ) event has taken place.
Access Modifiers - Keywords used to vary the way members of a class are used. Following are
different types...
4) Friend - Friend access means that elements are accessible only within the program. Friend is
the default access modifer for any class that does not have a modifier.
Available only to code within our project/component
5) Protected Friend - Available only to classes that inherit from our class (in any project) or to
code within our project/component. This is a combination of Protected and Friend.
Default - A Default property is a single property of a class that can be set as the default. This
allows developers that use your class to work more easily with your default property because
they do not need to make a direct reference to the property. Default properties cannot be
initialized as Shared or Private and all must be accepted at least on argument or parameter.
Default properties do not promote good code readability, so use this option sparingly.
Shared -The Shared keyword is used in an inherited or base class to define a property or method
as being shared among all instances of a given class. If multiple instances of a class with shared
properties or methods are loaded, the shared properties or methods will provide the same data
across each instance of the class. When one class alters the value for a shared property, all
instances of that class will reflect the change. Shared properties of all instances of the class
point to the same memory location.
Overides - The Overides keyword allows the inheriting class to disregard the property or method
of the inherited class and implements ts own code.
MustOverride - The MustOverride keyword forces the inheriting class to implement its own
code for the property or method.
Shadows - The Shadows keyword will effectively hide all of the other methods in the baseclass.
It is like forcefully getting rid of the overloading that has been done on the methods of the base
class.
The Shadows keyword works like the Overloads keyword except that with shadows we do not
have to follow rules such as implementing the same signature. The Shadows keyword does not
require the consent (override ability) of the inherited class to replace the property or method's
implementation code. A method does not have to be defined as overridable for the Shadows
keyword to work. Read the example...
'This is the Base Class
Public Class Parent
Public Sub MyProc(ByVal num As Integer)
MsgBox("Number in Parent is " & num)
End Sub
We can add parameters to the constructors. This was'nt allowed in VB6. We can overload the
constructors, change the order of parameters, datatypes of parameters which ultimately change
the way the constructor works whenever an instance of that class is invoked.
However, when the constructor is added with parameters, the following code is generated...
Book's constructor.
Author's constructor.
If the base class does'nt have a no-argument constructor, then it would result in a compiler error.
Hence, we need to use the MyBase keyword with the constructor. Our child class will look like
this...
An abstract class may contain abstract methods & non-abstract methods. When a class is derived
from an abstract class, the derived class must implement all the abstract methods declared in the
base class. We may use accessibility modifiers in an abstract class (unlike in Interfaces).
An abstract class can inherit from a non-abstract class. In C++, this concept is known as pure
virtual method.
Interface - its a kind of class, that has only methods, do not have code, just the definition of the
methods. Also, the interface can't be instantiated. Its an abstract class with public abstract
methods, all of which must be implemented in the inherited classes. All methods in an interface
are public, no other access modifier is used. It is public by default.
Classes can contain code, but interface dont. However, classes that implement an interface do
contain code. Keep in mind that there are no instances of interfaces in VB .NET. Every instance
is a type that implements an interface, but is itself not an instance of the interface. Also note, in
an interface, all methods must be abstract (which is not necessary in an abstract class).
Serializable - This is a class attribute. When we use this attribute with a class, an instance of this
class can be taken in whatever state it is, and write it to a disk. The class can then be deserialized,
and the class will act as if it is simply stored in the memory.
Boxing & Unboxing - Value Types are stored on the stack and Reference types are stored on the
heap. The conversion of value type to reference type is known as Boxing. Converting reference
type back to value type
is known as Unboxing.
Value Types - Value types are primitive types that are mapped directly to the FCL. Like Int32
maps to System.Int32, double maps to System.double.
All value types are stored on stack and all the value types are derived from System.ValueType.
All structures and enumerated types that are derived from System.ValueType are created on
stack, hence known as ValueType.
Reference Types - Reference Types are different from value types in such a way that memory is
allocated to them from the heap. All the classes are of reference type. C# new operator returns
the memory address of the
object.
Partial Class - This concept has been introduced in .NET framework 2.0. They give you the
ability to split a single class into more than one source code (.cs or .vb) file. Here's what a partial
class looks like when it's split over two files...
When you build the application, Visual Studio .NET tracks down each piece of MyClass and
assembles it into a complete, compiled class with two methods, MethodA() and MethodB().
Partial classes don't offer much in the way of solving programming problems, but they can be
useful if you have extremely large, unwieldy classes. (Of course, this might be a sign that you
haven't properly factored your problem, in which case you should really break your class down
into separate classes.) The real purpose of partial classes in .NET is to hide automatically
generated designer code.
XML Documentation Questions
1.Is XML case-sensitive?
Ans. Yes.
Assembly Questions
1.How is the DLL Hell problem solved in .NET?
Ans. Assembly versioning allows the application to specify
not only the library it needs to run (which was available
under Win32), but also the version of the assembly.
2.What are the ways to deploy an assembly?
Ans. An MSI installer, a CAB archive, and XCOPY command.
Questions...
struct AStruct
{
int aField;
}
class AClass
{
int aField;
}
class MainClass
{
public static void Main()
{
AClass b = null; // No error.
AStruct s = null; // Error
/* [ Cannot convert null to 'AStruct' because it is
a value type ].*/
}
}
When you instantiate a class, it will be allocated on the heap.When you instantiate a struct, it
gets created on the stack. You will always be dealing with reference to an
object ( instance ) of a class. But you will not be dealing
with references to an instance of a struct ( but dealing directly with them ).
class MyClass
{
int myVar =10; // no syntax error.
public void MyFun( )
{
// statements
}
}
struct MyStruct
{
int myVar = 10; //syntax error
public void MyFun( )
{
// statements
}
}
class MyClass
{
int myVar = 10;
public MyClass( ) // no syntax error.
{
// statements
}
}
struct MyStruct
{
int myVar;
public MyStruct( ) // syntax error.
{
// statements
}
}
Classes must be instantiated using the new operator. But structs can be instantiated without using
the new operator.
MyClass aClassObj;
/* MyClass aClassObj=new MyClass(); is the correct
format.aClassObj.myVar=100;//NullReferenceException
(because aClassObj does not contain a reference to an object
of type myClass). */
Classes support inheritance.But there is no inheritance for structs. ( structs don't support
inheritance polymorphism )
(1)
struct MyStruct
{
int aStructVar;
internal void aStructMethod()
{
// statements
}
}
(2)
class MyClass
{
int aClassVar;
int aClassMethod()
{
// statements
}
}
struct MyStruct
{
int myInt;
public MyStruct( )
{ } ~MyStruct( ) //Error.
{
Console.WriteLine("Destructor of MyStruct object");
}
}
class MyClass
{
int myInt;
public MyClass( ) { } ~MyClass( ) // No Error.
{
Console.WriteLine("Destructor of MyClass object"); }
}
Classes are used for complex and large set data. structs are
simple to use. structs are useful whenever you need a type that will be used often and is mostly
just a piece of data.
An example below...
// .NET Singleton
sealed class Singleton
{
private Singleton() {}
public static readonly Singleton Instance = new Singleton();
}
Obviously you'd need to add some properties and methods to get something useful, but you get
the idea. Watch out for
thread safety issues.
This link may give more insight: ttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpatterns/html/ImpSingletonInCsharp.asp
If you want to pass state from the source page to the new
page, you have to pass it either on the URL (such as a database key, or message string), or you can store it in the
Session
object (caveat: there may be more than one browser window, and they’ll all use the same session object).
The .NET components, which make use of the COM+ Services, are termed as ServicedComponents. Must read this
link to learn more : http://msdn2.microsoft.com/en-us/library/ms973809.aspx
Number of Tables
A recordset looks like a single table. If a recordset is to contain data from multiple database tables, it must use a
JOIN query, which assembles the data from the various database tables into a single result table. In contrast, a
dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are
DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple
DataTable objects. That is, each DataTable object typically corresponds to a single database table or view. In this
way, a dataset can mimic the structure of the underlying database.
A dataset usually also contains relationships. A relationship within a dataset is analogous to a foreign-key
relationship in a database —that is, it associates rows of the tables with each other. For example, if a dataset contains
a table about investors and another table about each investor's stock purchases, it could also contain a relationship
connecting each row of the investor table with the corresponding rows of the purchase table. Because the dataset can
hold multiple, separate tables and maintain information about relationships between them, it can hold much richer
data structures than a recordset, including self-relating tables and tables with many-to-many relationships.
A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes
made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data
classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-
only cursor is available in the ADO.NET DataReader object. For more information about cursor unctionality, see
Data Access Technologies.
There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you
communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the
database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter
object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source. The
important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are
transmitted to the database — by optimizing for performance, performing data validation checks, or adding any
other extra processing.
Note - Data adapters, data connections, data commands, and data readers are the components that make up a .NET
Framework data provider. Microsoft and third-party providers can make available other .NET Framework data
providers that can be integrated into Visual Studio. For information on the different .NET Data providers, see .NET
Data Providers.
12. Can you give an example of what might be best suited to place in the Application_Start and Session_Start
subroutines?
Ans. The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. It’s a
good place to initialize global variables. For example, you might want to retrieve a list of products from a database
table and place the list in application state or the Cache object. SessionStateModule exposes both Session_Start and
Session_End events.
Polymorphism by definition means taking many forms. In C# it means the ability for classes to share the same
methods (actions) but implement them differently. For instance, say we create a class called "Shape" and this class
has a method called .draw() which draws the shape onto the user interface. Then we create two subclasses, using
inheritance, of this Shape class. One called Square, the other called Circle. Now obviously a square and circle are
two entirely different shapes, yet both classes have the .draw() method. When the Square.draw() method is called it
will draw a square on the user interface. When the Circle.draw() method is called, it will draw a circle on the user
interface. So both classes can use the same methods but implement them differently.
16. Can you explain what inheritance is and an example
of when you might use it?
Ans. Inheriting a trait from a parent class!
Use the existing functionality along with its own
properities.
Ans. Inline function bind at compile time can write in aspx page with in <% %> .
20. Explain what a diffgram is, and a good use for one.
Ans. A DiffGram is an XML format that is used to identify
current and original versions of data elements. The DataSet uses the DiffGram format to load and
persist its contents, and to serialize its contents for transport across a network connection. When
a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information
to accurately recreate the contents, though not the schema, of the DataSet, including
column values from both the Original and Current row versions, row error information, and row
order. When sending and retrieving a DataSet from an XML Web service, the DiffGram format is
implicitly used.
Additionally, when loading the contents of a DataSet from
XML using the ReadXml method, or when writing the
contents of a DataSet in XML using the WriteXml method,
you can select that the contents be read or written as a
DiffGram
DiffGram Format
The DiffGram format is divided into three sections: the
current data, the original (or "before") data, and an
errors section, as shown in the following example.
<?xml version="1.0"?>
<diffgr:diffgram
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DataInstance>
</DataInstance>
<diffgr:before>
</diffgr:before>
<diffgr:errors>
</diffgr:errors>
</diffgr:diffgram>
The DiffGram format consists of the following blocks of data:
<DataInstance>
The name of this element, DataInstance, is used for
explanation purposes in this documentation. A DataInstance
element represents a DataSet or a row of a DataTable.
Instead of DataInstance, the element would contain the name
of the DataSet or DataTable. This block of the DiffGram format contains the current data,
whether it has been modified or not.
An element, or row, that has been modified is identified with
the diffgr:hasChanges annotation.
<diffgr:before>
This block of the DiffGram format contains the original
version of a row. Elements in this block are matched to
elements in the DataInstance block using the diffgr:id
annotation.
<diffgr:errors>
This block of the DiffGram format contains error information
for a particular row in the DataInstance block. Elements in
this block are matched to elements in the DataInstance block
using the diffgr:id annotation.
24. Whats MSIL, and why should my developers need an appreciation of it if at all?
Ans. Microsoft Intermediate language. which is the out put
for all the .net supported languages after compilation will
produce. Appreciation is for cross language support.
Definition:Microsoft Intermediate Language (MSIL) is the
CPU-independent instruction set generated by .NET compilers
from .NET languages such as J#, C# or Visual Basic. MSIL is
compiled before or during execution of the program by a Virtual Execution System (VES), which
is part of the Common Language Runtime module (CLR).
25. In what order do the events of an ASPX page execute. As a developer is it important to
undertsand these events?
Ans.
Page request
The page request occurs before the page life cycle begins.
When the page is requested by a user, ASP.NET determines
whether the page needs to be parsed and compiled (therefore beginning the life of a page), or
whether a cached version
of the page can be sent in response without running the page.
Start
In the start step, page properties such as Request and
Response are set. At this stage, the page also determines
whether the request is a postback or a new request and sets
the IsPostBack property. Additionally, during the start step,
the page's UICulture property is set.
Page initialization
During page initialization, controls on the page are
available and each control's UniqueID property is set. Any
themes are also applied to the page. If the current request is
a postback, the postback data has not yet been loaded and
control property values have not been restored to the values
from view state.
Load
During load, if the current request is a postback, control
properties are loaded with information recovered from view
state and control state.
Validation
During validation, the Validate method of all validator
controls is called, which sets the IsValid property of
individual validator controls and of the page.
Unload
Unload is called after the page has been fully rendered, sent
to the client, and is ready to be discarded. At this point,
page properties such as Response and Request are unloaded and any cleanup is performed.
30. What property must you set, and what method must you call in your code, in order to
bind the data from some data source to the Repeatercontrol?
Ans. Datasource, DataBind
33. How do you turn off cookies for one page in your site?
Ans. Disablecookies.
Response.Cookies("Name") = "Nigel"
Response.Cookies("Name").Expires = DateAdd("m", 1, Now())
It’s that easy! Nothing more to it. You have now set a permanent cookie on your computer. Also,
note that whenever the above code is called the expiration date of the cookie is renewed by one
month from now.
There are a few more options which you can set, like for example the Path option. You can limit
cookies to certain paths on your website, so you can set several cookies with the same name, as
long as they belong to different paths. To do this, you would use the following code (extending
the previous code):
Response.Cookies("Name").Path = "/foo/"
The above code would limit the cookie to the path foo. It is
also possible to assign multiple values to a particular cookie.
This is done using the so-called dictionary functionality of
a cookie. For example, if I’d want to store not only the first
name, but also the surname in my Name cookie, I’d be using
something like the following code:
Response.Cookies("Name")("First") = "Nigel"
Response.Cookies("Name")("Last") = "Pallett"
Response.Cookies("Name").Expires = DateAdd("m", 1, Now())
That’s all! Although there are a few more "advanced" options,
such as the Secure option and the Domain option, it is of no use now.
Retrieving Cookies
Retrieving the value of cookies is a very easy job, because
again everything is handled by the browser and your server.
All you have to use is ASP’s inbuilt functions.
There is no difference in retrieving a Session cookie or a
permanent cookie, and in both cases you use the following code:
The above is for when you assigned only one value to a cookie. If you assigned multiple values
you a cookie, you use the following code:
44. Where on the Internet would you look for Web services?
Ans. UDDI
45. What tags do you need to add within the
asp:datagrid tags to bind columns manually.
Ans. Autogenerate columns
46. Which property on a Combo Box do you set with a column name, prior to setting the
DataSource, to display data in the combo box?
Ans. Datatext, Datavalue
47. How is a property designated as read-only?
Ans.
In VB.NET:
Public ReadOnly Property PropertyName As ReturnType
Get ‘Your Property Implementation goes in here
End Get
End Property
In C#
public returntype PropertyName
{
get{
//property implementation goes here
}
// Do not write the set implementation
}
48. Which control would you use if you needed to make sure the values in two different
controls matched?
Ans. Ideally we would tend to use Comparefield validator.
49. True or False: To test a Web service you must create a windows application or Web
application to consume this service?
Ans. False
.NET - is the Microsoft Web services strategy to connect information, people, systems, and
devices through software. Integrated across the Microsoft platform, .NET technology provides
the ability to quickly build, deploy, manage, and use connected, security-enhanced solutions with
Web services. .NET-connected solutions enable businesses to integrate their systems more
rapidly and in a more agile manner and help them realize the promise of information anytime,
anywhere, on any device. (Source: http://www.microsoft.com/net/Basics.mspx )
Size of a .NET object - Minimum 12 bytes. 4 bytes for the table pointer, 4 bytes for the sync
block, and 4 bytes or more for the datatypes in the class. Even if there is no data type in the class,
the object will take 12 bytes, as per the CLR's functionality.
Versions of .NET - The final version of the 1.0 SDK & runtime were made publically available
on 15 - Jan -2002. At the same time, the final version of Visual Studio.NET was made available
to MSDN subscribers. .NET 1.1 was released in April 2003, with bugs fixed. .NET 2.0 was
launched in October 2005 for MSDN subscribers, and officially released in Nov 2005. On - Jun -
2006, .NET 3.0 was launched. This version is called WinFX.
Operating systems support in .NET - The runtime supports Windows Server 2003,
Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported.
Some parts of the framework do not work on all platforms - for example, ASP.NET is only
supported on XP and Windows 2000/2003. Windows 98/ME cannot be used for development.
IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET.
However, the ASP.NET Web Matrix web server does run on XP Home.
.NET Compact Framework - is a version of .NET for mobile devices. They run Windows CE
or Widows Mobile.
The .NET Framework SDK is free and includes command-line compilers for C++, C#, and
VB.NET and various other utilities to aid development.
SharpDevelop is a free IDE for C# and VB.NET.
Microsoft Visual Studio Express editions are cut-down versions of Visual Studio, for hobbyist or
novice developers. There are different versions for C#, VB, web development etc. Originally
the plan was to charge $49, but MS has decided to offer them as free downloads instead, at
least until November 2006. Microsoft Visual Studio Standard 2005 is around $300, or $200 for
the upgrade. Microsoft VIsual Studio Professional 2005 is around $800, or $550 for the upgrade.
At the top end of the price range are the Microsoft Visual Studio Team Edition for Software
Developers 2005 with MSDN Premium and Team Suite editions. Visual Web Developer Express
is available as a free download.
CLI (Common Language Infrastructure) - is the definition of the fundamentals of the .NET
framework. It is documented through ECMA (http://msdn.microsoft.com/netframework/ecma/).
The fundamentals include the following:
*Metadata
CLR - Common Language Runtime - It is the implementation of CLI. The core runtime engine
in the Microsoft .NET Framework for executing applications. The common language runtime
supplies managed code with services such as cross-language integration, code access security,
object lifetime management, resouce management, type safety, pre-emptive threading, metadata
services (type reflection), and debugging and profiling support. The ASP.NET Framework and
Internet Explorer are examples of hosting CLR.
The CLR is a multi-language execution environment. There are currently over 15 compilers
being built by Microsoft and other companies that produce code that will execute in the CLR.
The CLR is described as the "execution engine" of .NET. It's this CLR that manages the
execution of programs. It provides the environment within which the programs run. The software
version of .NET is actually the CLR version.
When the .NET program is compiled, the output of the compiler is not an executable file but a
file that contains a special type of code called the Microsoft Intermediate Language (MSIL).
This MSIL defines a set of portable instructions that are independent of any specific CPU. It's the
job of the CLR to translate this Intermediate code into a executable code when the program is
executed making the program to run in any environment for which the CLR is implemented.
And that's how the .NET Framework achieves Portability. This MSIL is turned into executable
code using a JIT (Just In Time) complier. The process goes like this, when .NET programs are
executed, the CLR activates the JIT complier. The JIT complier converts MSIL into native
code on a demand basis as each part of the program is needed. Thus the program executes as a
native code even though it is compiled into MSIL making the program to run as fast as it would
if it is compiled to native code but achieves the portability benefits of MSIL.
Class Libraries - Class library is the another major entity of the .NET Framework. This library
gives the program access to runtime environment. The class library consists of lots of prewritten
code that all the applications created in VB .NET and Visual Studio .NET will use. The code for
all the elements like forms, controls and the rest in VB .NET applications actually comes from
the class library.
Common Language Specification (CLS) - If we want the code which we write in a language to
be used by programs in other languages then it should adhere to the Common Language
Specification (CLS). The CLS describes a set of features that different languages have in
common. The CLS includes a subset of Common Type System (CTS) which define the rules
concerning data types and ensures that code is executed in a safe environment.
Common Type Specification(CTS) - The Common Type System (CTS) defines the rules
concerning data types and ensures that code is executed in a safe environment. Since all .NET
applications are converted to IL before execution all primitive data types are represented as .NET
types. This means that, a VB Integer and a C# int are both represented in IL code as
System.Int32. Because both the languages use a common and interconvertible type system, it is
possible to transfer data between components and avoid time-consuming conversions.
When a compiler produces MSIL, it also produces metadata. Metadata describes the types in
your code, including the definition of each type, the signatures of each type's members, the
members that your code references, and other data that the runtime uses at execution time. The
MSIL and metadata are contained in a portable executable (PE) file that is based on and extends
the published Microsoft PE and common object file format (COFF) used historically for
executable content. This file format, which accommodates MSIL or native code as well as
metadata, enables the operating system to recognize common language runtime images. The
presence of metadata in the file along with the MSIL enables your code to describe itself, which
means that there is no need for type libraries or Interface Definition Language (IDL). The
runtime locates and extracts the metadata from the file as needed during execution.
Managed Code - The .NET framework provides lots of core runtime services to the programs
that run within it. For example - security & exception handling. Such a code has a minimum
level of information. It has metadata associated with it. Such a code is called Managed Code.
VB.NET, C#, JS.NET code is managed by default. In order to make C++ code managed, we
make use of managed extensions, which is nothing but a postfix _gc after the class name.
Managed Data - Data that is allocated & freed by the .NET runtime's Garbage collecter.
Managed Class - A class whose objects are managed by the CLR's garbage collector. In
VC++.NET, classes are not managed. However, they can be managed using managed extentions.
This is done using an _gc postfix. A managed C++ class can inherit from VB.NET classes, C#
classes, JS.NET classes. A managed class can inherit from only one class. .NET does'nt allow
multiple inheritance in managed classes.
Reflection - The process of getting the metadata from modules/assemblies. When .NET code is
compiled, metadata about the types defined in the modules is produced. These modules are in
turn packaged as assemblied. The process of accessing this metadata in called Reflection.
The namespace System.Reflection contains classes that can be used for interrogating the types
for a module/assembly. We use reflection for examining data type sizes for marshalling across
process & machine boundaries.
Assembly - An assembly may be an exe, a dll, an application having an entry point, or a library.
It may consist of one or more files. It represents a group of resources, type definitions, and
implementation of these types. They may contain references to other assemblies. These
resources, types & references are compacted in a block of data called manifest. The manifest is a
part of the assembly, which makes it self-describing. Assemblies also increase security of code in
.NET. An assembly maybe shared(public) or private.
An assembly may be created by building the class(the .vb or .cs file), thereby producing its DLL.
ILDASM - The contents of an assembly may be viewed using the ILDASM tool, that comes
with the .NET SDK or the Visual Studio.NET.
Private Assembly - This type of assembly is used by a single application. It is stored in the
application's directory or the applications sub-directory. There is no version constraint in a
private assembly.
Shared Assembly (or Public Assembly) - A shared assembly has version constraint. It is stored
in the Global Assembly Cache (GAC). GAC is a repository of shared assemblies maintained by
the .NET runtime. The shared assemblies may be used by many applications. To make an
assembly a shared assembly, it has to be strongly named.
In order to share an assembly with many applications, it must have a strong name.
In order to convert a private assembly to a shared assembly, i.e. to create a strongly named
assembly, follow the steps below...
1) Create a strong key using the sn.exe tool. This is used to created a cryptographic key pair. The
key pair that is generated by the Strong Name tool can be kept in a file or we can store it our
your local machine's Crytographic Service Provider (CSP). For this, goto the .NET command
interpreter, and type the following...
sn -k C:\samplekey.snk
This will create a strong key and save it to the location C:\samplekey.snk
2) If the key is stored in a file, just like we have done above, we use the attribute
AssemblyKeyFileAttribute. This belongs to the namespace
System.Reflection.AssemblyKeyFileAttribute.
Go to the assemblyinfo.vb file of your project. Open this file. Make the following changes in this
file...
<assembly: assemblykeyfileattribute("C:\samplekey.snk")>
Imports System.Reflection
<assembly: assemblykeyfileattribute("C:\samplekey.snk")>
Namespace StrongName
Public class Sample
End Class
End Namespace
Assembly Versioning - Each assembly (shared assembly) has a version. Its called the
compatibility version. There are 4 parts in the version, namely Major, Minor, Build, Version. If
the first two parts are same, then two assemblies are compatible. If they are different, they are
incompatible. If the third part is different, then the two assemblies may or may not be
compatible. If only the fourth part is different, then they are surely compatible. The version
policy may be applied using the application's configuration file(.config file). Application Domain
- An application domain is a process running on the .NET runtime. In a Win32 environment, the
application domain can host several instances known as processes on the machine. An
application domain may be destroyed, without affecting other processes, as each application
domain is a separate process. The host, which is the Windows shell, creates a new application
domain for every application. For example, several instances of Internet Explorer may be
running on a single PC. Garbage Collection - Garbage collection is a heap-management strategy
where a run-time component takes responsibility for managing the lifetime of the memory used
by objects. This concept is not new to .NET - Java and many other languages/runtimes have used
garbage collection for some time. The garbage collector runs periodically. It runs through a list of
objects that are currently being referenced by an application. All objects that it does not find
during this search are ready to be destroyed (using the finalize method) and hence free the
memory. However, the runtime gets notified of the object that has been destroyed, only in the
next round of the garbage collector's periodic cycle.
In the class System.GC, there is a method called collect( ). This forces the garbage collector to
collect all unreferenced objects immediately, thereby giving the developer some control over the
garbage collector.
There is a gcConcurrent setting that can be set through the applications's .config file. This
specifies whether or not the garbage collector performs its activities on a specified thread or not.
We can view the performance monitor to view the activities of the garbage collector.
IDisposable interface - We implement this interface to a class when we have to work with
unmanaged types. For example, an IntPtr member representing an operating system's file
handler is actually unmanaged, and in order to destroy it, we make use of the Dispose method
by implementing the IDisposable interface. In this case, we override the Finalize method.
Note that we make use of Dispose method on those objects which have an uncertain life
period, and thus the garbage collector does not finalize them automatically.
We also make use of Dispose method while working with managed code, for example, an object
os System.IO.FileStream may have an uncertain life, and in order to dispose it, we use the
dispose method. Such types of objects are not accessed by the Garbage Collector's Finalizer.
Serialization - The process of converting an object into a stream of bytes.This stream of bytes
can be persisted. Deserialization is an opposite process, which involves converting a stream of
bytes into an object. Serialization is used usually during remoting (while transporting objects)
and to persist file objecst & database objects.
The XmlSerializer is used for Web Services. The BinaryFormatter & SoapFormatter is used for
Remoting.
While using XmlSerializer, it is required that the target class has parameter less constructors,
has public read-write properties and has fields that can be serialized. The XmlSerializer has good
support for XML documents. It can be used to construct objects from existing XML documents.
The XmlSerializer Enables us to serialize and deserialize objects to an XML format.
SoapFormatter enables us to serialize & deserialize objects to SOAP format. They can serialize
private and public fields of a class. The target class must be marked with the Serializable
attribute. On deserialization, the constructor of the new object is not invoked.
The BinaryFormatter has the same features as the SoapFormatter except that it formats data
into binary format.
The BinaryForamatter (and the SoapFormatter) has two main methods. Serialize and Deserialize.
To serialize an object, we pass an instance of the stream and the object to the Serialize method.
To Deserialize an object, you pass an instance of a stream to the Deserialize method.
You can use the BinaryFormatter to serialize many, but not all, classes in the .NET Framework.
For example, you can serialize ArrayLists, DataSets, and Arrays but not other objects, such as
DataReaders or TextBox controls. To serialize a class, the class must have the Serializable
attribute or implement the ISerializable interface.
Note that the XmlSerializer captures only the public members of the class, whereas the
BinaryFormatter & the SoapFormatter captures both the public & private members of the class.
The output using the BinaryFormatter is quite compact, as the information is in binary format,
whereas the XmlSerializer format is filled with XML tags.
objFileStream As FileStreamDim
colArrayList.Add( "Vodka")
colArrayList.Add( "Brandy")
Here we see that an instance of the file stream (objFileStream) and an instance of the object
(colArrayList) is passed to the Serialize method of the BinaryFormatter object
(objBinaryFormatter). We also end up creating a file by the name myArrayList.data on our hard-
drive.In order to deserialize an object, see the code below…
objFileStream.Close()
Next
Here, CType takes in two parameters, the first parameter is the serialized object in the file stream
format, and the second parameter is the desired type. Finally, the page iterates through all the
elements of the ArrayList and displays the value of each element.
Example below shows how we can serialize a class to a database table... Imports System
Namespace myComponents
Xml Serializer does not serialize instances of classes like Hashtable which implement the
IDictionary interface.
Attributes - Is a kind of property attached with a class. It allows some data to be attached to a
class or method. This data becomes part of the metadata for the class, and (like other class
metadata) can be accessed via reflection. An example of a metadata attribute is [serializable],
which can be attached to a class and means that instances of the class can be serialized.
[Serializable]
( ... )
Code Access Security (CAS) - CAS is the part of the .NET security model that determines
whether or not code is allowed to run, and what resources it can use when it is running. For
example, it is CAS that will prevent a .NET web applet from formatting your hard disk. The
CAS security policy revolves around two key concepts - code groups and permissions. Each
.NET assembly is a member of a particular code group, and each code group is granted the
permissions specified in a named permission set. For example, using the default security policy,
a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres
to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named
permission set represents a very restrictive range of permissions.) To view codegroups on our
system, use the following command on .NET command interpretor... caspol -lg Note the
hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then
sub-divided into several groups, each of which in turn can be sub-divided. Also note that
(somewhat counter-intuitively) a sub-group can be associated with a more permissive permission
set than its parent. If we want to trust a particular website giving it full rights to our system...Use
caspol. For example, suppose we trust code from www.mydomain.com and we want it have full
access to our system, but we want to keep the default restrictions for all other internet sites. To
achieve this, we would add a new code group as a sub-group of the 'Zone - Internet' group, like
this: caspol -ag 1.3 -site www.mydomain.com FullTrust To change the permission, we use the
-cg attribute.To turn off caspol, use caspol -s off
Threads - When we want to run one or more instances of a method, we make use of threading.
Suppose we have a method like this... Private Sub OnGoingProcess()
Dim i As Integer = 1
Do While True
ListBox1.Items.Add("Repeatitions: " + i)
i += 1
Loop
End Sub Dim t As Thread
t = New Thread(AddressOf Me.OnGoingProcess)
t.Start()
The AddressOf operator creates a delegate object to the BackgroundProcess method. A delegate
within VB.NET is a type-safe, object-oriented function pointer. After the thread has been
instantiated, you begin the execution of the code by calling the Start() method of the thread. After
the thread is started, you have some control over the state of it by using methods of the Thread
object. You can pause a thread's execution by calling the Thread.Sleep method. This method
takes an integer value that determines how long the thread should sleep. If you wanted to slow
down the addition of items to the listbox in the example above, place a call to the sleep method
in this code:
Do While True
ListBox1.Items.Add("Repeatitions: " + i)
i += 1
Thread.CurrentThread.Sleep(2000)
Loop
End Sub
You can also place a thread into the sleep state for an indeterminate amount of time by calling
Thread.Sleep (System.Threading.Timeout.Infinite). To interrupt this sleep you can call the
Thread.Interrupt method. Similar to Sleep and Interrupt are Suspend and Resume. Suspend
allows you to block a thread until another thread calls Thread.Resume. The difference between
Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The
thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it.
Sleep will immediately place a thread in a wait state. Lastly, Thread.Abort stops a thread from
executing. In our simple example, we would want to add another button on the form that allows
us to stop the process. To do this all we would have to do is call the Thread.Abort method as
follows:
Use this code to start the CalcSquare procedure on a new thread. following code:
oSquare.Value = 30
t.Start()
End Sub
Notice that after the thread is started, we do not inspect the square value of the class, because it
is not guaranteed to have executed once you call the start method of the thread. There are a few
ways to retrieve values back from another thread. The easiest way is to raise an event when the
thread is complete. We will examine another method in the next section on thread
synchronization. The following code adds the event declarations to the SquareClass.
Public Class SquareClass
Public Value As Double
Public Square As Double
Catching the events in the calling code has not changed much from VB6, you still declare the
variables WithEvents and handle the event in a procedure. The part that has changed is that you
declare that a procedure handles the event using the Handles keyword and not through the
naming convention of Object_Event as in VB6. Dim WithEvents oSquare As SquareClass
oSquare.Value = 30
t.Start()
End Sub
End Sub
The one thing to note with this method is that the procedure handling the event, in this case
SquareEventHandler, will run within the thread that raised the event. It does not run within the
thread from which the form is executing. (Source:
www.devx.com)
Trace and Debug - There are two main classes that deal with tracing - Debug and Trace. They
both work in a similar way - the difference is that tracing from the Debug class only works in
builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in
builds that have the TRACE symbol defined. Typically this means that you should use
System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release
builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in
debug builds.Tracing is actually the process of collecting information about the program's
execution.Debugging is the process of finding & fixing errors in our program. Tracing is the
ability of an application to generate information about its own execution. The idea is that
subsequent analysis of this information may help us understand why a part of the application is
not behaving as it should and allow identification of the source of the error.
We shall look at two different ways of implementing tracing in .NET via the
System.Web.TraceContext class via the System.Diagnostics.Trace and
System.Diagnostics.Debug classes Tracing can be thought of as a better (more featureful and
automated) alternative to the response.writes we used to put in our old ASP3.0 code to help
debug pages!
If we set the Tracing attribute of the Page Directive to True, then Tracing is enabled. The output
is appended in the web form output. Messeges can be displayed in the Trace output using
Trace.Warn & Trace.Write. The only difference between Trace.Warn & Trace.Write is that the
former has output in red color. If the trace is false, there is another way to enable tracing. This is
done through the application level. We can use the web.config file and set the trace attribute to
true. Here we can set <trace enabled=false .../>
Note that the Page Directive Trace attribute has precedence over th application level trace
attribute of web.config. While using application level tracing, we can view the trace output in the
trace.axd file of the project. For more information on Trace & Debug CLICK HERE