Friday, January 31, 2014

Application Object

Application object is used to store the information and access variables from any page in application. Application object is same as session object only the difference is session object is used to maintain the session for particular user while application object store the information for application same for all users i.e. If one user enters into the application then session id will create for that particular user if he leaves from the application then the session id will deleted. If they again enter into the application they will get different session id but application object is same for all users once application object is created that application object is used throughout the application regardless of user. The information stored in application object accessed throughout all the pages in application (like database connection information) and we can change the application object in one place those changes automatically reflected in all the pages.
You can create application objects in Global.asax file and access those variables throughout the application.
Application object remain in memory until the web server shut down or the web.config site configuration has changed.

Wednesday, January 29, 2014

Difference Between Serialization And Marshaling

  Difference Between Serialization And Marshaling

Serialization

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file, a memory buffer, or transmitted across a network connection to be "resurrected" later in the same or another computer environment. And this sequence of bits can be of any format the user chooses; however, they are usually formed as XML or binary.
Serialization comes in many forms in .NET Framework, it can be observed in ADO.NET, Web services, WCF services, Remoting, and others.
For example, calling the WriteXml() function of a DataSet serializes this DataSet into a XML file.


ds.WriteXml("data.xml");


And if we have such this structure:


1
public struct User


2
{


3
   public int id;


4
   public string name;


5
}


we can get the following results if we serialize a collection of that structure into XML:ers>


01


02


03


04
   


05
       12


06
       Mark


07
   


08
   


09
       13


10
       Charles


11
   


12
   


13
       14


14
       John


15
   


16


Serialization can be observed in Web and WCF services too. The request and parameter information for a function are serialized into XML, and when the function returns the response and the returned data too are serialized into XML. Actually, you don't have to think about these XML data, CLR handles this for you.
In the same vein, when it comes to Remoting, the sender and recipient must agree to the same form of XML data. That's, when you send some data CLR serializes this data for you before it sends it to the target process. When the target process receives this XML data, it turns it back (deserializes it) to its original form to be able to handle it.
Thus, the process of converting data structures and objects into series of bits is called Serialization. The reverse of this process, converting these bits back to the original data structures and objects, is called Deserialization.
Therefore, the following ADO.NET line does deserializes the XML file:


1
DataSet ds;


2
ds.ReadXml("data.xml");


And when your application receives response from the server or from another process, the CLR deserializes that XML data for you.
So why XML is preferred over binary serialization? That's because XML is text-based. Thus, it's free to be transmitted from a process to another or via a network connection, and firewalls always allow it.

Marshaling

Marshaling is the process of converting managed data types to unmanaged data types. There are big differences between the managed and unmanaged environments. One of those differences is that data types of one environment is not available (and not acceptable) in the other.
For example, you can't call a function like SetWindowText() -that sets the text of a given window- with a System.String because this function accepts LPCTSTR and not System.String. In addition, you can't interpret (handle) the return type, BOOl, of the same function, that's because your managed environment (or C# because of the context of this writing) doesn't have a BOOL, however, it has a System.Boolean.
To be able to interact with the other environment, you will need to not to change the type format, but to change its name.
For example, a System.String is a series of characters, and a LPCTSTR is a series of characters too! Why not just changing the name of the data type and pass it to the other environment?
Consider the following situation. You have a System.String that contains the value "Hello":


System.String str = "Hello";


The same data can be represented in an array of System.Char too, like the following line:


System.Char[] ch = str.ToCharArray();


So, what is the difference between that System.String variable and that System.Char array? Nothing. Both contain the same data, and that data is laid-out the same way in both variables. That's what Marshaling means.
So what is the difference between Serialization and Marshaling?
C# has a System.Int32, and Windows API has an INT, and both refer to a 32-bit signed integer (on 32-bit machines.) When you marshal the System.Int32 to INT, you just change its type name, you don't change its contents, or lay it in another way (usually.) When you serialize a System.Int32, you convert it to another form (XML for instance,) so it's completely changed.

Summary

I mean that, Marshaling is a very general term used to describe transformations of memory. Theoretically, it's more general than Serialization. In Python for instance, the terms Marshaling and Serialization are used interchangeably. There (in Python,) Marshaling = Serialization, and Serialization = Marshaling, there's no difference. In computer methodology, there's a silent difference between Marshaling and Serialization (check the Wikipedia definition.)
So what is that System.MarshalByRefObject class? Why that name -specifically- was used? First, System.MarshalByRefObject class allows objects to be passed by reference rather than by value in applications that use Remoting.
Personally, I like to say that Microsoft .NET Framework team's name was very scientific when they have called that object "MarshalByRefObject" with respect to that silent difference between serialization and marshaling or maybe that name was derived from Python, dunno!
After all, we should keep in mind that in .NET methodology, there's a big difference between Serialization and Marshaling, Marshaling usually refers to the Interop Marshaling. In .NET Remoting, it refers to that serialization process.
By the way, Marshalling is so named because it was first studied in 1962 by Edward Waite Marshall, then with the General Electric corporation.

