DotNet FrameWork Series Completion – Successful

Last Month we have seen most of  the basic Questions that can sometime come in our mind when we are new to Dot Net. I was also one amongst them so thought to learn and put it here so that not even me all our community can take advantage of it.

I will be more than Happy to hear any news, updates or Questions on My Framework Basic series.

you can get the complete series topic here Dotnet Framework series.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

DotNet FrameWork – What actually happens when you add something to an arraylistcollection – How Boxing and unboxing occures in memory – Why only boxed types can be unboxed – Day 30 of 30

What actually happens when you add  something to an arraylistcollection ?

Following things will happen :

Arraylist is a dynamic array class in c# in System.Collections namespace derived from interfaces – ICollection , IList , ICloneable , IConvertible  . It terms of in memory structure following is the implementation .

a. Check up the total space if there’s any free space on the declared list .

b. If yes add the new item and increase count by 1 .

c. If No Copy the whole thing to a temporary Array of Last Max. Size .

d. Create new Array with size ( Last Array Size + Increase Value )

e. Copy back values from temp and reference this new array as original array .

f. Must doing Method updates too , need to check it up .

What is Boxing and unboxing? Does it occure automaatically or u need to write code to box and unbox?

Boxing – Process of converting a System.ValueType to Reference Type , Mostly base class System.Object type and allocating it memory on Heap .Reverse is unboxing , but can only be done with prior boxed variables.

Boxing is always implicit but Unboxing needs to be explicitly done via casting , thus ensuring the value type contained inside .

How Boxing and unboxing occures in memory?

Boxing converts value type to reference type , thus allocating memory on Heap . Unboxing converts already boxed reference types to value types through explicit casting , thus  allocating memory on stack .

Why only boxed types can be unboxed?

Unboxing is the process of converting a Reference type variable to Value type and thus allocating memory on the stack . It happens only to those Reference type variables that have been earlier created by Boxing of a Value Type , therefore internally they contain a value type , which can be obtained through explicit casting . For any other Reference type , they don’t internally contain a Value type to Unboxed via explicit casting . This is why only boxed types can be unboxed .

Please read all the post in the Dotnet Framework series.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

DotNet FrameWork – What is the difference between typeof(foo) and myFoo.GetType() – Day 28 of 30

What is the difference between typeof(foo) and myFoo.GetType()?

Typeof is operator which applied to a object returns System.Type object. Typeof cannot be overloaded white GetType has lot of overloads.GetType is a method which also returns System.Type of an object. GetType is used to get the runtime type of the object.

Example from MSDN showing Gettype used to retrive type at runtime:-

public class MyBaseClass: Object {   ………………..   }

public class MyDerivedClass: MyBaseClass {  ………………   }

public class Test {

public static void Main() {

MyBaseClass myBase = new MyBaseClass();

MyDerivedClass myDerived = new MyDerivedClass();

object o = myDerived;

MyBaseClass b = myDerived;

Console.WriteLine(“mybase: Type is {0}”, myBase.GetType());

Console.WriteLine(“myDerived: Type is {0}”, myDerived.GetType());

Console.WriteLine(“object o = myDerived: Type is {0}”, o.GetType());

Console.WriteLine(“MyBaseClass b = myDerived: Type is {0}”, b.GetType());

}

}

/*

This code produces the following output.

mybase: Type is MyBaseClass

myDerived: Type is MyDerivedClass

object o = myDerived: Type is MyDerivedClass

MyBaseClass b = myDerived: Type is MyDerivedClass

*/

Can “this” be used within a static method?

No ‘This’ cannot be used in a static method. As only static variables/methods can be used in a static method.

Please read all the post in the Dotnet Framework series.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

DotNet FrameWork – difference between Finalize() and Dispose() – How is the using() pattern useful – What is Program Database (PDB) – Day 27 of 30

What is the difference between Finalize() and Dispose()?

Dispose() is called by the user of an object to indicate that he is finished with it, enabling that object to release any unmanaged resources it holds. Finalize() is called by the run-time to allow an object which has not had Dispose() called on it to do the same. However, Dispose() operates determinalistically, whereas there is no guarantee that Finalize() will be called immediately when an object goes out of scope – or indeed at all, if the program ends before that object is GCed – and as such Dispose() is generally preferred.

