Great way to earn money!

Zone1

Wednesday, February 29, 2012

Some CSHARP Questions Part 4



Abstract Class vs Interface


A class can implement any number of interfaces but a subclass can at most inherit from only one abstract class.
 
An abstract class can have non-abstract Methods(concrete methods) while in case of Interface all the methods has to be abstract.
 
An abstract class can declare or use any variables while an interface is not allowed to do so.


following Code will not compile
interface TestInterface
{
    int x = 4;  // Filed Declaration in Interface
    void getMethod();
 
    string getName();
}
An abstract class can have constructor declaration while an interface can not do so.

An abstract Class is allowed to have all access modifiers for all of its member declaration while in interface  we can not declare any access modifier(including public) as all the members of interface are implicitly public. 
Although it is perfectly legal to make interface access specifier as  Public (Remember only public is allowed)




Below code is correct :
public interface TestInterface
{
    void getMethod();
    string getName();
}

Below code is wrong:
interface TestInterface
{
    public void getMethod();
    string getName();
}




Tuesday, February 28, 2012

Some CSHARP Questions Part 3

Differentiate Finalize(), Dispose() and Destructors
Dispose() is called by as an indication for an object to release any unmanaged resources it has held.

Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object.

Dispose() operates determinalistically due to which it is generally preferred.


In C#, a destructor and a finalizer refer to the same thing, the function called before the object is fully-removed from the memory (i.e. GC-collected)   and it applies to c sharp only.





class BaseClass {     public ~BaseClass()     {         Console.WriteLine("dtor of BaseClass");     } } class DerivedClass : BaseClass {     public ~DerivedClass()     {         Console.WriteLine("dtor of DerivedClass");     } } class ChildClass : DerivedClass {     public ~ChildClass()     {         Console.WriteLine("dtor of ChildClass");     } }



When you define a class destructor with that C++-alike syntax (preceding the function name with a ~) the compiler actually replaces your destructor with an override of the virtual Object.Finalize() function. 



That is, before the object is removed (i.e. GC-collected) from the memory, the finalizer (i.e. destructor) is called first. 



This finalizer first executes your code. After that it calls the finalizer of the base type of your object. If we could decompile your assembly, would see that our destructor in the ChildClass (so other classes) has been replaced with this function:
protected virtual void Finalize()

{

    try

    {

        Console.WriteLine("dtor of ChildClass");

    }

    finally

    {

        base.Finalize();

    }
}
Finalizers are a feature of GC managed objects (i.e. managed classes). 


That's because the finalizer is called only when the GC removes the object from the memory (i.e. frees memory associated with).

You can't determine when finalizers would be called


That's because you don't know when the next garbage collection would occur, even if you performed a manual garbage collection (using System.GC.Collect() function) you won't know exactly when memory would be released.










Difference between System.String and StringBuilder


Every time we manipulate a string object we get a new string object created.


String is immutable means that once it has been created, a string cannot be changed.

No characters can be added or removed from it, nor can its length be changed.
The String object is immutable while StringBuilder object is mutable.

Both String and StringBuilder are reference type. But String acts like a value type.

StringBuilder is located in the System.Text namespace.
The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object.

Using the StringBuilder class can boost performance when concatenating many strings together in a loop.

Below is a small program:

        private void Example_StringBuilder()

        {
            StringBuilder String1 = new StringBuilder("beautiful");

            StringBuilder String2 = new StringBuilder();

            String2 = String1.Append(" Picture");

            // value of String2="beautiful Picture"

            String2 = String1.Remove(2, 4);

            // value of String2="beful Picture"

            String2 = String1.Insert(2, "auti");

            // value of String2="beautiful Picture"

            String2 = String1.Replace("beautiful", "Wonderful");

            // value of String2="Wonderful Picture"

          }



StringBuilder object contains a buffer, typically initialized with a string but usually larger than that string. 
This buffer can be manipulated in place without creating a new string: You can insert, append, remove, and replace characters. 
When you're done manipulating the characters, use StringBuilder's ToString method to extract the finished string from it. 



Both String and StringBuilder contain Unicode characters of type Char and support an indexer that returns Char. 


Because the String class is immutable, its indexer is read-only, but the StringBuilder indexer is readable/writeable. 