Friday, January 24, 2014

Remove Duplicate Rows

Create a table with duplicate values

CREATE TABLE testdup(Col1 INT, Col2 INT)
INSERT INTO testdup
SELECT 1, 1
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 1 --duplicate
UNION ALL
SELECT 1, 2
UNION ALL
SELECT 1, 2 --duplicate
UNION ALL
SELECT 1, 3
UNION ALL
SELECT 1, 4

How to select unique rows

Select Col1,Col2 from testdup group by col1, col2

Select distinct * from testdup


Delete Duplicate Rows

With CTE (Col1,Col2, RowNum)
As
(
 Select Col1,Col2, Row_Number() over (partition by col1,col2 order by col1,col2) as RowNum from testdup
)
Delete From CTE where RowNum>1


Get only duplicate rows(one row for each set)

Select Col1,Col2 from testdup group by col1, col2 Having count(*)>1

If table has an Identity column than it is an easy way to delete duplicate rows

Get Duplicate Rows

Select * from testdup where autoid not in ( select min(autoid) from testdup group by col1,col2)

Get Unique Rows

Select * from testdup where autoid in ( select min(autoid) from testdup group by col1,col2)

Delete Duplicate Rows

Delete from testdup where autoid not in ( select min(autoid) from testdup group by col1,col2)

Download the entire script from here

RemoveDuplicateRows


Private Constructor

1. One use of private construct is when we have only static member.
2. It provide implementation of singleton class pattern
3. Once we provide constructor (private/public/any) the compiler will not add the no parameter public constructor to any class.
4. If we still want to make object of the class having private constructor. We can have a set of public constructor along with the private constructor.

Difference Between import(using) and extends(implement)

Importing a class, makes you to use that class without needing to mention the full name in the current class you are writing.

import java.util.Scanner
// now you can use the Scanner class in your code:
Scanner stdin = new Scanner(System.in);
//instead of having to do
java.util.Scanner stdin = new java.util.Scanner(System.in);


Extending a class is creating a new class that is a subclass of some other class. This will allow you to add or change functionality of the class you are extending.

// this is a very contrived example
public class EmptyList extends ArrayList {
@Override
public boolean add(Object o){
return false; // will not add things to a list
}
}


We used extend in order to use the polymorphism feature. When we extending a class we can access the class data member & functions(methods) but by import a class we can access the class and we can't use members and methods of the class without creating instant for that class.

In UML conventions extending satisfies IS A relationship where just importing satisfies only use / Has A relationship.

Friday, January 17, 2014

Session in WebService

Usually, when you think of a Web Service, you think …make the call, get the response, and get on with the task at hand. These "one shot" calls are the norm in Web Services but there may be times when you need a little more. You may need the Web Service to remember states between calls.

Example :

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;