How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?

The using() pattern is useful because it ensures that Dispose() will always be called when a disposable object (defined as one that implements IDisposable, and thus the Dispose() method) goes out of scope, even if it does so by an exception being thrown, and thus that resources are always released.

What does this useful command line do? tasklist /m “mscor*”

Lists all the applications and associated tasks/process currently  running on the system with a module whose name begins “mscor” loaded into them; which in nearly all cases means “all the .NET processes”.

What’s wrong with a line like this? DateTime.Parse(myString);

There’s nothing wrong with this declaration.Converts the specified string representation of a date and time to its DateTime equivalent.But If the string is not a valid DateTime,It throws an exception.

What are PDBs? Where must they be located for debugging to work?

A program database (PDB) files holds debugging and project state information that allows incremental linking of debug configuration of your program.There are several different types of symbolic debugging information. The default type for Microsoft compiler is the so-called PDB file. The compiler setting for creating this file is /Zi, or /ZI for C/C++(which creates a PDB file with additional information that enables a feature called “”Edit and Continue””) or a Visual Basic/C#/JScript .NET program with /debug.

A PDB file is a separate file, placed by default in the Debug project subdirectory, that has the same name as the executable file with the extension .pdb. Note that the Visual C++ compiler by default creates an additional PDB file called VC60.pdb for VisulaC++6.0 and VC70.PDB file for VisulaC++7.0. The compiler creates this file during compilation of the source code, when the compiler isn’t aware of the final name of the executable. The linker can merge this temporary PDB file into the main one if you tell it to, but it won’t do it by default. The PDB file can be useful to display the detailed stack trace with source files and line numbers.

What is FullTrust? Do GAC’ed assemblies have FullTrust?

Before the .NET Framework existed, Windows had two levels of trust for downloaded code. This old model was a binary trust model. You only had two choices: Full Trust, and No Trust. The code could either do anything you could do, or it wouldn’t run at all.

The permission sets in .NET include FullTrust, SkipVerification, Execution, Nothing, LocalIntranet, Internet and Everything. Full Trust Grants unrestricted permissions to system resources. Fully trusted code run by a normal, nonprivileged user cannot do administrative tasks, but can access any resources the user can access, and do anything the user can do. From a security standpoint, you can think of fully trusted code as being similar to native, unmanaged code, like a traditional ActiveX control.

GAC assemblies are granted FullTrust. In v1.0 and 1.1, the fact that assemblies in the GAC seem to always get a FullTrust grant is actually a side effect of the fact that the GAC lives on the local machine.  If anyone were to lock down the security policy by changing the grant set of the local machine to something less than FullTrust, and if your assembly did not get extra permission from some other code group, it would no longer have FullTrust even though it lives in the GAC.

What does this do? gacutil /l | find /i “Corillian”

The Global Assembly Cache tool allows you to view and manipulate the contents of the global assembly cache and download cache.The tool comes with various optional params to do that.

“”/l”” option Lists the contents of the global assembly cache. If you specify the assemblyName parameter(/l [assemblyName]), the tool lists only the assemblies matching that name.

What does this do .. sn -t foo.dll ?

Sn -t option displays the token for the public key stored in infile. The contents of infile must be previously generated using -p.

Sn.exe computes the token using a hash function from the public key. To save space, the common language runtime stores public key tokens in the manifest as part of a reference to another assembly when it records a dependency to an assembly that has a strong name. The -tp option displays the public key in addition to the token.

How do you generate a strong name?

.NET provides an utility called strong name tool. You can run this toolfrom the VS.NET command prompt to generate a strong name with an option “-k” and providing the strong key file name. i.e. sn- -k < file-name >

What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?

The Debug build is the program compiled with full symbolic debug information and no optimization. The Release build is the program compiled employing  optimization and contains no symbolic debug information. These settings can be changed as per need from Project Configuration properties. The release runs faster since it does not have any debug symbols and is optimized.

