Mar 07

Some interview questions

ASP.Net | General | Tips and Tricks | Visual Studio 121 Comments »

Currently rated 3.0 by 5 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Today I was surfing on the blog of Sheikh Ahmad and I saw some interview questions related to .Net. I will try to give answers of some of the questions.

Here is a question from his blog:

How can we get the variables of first form from second form without using query string and session etc?

Answer:

In these kinds of questions the interviewrs are actually try to detrmine that how much do you know about the .Net 2.0. It is very simple to get any control of the Page by using the this keyword or just from the ID of the control like

lbltest.Text = "hello";

But now the critical part of the question is that how to get the variables of first form from second form without using query string or session etc. This question itself suggests that we can access variable of one form from another using the query string or session etc but the interviewers has asked you not to use this approach.

What if I ecounter this problem in my work life? To solve this I will try to use an approach in which I can get the instance of the first page in the second page. Now the problem is that how to pass the instance of the first page in the second page without using query string or session etc. The answer is Cross Page posting which is a new feature of .Net 2.0. By default Controls like button , image button of ASP.Net post back to same page. If you want to post back to some other page instead of the current page then you can set the postbackUrl of these controls (i.e. Buttons,LinkButton,Image buttons). This is called the Cross Page posting and it is the feature of the .net 2.0. By using this appraoch you can navigate to the second page and in that second page you can access the first page too.

Suppose you have two pages page1.aspx and page2.aspx. In page1.aspx you have a button and a lable. Set the PostbackUrl of the button to page2.aspx and in the page2.aspx use previouse page property to get the previouse page's instance like this:

Page source = this.PreviousePage.

By using this approach you able to get the instance of the first page in the second page without using the Session or Query string. Now you can use this instance to get the variables, View state etc of the first page. 

 

Question: What are collections and why we use them?

Answer: Simply speaking Collection is a container which is used to hold the objects.

The second part of the question is that why we use them?

Well in programming we write differnt kinds of classes then we declare the objects of those classes. Those objects perform differnt functions and communicate with each other too and after performing their action they give output to some other kind of objects. So we use the container or collection to hold these objects. 

The question arise that what is the need of this container in the presense of the array? The answer is that array can not be used to hold differnt kinds of objects. Secondly we need to set the length of the array when we declare it but this is not the case with collection. The size of collection is dynamic. You just need to declare the collection and that is it. In collection you do not need to know that how many and what types of objects you are going to hold in collection.

Like other programming language C# has differnt kinds of container or collections i.e.

  • Stack
  • Queues
  • Hashtable
  • ArrayList 

Actually what ever you add in a collection becomes an object. It is said that every thing in .Net is an object, so what ever you add in a collection becomes object thus loosing its identity because in collection they are now in the form of object. The conversion of types into object is done by the .Net itself and it is called the Boxing. And this conversion of types to object is also called upcasting and it is always safe. Why it is always safe? Because you are converting the types into their super class (i.e. object of your class into System.Object) and we know that every thing in .net is derived from Object so this conversion will be safe always. Now when we get back our data from the collection it will be in the form of Object instead of the form in which we have added it in the collection. So when we get the data back from the collection then we have to cast it back into its orignal type. The conversion of the object into some specific type is called unboxing. Unboxing is also called downcasting. Downcasting should be done carefully because if you try to cast it into some wrong type then you will get the error. e.g. Casting the Circle into rectangle is wrong. So downcasting should be done carefully. Upcasting is done by the .Net itself and can be done programmatically but it is not dangeriouse while downcasting could be dangerious if not done properly.

That can be explained like "Circle and rectangle are always shape but it is not necessary that Shape is always a circle or rectangle"

Question: Shellow Copy vs Deep Copy?

I already wrote an article that how to impliment Shallow copy in .Net. Here is the Link of that article. It might help you.

http://www.shahidriaz.com/post/2008/12/07/ShallowCopy.aspx

 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: ,

Dec 07

How to Implement Shallow copy in .Net

C# | General | Tips and Tricks | Visual Studio 106 Comments »

Currently rated 3.3 by 6 people

  • Currently 3.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

 

Hi,