namespace DemoWebService
{
    [WebService(Namespace = "http://AcmeWidgets.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class MyDemo : System.Web.Services.WebService
    {
        [WebMethod (EnableSession = true)]
        public string HelloWorld()
        {
            // get the Count out of Session State
            int? Count = (int?)Session["Count"];

            if (Count == null)
                Count = 0;

            // increment and store the count
            Count++;
            Session["Count"] = Count;

            return "Hello World - Call Number: " + Count.ToString();
        }
    }
}

We need EnableSession = true attribute to use Session in Web Service.







How To Call it From Client :

protected void Button1_Click(object sender, EventArgs e)
{
    localhost.MyDemo MyService;

    // try to get the proxy from Session state
    MyService = Session["MyService"] as localhost.MyDemo;

    if (MyService == null)
    {
        // create the proxy
        MyService = new localhost.MyDemo();

        // create a container for the SessionID cookie
        MyService.CookieContainer = new CookieContainer();

        // store it in Session for next usage
        Session["MyService"] = MyService;
    }

    // call the Web Service function
    Label1.Text += MyService.HelloWorld() + "
";
}

Output :
Hello World - Call Number: 1
Hello World - Call Number: 2
Hello World - Call Number: 3

Need to store the Service Object in Session Otherwise it will create a new object for each click. And output will be like this.

Hello World - Call Number: 1
Hello World - Call Number: 1
Hello World - Call Number: 1

Because session id will be different each time. You also need to create Container for SessionID.

In a Windows Forms application this is easy. Make the proxy global or static…just don't put it on the stack. For a Web Application it's a bit trickier, we put the proxy into the Session collection.

Search a Control using Key

  GroupBox objGrpBox = null;
           String sGroupBoxName = "GroupBox";


           
               if (SplitContnerEpub.Panel1.Controls.ContainsKey(sGroupBoxName))
               {
                   objGrpBox = SplitContnerEpub.Panel1.Controls[sGroupBoxName] as GroupBox;
                   objGrpBox.Controls.Clear();
               }
               else
                   objGrpBox = new GroupBox();
                           
               objGrpBox.Name = sGroupBoxName;


Saturday, January 11, 2014

Interview-Acc

1. Code Optimization technique
2. nunit Testing
3. Mocking in nunit Testing
4. What is script descriptor?
5. Reflection.
6. foreach is fast in which scenario.
7. Type of Serialization
8. Why we create App Domain tell me any real scenario.

Friday, January 10, 2014

Why Java/.Net does not support multiple Inheritance

The reasons for omitting multiple inheritance from the Java /.Net is  Simplicity of Language. To avoid complexity they have omitted the concept of Multiple Inheritance.

or instance, we can consider diamond problem of multiple inheritance.

We have two classes B and C inheriting from A. Assume that B and C are overriding an inherited method named ‘foo’ and they provide their own implementation. Now D inherits from both B and C doing multiple inheritance. D should inherit that overridden method, which overridden method will be used? Will it be from B or C? Here we have an ambiguity.
In C++ there is a possibility to get into this trap though it provides alternates to solve this. In java this can never occur as there is no multiple inheritance. Dynamic loading of classes makes the implementation of multiple inheritance difficult.

Multiple Inheritance is allowed for interfaces because the interface doesn’t implement the function. The function is always implemented by the class. So, in the above case, A,B and C will be interfaces, and D will implement foo. main knows which function to call because there's only one foo.

How C++ solve this problem?

class A                     { public: void eat(){ cout<<"A";} };
class B: virtual public A   { public: void eat(){ cout<<"B";} };
class C: virtual public A   { public: void eat(){ cout<<"C";} };
class D: public         B,C { public: void eat(){ cout<<"D";} };

int main(){
    A *a = new D();
    a->eat();
}

If we will not use virtual C++ compiler will give an error on compile time “Member is ambiguous:
…..”. After using virtual keyword it ensures that only one copy of super class(A) method will remain in Child class (D).

And Java/.Net  doesn’t support virtual keyword in inheritance chain.


Interview Questions-Answers IG - 8

1) What is Json?
Answer : JSON stands for Java Script Object Notation, it is a text based format, It contains the values in key-value pair.

2) Why we use Json?
Answer : We use the JSON to store the values in key-value pair.

3) Joins - Left Outer, Right Outer, Full Outer, Inner Join?
Answer : In left Outer - All matching rows + all no matching left table rows
Right Outer Join - All matching rows + all non matching right table rows
Full Outer Join- All matching rows + all non matching left table rows + all non matching right table rows

4) Why we use static method?
Answer : To use the common value in whole application.
Static methods are conceptually the same as static variables, thus the reasons to use or not use them are similar. They belong to the class, not specific objects of that class. If a method perform a same task irrespective of object than that method should be declared as static.

In a class Car you might have a method double convertMpgToKpl(double mpg) which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But void setMileage(double mpg) (which sets the efficiency of one particular Car) can't be static since it's inconceivable to call the method before any Car has been constructed.

5) Give me real example where you use static method.
Answer : in Singleton Pattern

6) If we have a table in which thousands of record inserting,deleting and updating daily. Which type of index you will use there.
Answer : Non Clustered Index. Since in case of clustered index table reorder for each insert,update or delete.

7)Any critical job/work that you have done so far?

8) Difference between clustered and nonclustered index.
Answer : In clustered Index leaf node contains the row itself while in case of non clustered index leaf node contains the pointer of the row.

9) What is identity?
 Answer : Indentity  is a column whose value auto generated.
Syntax to get Identity : IDENT_CURRENT('table_name')

10) What is scope_identity?
Answer : Scope_Identity used to get the last identity values use by function of procedure.
Syntax : Scope_Identity()

11) Is it make sense that we define clustered index on primary key column.
Answer : No

Beacause a Clustered Index is automatically created on the table when we create a PRIMARY KEY constraint if it is not created already.