Explain the use of virtual, sealed, override, and abstract.

Abstract: The keyword can be applied for a class or method.

1. Class: If we use abstract keyword for a class it makes the

class an abstract class, which means it cant be instantiated. Though

it is not nessacary to make all the method within the  abstract class to be virtual. ie, Abstract class can have concrete methods

2. Method: If we make a method as abstract, we dont need to provide implementation

of the method in the class but the derived class need to implement/override this method.

Sealed: It can be applied on a class and methods. It stops the type from further derivation i.e no one can derive class

from a sealed class,ie A sealed class cannot be inherited.A sealed class cannot be a abstract class.A compile time error is thrown if you try to specify sealed class as a  base class.

When an instance method declaration includes a sealed modifier, that method is said to be a sealed method. If an instance method declaration includes the sealed modifier, it must also include the override modifier. Use of the sealed modifier prevents a derived class from further overriding the method  For Egs: sealed override public void Sample() { Console.WriteLine(“Sealed Method”); }

Virtual & Override: Virtual & Override keywords provides runtime polymorphism. A base class can make some of its methods

as virtual which allows the derived class a chance to override the base class implementation by using override keyword.

For e.g. class Shape

{

int a

public virtual void Display()

{

Console.WriteLine(“Shape”);

}

}

class Rectangle:Shape

{

public override void Display()

{

Console.WriteLine(“Derived”);

}

}

Explain the importance and use of each, Version, Culture and PublicKeyToken for an assembly.

This three along with name of the assembly provide a strong name or fully qualified name to the assembly. When a assembly is referenced with all three.

PublicKeyToken: Each assembly can have a public key embedded in its manifest that identifies the developer. This ensures that once the assembly ships, no one can modify the code or other resources contained in the assembly.

Culture: Specifies which culture the assembly supports

Version: The version number of the assembly.It is of the following form major.minor.build.revision.

Explain the differences between public, protected, private and internal.

These all are access modifier and they governs the access level. They can be applied to class, methods, fields.

Public: Allows class, methods, fields to be accessible from anywhere i.e. within and outside an assembly.

Private: When applied to field and method allows to be accessible within a class.

Protected: Similar to private but can be accessed by members of derived class also.

Internal: They are public within the assembly i.e. they can be accessed by anyone within an assembly but outside assembly they are not visible.

Please read all the post in the Dotnet Framework series.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

DotNet FrameWork – ASP.NET Web Services vs. .NET Remoting – Security – Asssembly Qualified Name – Day 26 of 30

Distributed Application Design: ASP.NET Web Services vs. .NET Remoting

ASP.NET Web services favor the XML Schema type system, and provide a simple programming model with broad cross-platform reach. .NET Remoting favors the runtime type system, and provides a more complex programming model with much more limited reach. This essential difference is the primary factor in determining which technology to use. However, there are a wide range of other design factors, including transport protocols, host processes, security, performance, state management, and support for transactions to consider as well.

Security

Since ASP.NET Web services rely on HTTP, they integrate with the standard Internet security infrastructure. ASP.NET leverages the security features available with IIS to provide strong support for standard HTTP authentication schemes including Basic, Digest, digital certificates, and even Microsoft® .NET Passport. (You can also use Windows Integrated authentication, but only for clients in a trusted domain.) One advantage of using the available HTTP authentication schemes is that no code change is required in a Web service; IIS performs authentication before the ASP.NET Web services are called. ASP.NET also provides support for .NET Passport-based authentication and other custom authentication schemes. ASP.NET supports access control based on target URLs, and by integrating with the .NET code access security (CAS) infrastructure. SSL can be used to ensure private communication over the wire.

Although these standard transport-level techniques to secure Web services are quite effective, they only go so far. In complex scenarios involving multiple Web services in different trust domains, you have to build custom ad hoc solutions. Microsoft and others are working on a set of security specifications that build on the extensibility of SOAP messages to offer message-level security capabilities. One of these is the XML Web Services Security Language (WS-Security), which defines a framework for message-level credential transfer, message integrity, and message confidentiality.