Few days back I was trying to implement an algoritm. During the implementation I was interested to create a shallow copy of my class. In shallow copy the change in your cloned class will also reflect in the main object too. Shallow copy is the easiest way to clone your class. If you want that your class can be cloned then you can implement an interface called ICloneable.

Here I am giving a small example showing how to implement ICloneable interface. ICloneable interface expose only one method which is Clone.

Example:

First of all write a class, with two properties, like this:

public class myData
    {
        private string _Name;

        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        private int _Age;

        public int Age
        {
            get { return _Age; }
            set { _Age = value; }
        }

    }

 

In the above code I wrote a class "myData". I declared two member variable which are _Name and _Age respectively. Then I wote two properties against these two member variables which are Name and Age respectively.

Now derive a class from List<T> and also implement IClonabale interface as shown in the following code.

class myCollectionofData<T> : List<T>,ICloneable
    {
        #region ICloneable Members

        public object Clone()
        {
            return this.MemberwiseClone();
        }

        #endregion
    } 

 

In the above code I wrote a small class with the name "myCollectionofData". You can see that this class is implementing the ICloneable interface. As I mentioned earlier that this interface expose only one method which is Clone. I wrote only one line of code in this method which is  "return this.MemberwiseClone();"

According to MSDN MemberwiseClone  method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

Now all we need to do is to check our class. I wrote the following code to test my class:

  class Program
    {
        static void Main(string[] args)
        {
            // Declare the object of the myData class
            myData _myData = new myData();
            _myData.Name = "Shahid Riaz Bhatti";
            _myData.Age = 26;

            myCollectionofData<myData> _myDataCollection = new myCollectionofData<myData>();
            _myDataCollection.Add(_myData);
            foreach (myData data in _myDataCollection)
            {
                Console.WriteLine(data.Name);
                Console.WriteLine(data.Age);
            }
            myCollectionofData<myData> Cloned = (myCollectionofData<myData>)_myDataCollection.Clone();
            foreach (myData data in Cloned)
            {
                Console.WriteLine(data.Name);
                Console.WriteLine(data.Age);
            }
        }
    }

 

In this class I declared the object of myData and set the Name and Age as follow:

 // Declare the object of the myData class
            myData _myData = new myData();
            _myData.Name = "Shahid Riaz Bhatti";
            _myData.Age = 26;

i.e. I set the Name to my name i.e. Shahid Riaz Bhatti :) and Age = 26.

Now I declared the object of myDataCollection class and add records in this object as follow:

              myCollectionofData<myData> _myDataCollection = new myCollectionofData<myData>();
            _myDataCollection.Add(_myData);

Now I Iterated this collection to see those records which we added in this collection. i.e.

   foreach (myData data in _myDataCollection)
            {
                Console.WriteLine(data.Name);
                Console.WriteLine(data.Age);
            }

The above loop will give the following output:

Shahid Riaz Bhatti

26

Upto this point I didn't used the Clone method of my class. Now lets look at the following line of code:

myCollectionofData<myData> Cloned = (myCollectionofData<myData>)_myDataCollection.Clone();

In the above code I used the Clone method to get the cloned copy of my object. i.e.

_myDataCollection.Clone();

This will return me an Object. I unboxed that object into myCollectionofData<myData>. Now I need to check that did I get the copy of my object. For that purpose I Iterated the Cloned object and displayed the Name and Age as follow:

   foreach (myData data in Cloned)
            {
                Console.WriteLine(data.Name);
                Console.WriteLine(data.Age);
            }

This will exactly give me the same output of the main object which is:

Shahid Riaz Bhatti

26

The complete code is given below:

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

namespace ConsoleApplication1
{
    public class myData
    {
        private string _Name;

        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        private int _Age;

        public int Age
        {
            get { return _Age; }
            set { _Age = value; }
        }

    }

    class myCollectionofData<T> : List<T>,ICloneable
    {
        #region ICloneable Members

        public object Clone()
        {
            return this.MemberwiseClone();
        }

        #endregion
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Declare the object of the myData class
            myData _myData = new myData();
            _myData.Name = "Shahid Riaz Bhatti";
            _myData.Age = 26;