12) Can we define clustered index on composite column?
Answer : Yes, you can create.
However, from a performance view you should avoid composite clustered indexes. Generally speaking, the leaner index, the faster SQL Server can scan or seek through it. For small tables (or data sets) composite indexes perform relatively well, but as number of records grows, performance decreases.

Thursday, January 9, 2014

Polymorphism, Method Hiding and Overriding in C#

  

Overview
One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning "having multiple forms") in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow a variable to refer to more than one type of object.
Example Class Hierarchy
Let's assume the following simple class hierarchy with classes AB and C for the discussions in this text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the easier examples, we will only refer to a part of this class hierarchy.
Inherited Methods
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()"
            }
        }
    }
     
There are two problems with this code.
  • The output is not really what we, say from Java, expected. 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. An example using virtual methods and polymorphism will be given in the next section.
  • Although the code compiles and runs, the compiler produces a warning:
...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'
This issue will be discussed in section Hiding and Overriding Methods.
Virtual and Overridden Methods
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()"
            }
        }
     }
Method Hiding
Why did the compiler in the second listing generate a warning? Because 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() {}
            }
Conclusion
  • C# is not Java.
  • 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.
  • Know what your doing and look out for compiler warnings.

Remoting

  1. Describe in detail Basic of SAO architecture of Remoting?
  2. Remoting has at least three sections :
    • Common Interface which will be shared between them.
    • Server.
    • Client.
  3. Here is an explanation of the process:
    • First important section is the common interface between Server and Client. For sample project interface
    • is very simple with only two methods : SetValue and GetValue.
    • Public Interface InterFaceRemoting
    • Sub SetValue(ByVal value As String)
    • Function GetValue() As String
    • End Interface
    • Second important section is the server. In this sample server is using HTTP channel and the server object is singleton.
    • Imports System
    • Imports System.Runtime.Remoting
    • Imports System.Runtime.Remoting.Channels.Http
    • Imports System.Runtime.Remoting.Channels
    • Imports InterFaceRemoting
    • Public Class RemotingServer Inherits MarshalByRefObject
    • Implements InterFaceRemoting.InterFaceRemoting
    • Private strData As String
    • Public Function GetValue() As String Implements
    • InterFaceRemoting.InterFaceRemoting.GetValue
    • Return strData
    • End Function
    • Sub New()
    • strData = "testing.."
    • End Sub
    • Public Sub SetValue(ByVal value As String) Implements
    • InterFaceRemoting.InterFaceRemoting.SetValue
    • strData = value
    • End Sub
    • End Class
    • Module ModuleRemotingStartUp
    • Sub Main()
    • Dim objHttpChannel As HttpChannel
    • Console.WriteLine("Server Started...")
    • objHttpChannel = New HttpChannel(1234)
    • ChannelServices.RegisterChannel(objHttpChannel)
    • RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingServer),
    • "RemoteObject", WellKnownObjectMode.Singleton)
    • Console.WriteLine("Server registered and listening waiting for clients...")
    • Console.ReadLine()
    • End Sub
    • End Module
    • In the code above, Channel object is created and registered. Server then hosts the object so that client can connect to it. This is the time when we specify what mode the server object will be created i.e. Singleton or SingleCall. This is done by the following below given code. Note in sample we are hosting the server object in singleton mode that means that the same object
    • will be shared between all clients. Also note the server object is implementing "InterFaceRemoting" and inheriting from "MarshalByRefObject".
    • RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingServer),
    • "RemoteObject", WellKnownObjectMode.Singleton)
    • In the last section the client will connect to this hosted remoting object.
    • Imports System
    • Imports System.Runtime.Remoting
    • Imports System.Runtime.Remoting.Channels.Http
    • Imports System.Runtime.Remoting.Channels
    • Imports InterFaceRemoting
    • Module ModuleStartClient
    • Sub Main()
    • Dim objHttpChannel As New HttpChannel
    • Dim objRemoting As InterFaceRemoting.InterFaceRemoting
    • ChannelServices.RegisterChannel(objHttpChannel)
    • objRemoting =
    • CType(Activator.GetObject(GetType(InterFaceRemoting.InterFaceRemoting),
    • "http://localhost:1234/RemoteObject"),
    • InterFaceRemoting.InterFaceRemoting)
    • Console.WriteLine("Referenced the main object.... Now displaying Data")
    • Console.WriteLine("Value on server :- " & objRemoting.GetValue.ToString())
    • Console.WriteLine("Press enter to Terminate")
    • Console.ReadLine()
    • End Sub
    • End Module
    • Finally you need to run server and then client.

Followers

Link