As noted in the previous section, the .NET Remoting plumbing does not secure cross-process invocations in the general case. A .NET Remoting endpoint hosted in IIS with ASP.NET can leverage all the same security features available to ASP.NET Web services, including support for secure communication over the wire using SSL. If you are using the TCP channel or the HTTP channel hosted in processes other than aspnet_wp.exe, you have to implement authentication, authorization and privacy mechanisms yourself.

One additional security concern is the ability to execute code from a semi-trusted environment without having to change the default security policy. ASP.NET Web Services client proxies work in these environments, but .NET Remoting proxies do not. In order to use a .NET Remoting proxy from a semi-trusted environment, you need a special serialization permission that is not given to code loaded from your intranet or the Internet by default. If you want to use a .NET Remoting client from within a semi-trusted environment, you have to alter the default security policy for code loaded from those zones. In situations where you are connecting to systems from clients running in a sandbox—like a downloaded Windows Forms application, for instance—ASP.NET Web Services are a simpler choice because security policy changes are not required.

Conceptually, what is the difference between early-binding and late-binding?

Early binding – Binding at Compile Time

Late Binding – Binding at Run Time

Early binding implies that the class of the called object is known at compile-time; late-binding implies that the class is not known until run-time, such as a call through an interface or via Reflection.

Early binding is the preferred method. It is the best performer because your application binds directly to the address of the function being called and there is no extra overhead in doing a run-time lookup. In terms of overall execution speed, it is at least twice as fast as late binding.

Early binding also provides type safety. When you have a reference set to the component’s type library, Visual Basic provides IntelliSense support to help you code each function correctly. Visual Basic also warns you if the data type of a parameter or return value is incorrect, saving a lot of time when writing and debugging code.

Late binding is still useful in situations where the exact interface of an object is not known at design-time. If your application seeks to talk with multiple unknown servers or needs to invoke functions by name (using the Visual Basic 6.0 CallByName function for example) then you need to use late binding. Late binding is also useful to work around compatibility problems between multiple versions of a component that has improperly modified or adapted its interface between versions.

What is an Asssembly Qualified Name? Is it a filename? How is it different?

An assembly qualified name isn’t the filename of the assembly; it’s the internal name of the assembly combined with the assembly version, culture, and public key, thus making it unique.

e.g. (“”System.Xml.XmlDocument, System.Xml, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″”)

How is a strongly-named assembly different from one that isn’t strongly-named?

Strong names are used to enable the stricter naming requirements associated with shared assemblies. These strong names are created by a .NET utility – sn.exe

Strong names have three goals:

· Name uniqueness. Shared assemblies must have names that are globally unique.

· Prevent name spoofing. Developers don’t want someone else releasing a subsequent version of one of your assemblies and falsely claim it came from you, either by accident or intentionally.

· Provide identity on reference. When resolving a reference to an assembly, strong names are used to guarantee the assembly that is loaded came from the expected publisher.

Strong names are implemented using standard public key cryptography. In general, the process works as follows: The author of an assembly generates a key pair (or uses an existing one), signs the file containing the manifest with the private key, and makes the public key available to callers. When references are made to the assembly, the caller records the public key corresponding to the private key used to generate the strong name.

Weak named assemblies are not suitable to be added in GAC and shared. It is essential for an assembly to be strong named.Strong naming prevents tampering and enables assemblies to be placed in the GAC alongside other assemblies of the same name.

How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?

The hugely simplistic version is that every time it garbage-collects, it starts by assuming everything to be garbage, then goes through and builds a list of everything reachable. Those become not-garbage, everything else doesn’t, and gets thrown away. What makes it generational is that every time an object goes through this process and survives, it is noted as being a member of an older generation (up to 2, right now). When the garbage-collector is trying to free memory, it starts with the lowest generation (0) and only works up to higher ones if it can’t free up enough space, on the grounds that shorter-lived objects are more likely to have been freed than longer-lived ones.