If you modify the string frequently-in operations like reassigning, appending, removing, and replacing some characters-you should choose the StringBuilder class. 


Whenever you modify a string in the String class, the methods of the String class returns a new string as the result. Creating many String objects might degrade the performance of your program. You can avoid creating a new instance of a string by using the StringBuilder class. 



Some CSHARP Questions Part 2

Explain the difference between a class and a structure

Class:

a. It is reference type.
 
b. Null value can be assigned to a variable in a class
 
c. It can have destructor.
 
d. All variables in classes are by default private.
 
e. Good to be used from architecture view as it provides high flexibility.

Structure:

a. It is value type.
 
b. Null value assignment is not feasible here.
 
c. Cannot have destructor.
 
d. All variables in structures are public.
 
e. Good to be used for simple data structures.




What are virtual, sealed, override, new, and abstract keywords.

The virtual keyword enables a class to be overridden.

If it has to be prevented from being overridden, then the sealed keyword needs to be used.

The override keyword is used to override the virtual method in the base class.

Abstract keyword is used to modify a class, method or property declaration.

You cannot instantiate an abstract class or make calls to an abstract method directly.

An abstract virtual method means that the definition of the method needs to be given in the derived class.


Lets have some examples :

  1. By using virtual and override keywords we can accomplish Method overriding.
  2. The virtual modifier indicates to derived classes that they can override this method.
  3. The override modifier allows a method to override the virtual method of its base class at run-time.
To achieve Run-time polymorphism or Late Binding, we are using Method Overriding concept.

using System;

using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication3
{
    class baseclass
    {
        public virtual int Add(int a, int b)
        {
            return a + b;
        }
    }
    class subclass : baseclass
    {
        public override int Add(int x, int y)
        {
            int d = 20;
            return base.Add(x,y)+d;
        }
    }
    class subclass2 : baseclass
    {
        public int Add(int x, int y)
        {
            int d = 40;
            return base.Add(x, y) + d;
        }
    }
    class something
    {
        public static void Main(String[] args)

        {
            baseclass baseclsinst = new baseclass();
            Console.WriteLine("Base class Addition::::::::::::" + baseclsinst.Add(23, 23));
            baseclass bscls = new subclass();
            Console.WriteLine("Derived class addition:::::::::" + bscls.Add(34, 54));
            baseclass bscls2 = new subclass2();
            Console.WriteLine("Derived class addition:::::::::" + bscls2.Add(34, 54));
            Console.ReadLine();
        }
    }
}


 
Sealed class is used to define the inheritance level of a class.
 
The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. 

.  A class, which restricts inheritance for security reason is declared, sealed class.
2.  Sealed class is the last class in the hierarchy.
3.  Sealed class can be a derived class but can't be a base class.
4.  A sealed class cannot also be an abstract class. Because abstract class has to provide functionality and here we are restricting it to inherit.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace sealed_class
{
    class Program
    {
        public sealed class BaseClass
        {
            public void Display()
        {
            Console.WriteLine("This is a sealed class which can;t be further inherited");
        }
    }
 
        public class Derived : BaseClass
        {
            // this Derived class can;t inherit BaseClass because it is sealed
        }
   
        static void Main(string[] args)
        {
            BaseClass obj = new BaseClass();
 
            obj.Display();
 
            Console.ReadLine();
        }
    }
}


Sealed method is used to define the overriding level of a virtual method.
 
Sealed keyword is always used with override keyword

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace sealed_method
{
    class Program
    {
        public class BaseClass
        {
           
            public virtual void Display()
            {
                Console.WriteLine("Virtual method");
            }
        }
 
       public class DerivedClass : BaseClass
        {
            // Now the display method have been sealed and can;t be overridden
            public override sealed void Display()
            {
                Console.WriteLine("Sealed method");
            }
        }
 
       //public class ThirdClass : DerivedClass
       //{
 
       //    public override void Display()
       //    {
       //        Console.WriteLine("Here we try again to override display method which is not possible and will give error");
       //    }
       //}
 
        static void Main(string[] args)
        {
 
            DerivedClass ob1 = new DerivedClass();
            ob1.Display();
 
            Console.ReadLine();
        }
    }
}