            myCollectionofData<myData> _myDataCollection = new myCollectionofData<myData>();
            _myDataCollection.Add(_myData);
            foreach (myData data in _myDataCollection)
            {
                Console.WriteLine(data.Name);
                Console.WriteLine(data.Age);
            }
            myCollectionofData<myData> Cloned = (myCollectionofData<myData>)_myDataCollection.Clone();
            foreach (myData data in Cloned)
            {
                Console.WriteLine(data.Name);
                Console.WriteLine(data.Age);
            }
        }
    }
}

Copy and paste the above code in a C# console application to see the output. If found any error on "using System.Linq;" then remove it coz I wrote this example in VS2008.

If u remembered that In the beginning of this article I stated that in shallow copy the change in your cloned class will also reflect in the main object too. Lets check this one too. For this I made a lil change in the code of the main program which is given below:

myCollectionofData<myData> Cloned = (myCollectionofData<myData>)_myDataCollection.Clone();
            foreach (myData data in Cloned)
            {
                data.Name = "Name is Changed";
                data.Age = "100";
            }

i.e. Instead of displaying the data of the cloned object, I changed it. i.e.

I changed Name to "Name is Changed" and Age from 26 to 100.

Now lets Iterate the main object to see its data as shown below:

foreach (myData data in _myDataCollection)
            {
                Console.WriteLine(data.Name);
                Console.WriteLine(data.Age);
            }

 

Instead of displaying

Shahid Riaz Bhatti

20

It will display:

Name is Changed

100

The modified complete code of class Program is given below:

class Program
    {
        static void Main(string[] args)
        {
            // Declare the object of the myData class
            myData _myData = new myData();
            _myData.Name = "Shahid Riaz Bhatti";
            _myData.Age = 26;

            myCollectionofData<myData> _myDataCollection = new myCollectionofData<myData>();
            _myDataCollection.Add(_myData);
            foreach (myData data in _myDataCollection)
            {
                Console.WriteLine(data.Name);
                Console.WriteLine(data.Age);
            }
            myCollectionofData<myData> Cloned = (myCollectionofData<myData>)_myDataCollection.Clone();
            foreach (myData data in Cloned)
            {
                data.Name = "Name is Changed";
                data.Age = "100";
            }
            foreach (myData data in _myDataCollection)
            {
                Console.WriteLine(data.Name);
                Console.WriteLine(data.Age);
            } 

        }
    }

 Note:

Clone method allows only the Shallow copy and not the deep copy. In shallow copy a change made in cloned object will also be reflected in the main object because in Shallow copy the orignal object and its clone refer to the same object. Deep copy is achieved by using the ISeralizable interface. i.e. First serialize the object, then deserialize back to a complete new copy. Now any changes in the new copy do not reflect on the orignal copy of the object.

kick it on DotNetKicks.com