Non-deterministic finalization implies that the destructor (if any) of an object will not necessarily be run (nor its memory cleaned up, but that’s a relatively minor issue) immediately upon its going out of scope. Instead, it will wait until first the garbage collector gets around to finding it, and then the finalisation queue empties down to it; and if the process ends before this happens, it may not be finalised at all. (Although the operating system will usually clean up any process-external resources left open – note the usually there, especially as the exceptions tend to hurt a lot.)

Please read all the post in the Dotnet Framework series.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )

DotNet FrameWork – what an Interface is and how it’s different from a Class – difference between XML Web Services using ASMX and .NET Remoting using SOAP – Serialization and Metadata – Day 25 of 30

Describe what an Interface is and how it’s different from a Class.

An interface is a structure of code which is similar to a class. An interface is a prototype for a class and is useful from a logical design perspective. Interfaces provide a means to define the protocols for a class without worrying about the implementation details. The syntax for creating interfaces follows:

interface Identifier {  InterfaceBody  }

Identifier is the name of the interface and InterfaceBody refers to the abstract methods and static final variables that make up the interface. Because it is assumed that all the methods in an interface are abstract, it isn’t necessary to use the abstract keyword

An interface is a description of some of the members available from a class. In practice, the syntax typically looks similar to a class definition, except that there’s no code defined for the methods — just their name, the arguments passed and the type of the value returned.

So what good is it? None by itself. But you create an interface so that classes will implement it.

But what does it mean to implement an interface. The interface acts as a contract or promise. If a class implements an interface, then it must have the properties and methods of the interface defined in the class. This is enforced by the compiler.

Broadly the differentiators between classes and interfaces is as follows

• Interface should not have any implementation.

• Interface can not create any instance.

• Interface should provide high level abstraction from the implementation.

• Interface can have multiple inheritances.

• Default access level of the interface is public.

What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?

ASP.NET Web services and .NET Remoting provide a full suite of design options for cross-process and cross-plaform communication in distributed applications. In general, ASP.NET Web services provide the highest levels of interoperability with full support for WSDL and SOAP over HTTP, while .NET Remoting is designed for common language runtime type-system fidelity and supports additional data format and communication channels. Hence if we looking cross-platform communication than web services is the choice coz for .NET remoting .Net framework is requried which may or may not present for the other platform.

Serialization and Metadata

ASP.NET Web services rely on the System.Xml.Serialization.XmlSerializer class to marshal data to and from SOAP messages at runtime. For metadata, they generate WSDL and XSD definitions that describe what their messages contain. The reliance on pure WSDL and XSD makes ASP.NET Web services metadata portable; it expresses data structures in a way that other Web service toolkits on different platforms and with different programming models can understand. In some cases, this imposes constraints on the types you can expose from a Web service—XmlSerializer will only marshal things that can be expressed in XSD. Specifically, XmlSerializer will not marshal object graphs and it has limited support for container types.

.NET Remoting relies on the pluggable implementations of the IFormatter interface used by the System.Runtime.Serialization engine to marshal data to and from messages. There are two standard formatters, System.Runtime.Serialization.Formatters.Binary.BinaryFormatter and System.Runtime.Serialization.Formatters.Soap.SoapFormatter. The BinaryFormatter and SoapFormatter, as the names suggest, marshal types in binary and SOAP format respectively. For metadata, .NET Remoting relies on the common language runtime assemblies, which contain all the relevant information about the data types they implement, and expose it via reflection. The reliance on the assemblies for metadata makes it easy to preserve the full runtime type-system fidelity. As a result, when the .NET Remoting plumbing marshals data, it includes all of a class’s public and private members; handles object graphs correctly; and supports all container types (e.g., System.Collections.Hashtable). However, the reliance on runtime metadata also limits the reach of a .NET Remoting system—a client has to understand .NET constructs in order to communicate with a .NET Remoting endpoint. In addition to pluggable formatters, the .NET Remoting layer supports pluggable channels, which abstract away the details of how messages are sent. There are two standard channels, one for raw TCP and one for HTTP. Messages can be sent over either channel independent of format.

Please read all the post in the Dotnet Framework series.

Reference : Dilip Kumar Jena ( https://mstechexplore.wordpress.com )