'abstract' modifier before a class indicates that the class is incomplete and intended to be used only as base class and must be implemented in derived class 

 it cannot be instantiated 

it may contain abstract methods

'Abstract' modifier before a method indicates that the method (or property) does not have implementation

it's implicitly a virtual method

The implementation is provided in the overriding method




Difference between Abstract Method & Virtual Method

A virtual method must have its implementation in the base class and may optionally be overriden in the derived class if some additional functionality is required WHEREAS, Abstract Method has no implementation in the base class; it is implemented by the overriding method in the derived class.

In other words, Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method. 




Now lets come to overriding and new:



A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses
    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Foo() { Console.WriteLine("A::Foo()"); }
        }
        class B : A {}         class Test
        {
            static void Main(string[] args)
            {
                A a = new A();
                a.Foo();  // output --> "A::Foo()"
                B b = new B();
                b.Foo();  // output --> "A::Foo()"
            }
        }
    }
The method Foo() can be overridden in classes B and C:
    using System;
    namespace Polymorphism
    {
        class A
        {
              public void Foo() { Console.WriteLine("A::Foo()"); }
        }
        class B : A
        {
              public void Foo() { Console.WriteLine("B::Foo()"); }
        }
        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;
                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"
                a = new B();
                a.Foo();  // output --> "A::Foo()"
            }
        }
    }
The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual.  

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.
    using System;
    namespace Polymorphism
    {
        class A
        {
            public virtual void Foo() { Console.WriteLine("A::Foo()"); }
        }
        class B : A
        {
            public override void Foo() { Console.WriteLine("B::Foo()"); }
        }
        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;
                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"
                a = new B();
                a.Foo();  // output --> "B::Foo()"
            }
        }
     }

C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:
    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Foo() { Console.WriteLine("A::Foo()"); }
        }
        class B : A
        {
            public new void Foo() { Console.WriteLine("B::Foo()"); }
        }
        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;
                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"
                a = new B();
                a.Foo();  // output --> "A::Foo()"
            }
        }
    }
Combining Method Overriding and Hiding

Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
            class A
            {
                public void Foo() {}
            }
            class B : A
            {
                public virtual new void Foo() {}
            }
     
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
            class C : B
            {
                public override void Foo() {}
                // or
                public new void Foo() {}
            }
Only methods in base classes need not override or hide derived methods. All methods in derived classes require to be either defined as new or as override.










Some SHAREPOINT Questions Part 3


What are the security improvements in SharePoint 2010

In SharePoint 2010 a variety of security methods have been introduced.

Claims-Based Authentication - Claims based authentication is based on identity. and trust.

Code Access Security - in which you can specify your own code access
security (CAS) policy for your web parts.

Sandbox Solutions - Sandbox Solutions which when deployed to the server, SharePoint runs in a special process that has limited permissions.

Cross-Site Scripting - Introduced to prevent Cross - Site Scripting (XSS) attacks.


What are SharePoint Sandboxed soultions

SharePoint 2010 provides a new sandboxed environment that enables you to run user solutions without affecting the rest of the SharePoint farm. This environment means that users can upload their own custom solutions without requiring intervention from administrators, and without putting the rest of the farm at risk. This means that the existing sites\pages or components will not be effected by the newly added soultion.



What Changes are made in SharePoint 2010 to enforce Referential Integrity

In SharePoint 2010, Referential Integrity is enforced using two options, available with Look-up columns.
While creating a Look-up column, you can either choose:
a) Restrict Delete or
 b) Cascade Delete 

to define a relationship between the Look-up list and the list containing the look-up Column.





What Has Changed with SSP in SharePoint 2010