[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , ,

Oct 15

HTML Encoding

ASP.Net | C# | General | Random Thoughts | Tips and Tricks | Visual Studio 11 Comments »

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
There are certain characters that have a special meaning in HTML. For example, the angle brackets (< >) are always used to create tags. This can cause problems if you actually want to use these characters as part of the content of your web page. For example, imagine you want to display this text on a web page:
Enter a word <here>
If you try to write this information to a page or place it inside a control, you end up with this instead:
Enter a word
The problem is that the browser has tried to interpret the <here> as an HTML tag. A similar problem occurs if you actually use valid HTML tags. For example, consider this text:
To bold text use the <b> tag.
Not only will the text <b> not appear, but the browser will interpret it as an instruction to make the text that follows bold. To overcome this automatic behavior, you need to convert potential problematic values to their HTML equivalents. For example, < becomes &lt; in your final HTML page, which the browser displays as the < character.
The following table lists some special characters that need to be encoded.
 
Result Description Encoding
  Non breaking space
&nbsp;
<
Less-than symbol
&lt
>
Greate-than symbol &gt
&
Ampersand

&amp

"
Quotation mark
&quote
 
Alternate solution:

  This problem can also be solved in another way i.e. by using the innerText property of the server control. InnerText property automatically converts any illegal characters into their HTML equivalent. However, this won’t help if you want to set a tag that contains a mix of embedded HTML tags and encoded characters. It also won’t be of any use for controls that don’t provide an InnerText property, such as the Label web control . In these cases, we can use the HttpServerUtility.HtmlEncode() method to replace the special characters. (Remember, an HttpServerUtility object is provided through the Page.Server property.)

 
 
Here’s an example:
// Will output as "Enter a word &lt;here&gt;" in the HTML file, but the
// browser will display it as "Enter a word <here>".

ctrl.InnerHtml = Server.HtmlEncode("Enter a word <here>");
// Or consider this example, which mingles real HTML tags with text that needs to be
// encoded:
ctrl.InnerHtml = "To <b>bold</b> text use the ";
ctrl.InnerHtml += Server.HtmlEncode("<b>") + " tag.";

 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , , ,

Oct 10

In this article I will cover some basic things which we encountered in our daily programming tasks. These tasks includes how to find values from IList. This kind of tasks are extremely easy. We know that in programming we finish a tasks by using different techniques. e.g. We can write a simple program which inserts, update and delete some record from the database. This application sounds very simple and it is a simple but different approaches can be adopted to complete this tasks. Like we can adopt layered architecture, can adopt any design patterns depending on the nature of the application or we can violate all these rules. Application development is not a big tasks but how the application is developed is important.

Today I am going to discuss that how can we play with IList in C#. Basically I am a C# developer andhaving background of VC++, so I am comfortable by giving the C# example, but any VB.Net developer can also take benifit from these example.

A common task in our daily programming is searching. Different developers used different ways for searching.

Suppose I have a string collection and I want to fing a particular item from that string collection. Now how can we achieve this tasks? The simple answer is that iterate through the string collection to find the required entry. That is right but does it mean that we dont have any other option.. The good news is that we have some other options too which are given below:

  • Loop (Not a professional approach in case of any class which is implimenting IList interface
  • Predicate delegate (A little known delegate but it makes searching easier and much cleaner)
  • Lamda Expression (Avaiable only in .Net 3.0 and .Net 3.5)

Loop Approach: In this approach we use for, foreach or any other loop.

Lets say I have a collection of string as follow:

            // Declare the string collection
            List<string> myStings = new List<string>();
            // Add values in the collection
            myStings.Add("Shahid");
            myStings.Add("Riaz");
            myStings.Add("Bhatti");
            myStings.Add("Ayaz Khan");
            myStings.Add("Salman");
            myStings.Add("Kamran");
            myStings.Add("Munir");
            myStings.Add("Zafar Iqbal");
            myStings.Add("Asim");
            myStings.Add("Zahid");
            myStings.Add("Sheikh Ahmad");

In the above lines I have declared List of type string and added names of some persons in it. Now I want to find all the names where the length of name is greater than four (4). Using the Loop techniques we will do it some thing like this:

            Console.WriteLine("Find names where length is greater than 4 using Loop approach\n");
            foreach (string strName in myStings)
            {
                    if(strName.Length>4)
                        System.Console.WriteLine(strName);
            }

Predicate delegate approach:

The task which we have just finished by using the Loop approach can be completed by using the predicate delegate approach. Predicate delegate are not well known delegate but they make searching easy and much cleaner. Predicate are basically just a simple user defined boolean condition which we can define in our code to sort through collection.

Consider I have the sampe string collection which we declared in the Loop approach. Now we want to fing all the name where length is greater than four (4).

Predicate<string> callBack = new Predicate<string>(IsLengthGreaterThanFour);
            List<string> Names = myStings.FindAll(callBack);
            // Display all names where length name length is greater than 4
            foreach (string strName in Names)
            {
                Console.WriteLine(strName + "\n");
            }

The user defined boolean function which we used in Predicate delegate is IsLengthGreaterThanfour and it is given below:

private static bool IsLengthGreaterThanFour(string name)
        {
            return (name.Length > 7);
        }

The above code is self explanatory.

Lamda Expression: We can use Loop and predicate delegate in our code even in .Net 3.0 and .net 3.5. But we have another feature in .Net 3.0 and 3.5 which is Lamda expression.

Note: At the moment I dont have .Net 2008 on my laptop. So I didn't wrote any Lamda expression example. But I will write very soon. 

NOTE:

Predicate delegate can be used for the different function of IList, which includes:

  • Find
  • FindAll
  • Exists and many more
I have attached a .cs file in this post. You can check the implimentation of IList function in this .cs file. The code is commented in the example. I will update this POST very soon with the implementation of lamda expression.
 

Regards,

Shahid Riaz Bhatti

Microsoft certified application developer

Predicate.cs (1.35 kb)



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , , , ,

Sep 27

What is WCF:

WCF stands for Windows communication foundation. WCF allows to build distributed application reagrdless of their underlying plumbing, in a syammetrical manner. Unlike other distributed APIs like (DCOM, .Net remoting, XML web services etc), WCF provides a single, unified, and extendable programming object model that can be used to interact with a number of previously diverse distributed technologies.

WCF is a way to develop the SOA application.

Lets get a brief introduction, advantage and disadvatange of other distributed technologies prior to WCF.

DCOM:

DCOM stands for Distributed component object model. This technology was used prior to the release of .Net platform. Using DCOM it was possible to develop Distributed system using COM objects.

Benifit:

Benifit of the DCOM was the location transparency of components. This allowed client software to be programmed in such a way that the physical location of the remote objects were not hard-coded. Regardless of whether the remote object was on the same machine or secondary networked machine, the code base could remain neutral, as the actual location was recorded externally in the system registry.

Limitation:

DCOM  was a Windows centric API. Even though DCOM was ported to a few other OS, DCOM alone did not provde a fabric to build comprehensive solution involving multiple OS(Windows,Unix, Mac) or promote sharing of data between diverse architectures (COM, J2EE, CORBA, etc)

COM+/Enterprise services:

COM+ was released by Microsoft. It's first name was Microsoft Transaction server (MTS). Despite its name, COM+ is not only used by COM programmers, it is also accessible to .Net programmers.

Features of COM+:

COM+ provides a number of features which are Transaction Management, object lifetime management, pooling services, a role based security system and a loosely coupled event model and so on.

Limitation:

COM+ has the same limitation of DCOM i.e. It is a windows only solution that is best suited for in-house application development or as a backend service indirectly manipulated by more agonistic front end.

.Net Remoting:

With the release of .Net plateform, DCOM quickly bacame a lagacy distributed API. In its place, the .Net base class libraries shipped with the .net remoting layer, represented by the System.Runtime.Remoting namespace. This namespace allows multiple computers to distribute objects, provided they are all running the application under the .net plateform.

Benifit:

.Net Remoting is usable only by .net application but it is possible to make use of .Net remoting to build distributed systems that span multiple OS.

Limitation:

Interoperability between other programming architectures (such as J2EE) was still not directly possible.

WEB Services:

From the history of the distributed API we can see that developing the distributed application which can run on multiple OS was not possible. They are all plateform and framework dependent.

XML web servies addressed this issue. So when you need to expose the services of remote objects to any OS and any programming model, XML web services provide the most straightforward way of doing so.

Benifit:

The benifit of the XML web services is interoperability and data exchange, because web service encodes its data as simple XML. Given the fact that web services are based on open industry standard (HTTP,XML,SOAP) rather than proprietary type systems and proprietary wire formats (as in case with DCOM or .net remoting), they allow for a high degree of interporability and data exchange.

Limitation:

Potential draw back of web services is the fact that they can suffer from some performance issues (given the use of HTTP and XML data representation), and they may not be suitable for in house application where TCP-based protocol and binary formatting of data could be used without penalty.

Role of WCF:

WCF is a distributed computing toolkit introduced with .net 3.0 that integrated these previous independent technologies into a streamlined API represented primarily via the System.ServiceModel namespace. WCF enables to expose services to callers using wide variety of techniques. For example, in an In-house application where all connected machines are windows based, you can make use of various TCP protocols to ensure the fastest possible performance. This same service can also be exposed using the XML web service-based protocol to allow external callers to leverage its functionality regardless of the programming language or OS.

WCF allows to pick the correct protocol for the job using a common programming model. Due to this it becomes easy to plug and play the underlying plumbing of your distributed application. In most cases, you can do so without being required to recompile or redeploy the client/service software.

In this POST I have attached a word file. In that file I developed a a simple service using the WCF. I developed that service from scratch, instead of using the WCF template. I hope that it will help in understanding of WCF.

WCF.doc (1.12 mb)



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , , , ,