Shahid Riaz Bhatti

if(my.work == “Interesting” || my.availableTime > my.workHours) { this.blog.Post();}

iframe source on the fly

May 01
by Shahid Riaz Bhatti 1. May 2009 06:38

This article will explain that how to load pages dynamically in IFrame from the code behind.

Actually few days back I encountered a situation where I was interested to set the src of IFrame dynamically. Some of the solutoin which I found on the internet were some thing like this:

 Declare a Generic control:
protected System.Web.UI.HtmlControls.HtmlGenericControl IFrame1;

Then, you need to do findcontrol to identify the control on the page and
typecast it:

HtmlControl IFrame1 = (HtmlControl)this.FindControl("IFrame1");

Now you can access the src property:

IFrame1.Attributes["src"] = http://www.live.com ;

I tried this solution but it did not work. Cry

SimilarlyI found many other solution saying exactly the same thing which I mentioned above. I posted on different forums and the answer was that this solution might not work if you are using master pages. And they gave me another suggestion that instead of passing IFrame1 (i.e. the ID of your Iframe) just pass the client ID of the IFrame to Findcontrol. But that solution also did not work for me.

Then I came across a POST which stated that turn your HTML snippet into server side code and then use the above code i.e. (HtmlControl IFrame1 = (HtmlControl)this.FindControl("IFrame1");)

I did not try this suggestion, instead I only turned my IFrame into a server side control by adding a runat="server" attribute into my IFrame and then like any other server control I accessed my IFrame from the code behindLaughing

I hope that this will help all who are facing same kind of problem.

Here is the summary:

  • Turn your IFrame into a server side control by adding a runat="server" attribute, like this:
<IFrame id="myDynamicFrame" scrolling="auto" runat="server"/>
  • Now you can access this control from your code behind file and you can set its src property on the fly, like this:
myDynamicFrame.Attributes["src"] = "http://www.shahidriaz.com";
 

Currently rated 5.0 by 2 people

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

Tags:

ASP.Net | C# | Tips and Tricks

Some interview questions

March 07
by Shahid Riaz Bhatti 7. March 2009 11:28

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

 

Currently rated 3.0 by 5 people

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

Tags: ,

ASP.Net | General | Tips and Tricks | Visual Studio

How to Implement Shallow copy in .Net

December 07
by Shahid Riaz Bhatti 7. December 2008 07:15

 

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

Currently rated 3.3 by 6 people

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

Tags: , ,

C# | General | Tips and Tricks | Visual Studio

HTML Encoding

October 15
by Shahid Riaz Bhatti 15. October 2008 15:41
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.";

 

Facade design pattern using C#

October 04
by Shahid Riaz Bhatti 4. October 2008 06:44

Dictionary Meaning : The front of a building

In Programming :

According to the Gang of four (GoF): "It is a design pattern that provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. "

Explanation:

So according to the GoF defination of the facade pattern we can say that facade pattern is used to wrap a set of complex classes into a simpler enclosing interface. It means that instead of calling the subsystem directly the developer has to use the unified simpler interface(facade class).

 

A Sample Program:
I have attached a rar file. Please read that file. I am also pasting that class, but for the better readability please download the attached rar file.
 
#region Start Facade
    /// <summary>
    /// In this example there are two classes which are:
    /// 1) Teacher
    /// 2) Student
    /// These two classes are our sub system.
    /// According to the defination of facade design pattern
    /// which is given below:
    /// (It is a design pattern that provide a unified interface
    ///  to a set of interfaces in a subsystem.)
    ///  So now according to the defination we have to create a unified
    ///  interface which would be class. You can find this class at the
    ///  end. i.e. after the student class.
    ///  This unified class will interact
    ///  with the sub system. In our main program we have to use this
    ///  unified class to access our subsystem instead of calling these
    ///  two subsystem directly.
    /// </summary>
    #endregion

    /// <summary>
    /// This is our Teacher class (Sub System). In this class we declared
    /// TeacherCollection variable of type List. In the constructor we
    /// initilized this TeacherCollection varible.
    /// Then we made a function called _GetAllTeacher of type List<T>.
    /// In this function we populated TeacherCollection with some dummy values.
    /// </summary>  
    public class Teacher
    {
        List<string> TeacherCollection;
        public Teacher()
        {
            TeacherCollection = new List<string>();
        }
        public List<string> _GetAllTeacher()
        {
            TeacherCollection.AddRange(new string[] {"Teacher One","Teacher Two","Teacher three","Teacher four","Teacher Five"});
            return TeacherCollection;
        }
    }
    /// <summary>
    /// This is our student class (Sub System). In this class we declared
    /// StudentCollection variable of type List. In the constructor we
    /// initilized this StudentCollection varible.
    /// Then we made a function called _GetAllStudent of type List<T>.
    /// In this function we populated StudentCollection with some dummy values.
    /// </summary>
    public class Student
    {
        List<string> StudentCollection;
        public Student()
        {
            StudentCollection = new List<string>();
        }
        public List<string> _GetAllStudent()
        {
            StudentCollection.AddRange(new string[] { "Student One", "Student Two", "Student three", "Student four", "Student Five" });
            return StudentCollection;
        }
    }

    /// <summary>
    ///
    /// </summary>
    public class Facade
    {
        // Declare the object of Subsystems
        Teacher _ObjectOfTeacher;
        Student _ObjectOfStudent;
        //Constructor
        public Facade()
        {
            // Initilize the Sub Systems.
            _ObjectOfTeacher = new Teacher();
            _ObjectOfStudent = new Student();
        }
        /// <summary>
        /// Get all teachers from the teacher Sub system
        /// </summary>
        /// <returns></returns>
        public List<string> GetTeacehrs()
        {
            return _ObjectOfTeacher._GetAllTeacher();
        }
        /// <summary>
        /// Get all students from Student Sub Systems
        /// </summary>
        /// <returns></returns>
        public List<string> GetStudents()
        {
            return _ObjectOfStudent._GetAllStudent();
        }
    }
 
Advantages of using Facade: 

The Facade pattern shields clients from complex subsystem components and provides a simpler programming interface for the general user. The Facade allows us to make changes in the underlying sub systems without requiring changes in the client code and reduces the compilation dependencies. 

 

Regards,

Shahid Riaz Bhatti

Microsoft Certified Application developer (MCAD)

Facaderar.rar (1.41 kb)

Be the first to rate this post

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

Tags: , , , , ,

C# | Design Patterns | General | Tips and Tricks

RecentComments

Comment RSS

Most comments

supplynflshop supplynflshop
51 comments
tiffany-bracelets tiffany-bracelets
39 comments
AVI to iPad AVI to iPad
36 comments