In SharePoint 2010 Shared Service Providers (SSP's) are replaced by Service Applications. 

Services are no longer combined into a SSP. They are running independent as a service application. 

The service application architecture is now also built into Microsoft SharePoint Foundation 2010, in contrast to the Shared Services Provider (SSP) architecture that was only part of Office SharePoint Server 2007and not wss.

A key benefit here is that all services are installed by default and there is no SSP setup.









Some SHAREPOINT Questions Part 2



What is the difference between System.Web.UI.WebControls.WebParts.WebPart and Microsoft.SharePoint.WebPartPages.WebPart?

Microsoft.SharePoint.WebPartPages.WebPart is provided in MOSS 2007 to provide backwards compatability with MOSS 2003 webparts. In MOSS 2007, it is recommended to use System.Web.UI.WebControls.WebParts.WebPart instead. 




 When running with SPSecurity.RunWithElevatedPrivileges (web context) what credentials are being used?

 The App Pool Identity for the web application running SharePoint.




Difference between SharePoint List and document library

  • In to a document library we can upload document which get stored in Content database.

  • A list on the other hand a just piece of data, just like SQL table although it is possible  to store binary content in to list as well as using attachment.

  •  With a document library we can use SPFileCollection.add(string, stream) – Document Library Accept a stream, means the content can be in memory, or disk or even a TCP/IP socket. But with List we Can only use SPAttachmentCollection.Add(string, byte) only accepting a byte , means the attachment must fit entirely in one continuous block memory. If this is something you do with large file , your server memory may become fragmente

  • We Can Publish a Infopath Form Template in document Library, and this problem is rise when we submit the Form in different place then where you published the form. 

  • We can’t create Folder in List but can in Doc. Library 

  •  Document library has the Check in Check out functionality but not in List. 

  • Document library support the Major and Minor Version of files and Folders. But in List only support the Major version. So that two people cannot change the same content at concurrently. 

  • Some type of list have different functions like for instance people being only able to read their own posts, but these are not available in every type of list and are not available at all with document libraries and other libraries. 

List have one special List Content type, same as list Library has also DocumentLibaray type content type.

 

 

 

When modifying a list item, what is the "main" difference between using SPListItem.Update() and SPListItem.SystemUpdate()

Using SystemUpdate() will not create a new version and will also retain timestamps.

 


Some SHAREPOINT Questions Part 1

How does SharePoint store pages?

SharePoint does not store the pages directly in the filesystem. The mechanism is a little less straightforward.

To understand this mechanism, You have to understand the concepts of Ghosting/Unghosting, and the ASP.NET Virtual Path Provider. 

The SharePoint stores the pages in the Database as BLOBS, and serves them up using the ASP.NET Virtual path provider.

The ASP.NET Virtual Path Provider provides an abstraction between ASP.NET and FileSystem. 
Instead of getting a System.IO.FileStream object directly from the filesystem, the provider uses MapPathBasedVirtualPathProvider and the MapPathBasedVirtualFile classes to get the FileStream object.

This abstraction allows ASP.NET to serve up pages from anywhere, without having to store the pages in an actual file system. This concept is used to implement Ghosting/Unghosting which basically means having a single copy of the page, and serving them up as different pages.

SharePoint leverages this new feature in ASP.NET 2.0, along with the improved BLOB storage functionality in SQL Server 2005 to serve up pages.





What are SharePoint Ghosted and Unghosted Pages

Each .aspx page is rendered by one of two possible parsers. When a request is received for an .aspx page, the SharePoint isapi filter determines who will handle the rendering of the page—Asp.net orthe SharePoint SafeMode parser. The first parser, Asp.net, requires the least amount of introduction. The second parser is unique to Windows SharePoint Services.
As everyone knows, all pages within SharePoint are stored in the database. This effectively means that for each document, you will find a row in the docs table for that document. The actual file is stored in the Content column. This is true for all files. However, there is one exception - some .aspx pages don't actually have their content stored in the database. Instead, these pages reference files which exist on the server's file system. These pages are considered ghosted pages.

 From a technical standpoint, ghosted pages are those rows in the docs table which have null values for the Content column and a non-null value for the SetupPath column which points to a file on the file system itself. The referenced file essentially serves as a template and content source.

What pages are ghosted? For example, the default home page is a ghosted page. Any web part pages created via New Web Part Page user interface also ghosted.

What does it mean if a document doesn't reference a template on the file system? Or, more to the point, the Content column actually contains data? These pages are known as unghosted .aspx pages and they are routed through the SafeMode parser.




 
 What is the main difference between the SafeMode parser and Asp.net?

As everyone knows, Asp.net will parse a page on first render and compile it into an assembly. The SafeMode parser does NOT compile pages. It is designed to interpretatively parse a page and create the object structure of the page. In the event inline server-side code is detected, the SafeMode parser will not allow the page to render. Additionally, the only objects within the page (i.e. controls marked as runat=server) which can be instantiated are those items found in the SafeControls list.




 Can a page transition from a ghosted state to unghosted?

 Yes, Ghosted pages become unghosted once a file has been modified. If a page is updated using FrontPage 2003, web folders, or the modification of custom document library fields, the Content column of the given document row is populated with the page contents. All uploaded .aspx files are automatically unghosted.



Some ASP.NET Questions Part 1

What’s the difference between Response.Write() and Response.Output.Write()



 In ASP.NET the Response object is of type HttpResponse and when you say 'Response.Write', you're really saying (basically) HttpContext.Current.Response.Write and calling one of the many overloaded Write methods of HttpResponse. 

Response.Write then calls .Write() on it's internal TextWriter object:

public void Write(object obj){ this._writer.Write(obj);} 

HttpResponse also has a Property called Output that is of type, yes, TextWriter, so:

public TextWriter get_Output(){ return this._writer; } 

Which means you can to the Response whatever a TextWriter will let you.  Now, TextWriters support a Write() method ala String.Format, so you can do this:

Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);
But internally, of course, this is happening:

public virtual void Write(string format, params object[] arg)
{
   this.Write(string.Format(format, arg));
}


Some CSHARP Questions Part 1





What is the difference between const and readonly


When using the const keyword to set a constant variable, the value needs to be set at compile time.

The const keyword may not be used with an object of reference type. 
All the constant variables are static ie they are shared across all the instances of the class. You dont have to add the keyword "static".

In case a reference type needs to be assigned a non-changeable value, it may be set as readonly

Readonly fields are delayed initalized constants. 

When we declare a field as const it is treated as a static field. where as the Readonly fields
are treated as normal class variables.

if we want a field that can have different values between different objects of same class, however
the value of the field should not change for the life span of object; We should choose the Read
Only fields rather than constants.Since the constants have the same value across all the
objects of the same class; they are treated as static.


What are value types and reference types


When you declare a variable in a .Net application, it allocates some chunk of memory into the RAM. 

This memory has 3 things first the name of the variable, second data type of the variable and finally the value of the variable.

Depending on what kind of data type your variable is, the memory is allocated to it. 

There are two types of memory allocation stack memory and heap memory. 

Value types are types which hold both data and the memory on the same location. 

While a reference type has a pointer which points to the memory location.

Below is a simple integer data type with name 'i' whose value is assigned to an other integer data type with name 'j'.

Both these memory values are allocated on the stack.

When we assign the 'int' value to the other 'int' value it creates a complete different copy. In other word if you change either of them the other does not change. These kinds of data types are called as 'Value types'.

public void method()
{
    int i = 9;
    int j=i;
}

When we create an object and when we assign one object to the other object, they both point to the same memory location as show in the below code snippet. 

So when we assign 'obj' to 'obj1' they both point to the same memory location.

In other words if we change one of them the other object is also affected this is termed as 'Reference types'.


public void method()
{
     Class1 obj = new Class1();
     Class1 obj1 = obj;
}
 In .NET depending on data types the variable is either assigned on the stack or on the heap. 
'String' and 'Objects' are reference types and any other .NET primitive data types are assigned on the stack. 







What is boxing and unboxing

Boxing is used to store value types in the garbage-collected heap. 

Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. 

Boxing a value type allocates an object instance on the heap and copies the value into the new object.

Consider the following declaration of a value-type variable:

 int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

// Boxing copies the value of i into object o.
object o = i;

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable.


Consider follwing C# code:

class TestBoxing
{
    static void Main()
    {
        int i = 123;

        // Boxing copies the value of i into object o.
        object o = i; 

        // Change the value of i.
        i = 456; 

        // The change in i does not effect the value stored in o.
        System.Console.WriteLine("The value-type value = {0}", i);
        System.Console.WriteLine("The object-type value = {0}", o);
    }
}
/* Output:
    The value-type value = 456
    The object-type value = 123
*/

Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface.

An unboxing operation consists of:
Checking the object instance to make sure that it is a boxed value of the given value type.

Copying the value from the instance into the value-type variable.

int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;   // unboxing