Shahid Riaz Bhatti

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

How to Remove command bar button from Add-Ins

May 04
by Shahid Riaz Bhatti 4. May 2009 10:05
 

Remove command bar from Add-ins in MS Word

 

Some time we need to develop some add-ins to fulfill our requirements in different software (e.g. MS Word). Few days back I was developing an Add-ins for MS word. The requirement was to add a button in a command bar of the MS-Word. I successfully added button in the command bar and also wrote code against the event handler of that button. But unfortunately whenever I ran the MS word, my code started to add the same button in command bar again and again. To overcome this problem I wrote code which forcefully removed that custom button from the command bar on the closing of the ms word.

The code which was removing that button on the closing of the word was in the Application_DocumentBeforeClose event of Add-in. But that code didn’t give me the expected output.

There was nothing wrong in the code, because I debugged the code and in the shutdown event I made sure that the command button exists in the command bar. If it exists then delete the button. But again that code didn’t work. And interesting thing was that the code segment which was checking that the command button exists in the command bar always gave me true and in the true section I was deleting that button, but I don’t know that why it didn’t work. I was deleting the command button by using the ID of the button something like this:

1.     Office.CommandBarPopup foundMenu = (Office.CommandBarPopup)

2.     this.Application.CommandBars.ActiveMenuBar.FindControl(Office.

3.     MsoControlType.msoControlPopup, System.Type.Missing, IDOfControl, true, true );

4.     if (foundMenu != null)

5.     {

6.       foundMenu.Delete(false);

7.     }

The above code didn’t work L 

In line 3, I used the IDOfControl to find the command bar button, but it didn’t find that control. Though I tried to use the Id.delete() method, but it also didn’t work for me. Then I changed the Line number 3 and instead of using the ID of the control to find the command bar button, I used the tag of that control and this change in code successfully find the control and this change also make the Line 6 to give the expected output.  So if you are also facing this kind of situation then try to use the tag of the button instead of its ID. I am sure it will work. Well I was developing the add-in for office 2007. This code will probably work in other version of MS word too. The reason that this code work is given below: 

Add-in Express identifies all its controls (commandbar controls) through the use of the ControlTag property (the Tag property of the CommandBarControl interface). The value of this property is generated automatically and you don’t need to change it. For your own needs, use the Tag property instead.       

Be the first to rate this post

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

Tags:

C# | C# | Tips and Tricks | Tips and Tricks

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

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

When to use abstract class??

November 25
by Shahid Riaz Bhatti 25. November 2008 08:38

I got the following question in a Yahoo group:

I read few articles on Abstract Classes but it is still not clear to me. What exactly an "Abstract" keyword means? In which situation to use Abstract Class?

In response to that question I wrote the following article and thought to share it.  

Abstract class:

It is a class which can not be initialized. You should make a class an abstract class when there is atleast one abstract method in your class. Abstract class can have abstract as well as non abstract method. Abstract class can not be used directly, instead you need to derive class from the abstact class. 

Difference between abstract class and an interface is that:

Abstract class can have internal member, while interface can not. Abstract class can have abstract and non-abstract method while intreface contains only the signature.

When to use abstract class:

Make a class an abstract class when there is atleast one abstract method in your class. When you want your class to be act as a base class and you dont want that object of your class could be created.

Example:

Let’s consider a very simple and basic example. We need to write two classes for

  • Lion
  • Goat

From the name of these two classes you can imagine that what these two classes are.

Common things between these two types of class are:

  1. Both types of classes have same number of Legs.
  2. Both are living creatures.

The uncommon things b/w these two is that Lion eats meats while goat does not.

Wrong Solution:

If you are asked to write classes to handle these two classes then you can do the following things:

Write two classes (i.e. Lion and Goat) with the following function along with their Implementation:

  • public void NoOfLegs()
  • public void IsLivingCreature()
  • public void DoesEatMeat()

You have achieved your solution, but it is not a good solution. Now lets write code to achieve the same thing in a different way.

A better solution: 

Write a class "Common" like this:

public abstract class common
    {
        public void NoOfLegs()
        {
            Console.WriteLine("No. of legs are: 4");
        }
        public void IsLivingCreature()
        {
            Console.WriteLine("Yes");
        }
        public abstract void DoesEatMeat();
    }

You can see that we have implemented those function which are common in Lion and Goat class, so that we can avoid to write code for these two function again in Lion and Goat class, because we will derive our Lion and Goat classes from this common class. We made the DoesEatMeat() an abstract method because Lion and Goat's behavior are differnet for this (i.e. Lion eat meat while goat does not). Here is the Lion and Goat class:

  public class Lion : common
    {
        public override void DoesEatMeat()
        {
            Console.WriteLine("Yes");
        }
    }
    public class Goat : common
    {
        public override void DoesEatMeat()
        {
            Console.WriteLine("No");
        }
    }

In the above code you can see that we derived two classes Lion and Goat from the common class and override only the DoesEatMeat according to the behavior of Lion and Goat.

We can not achieve the same thing using interface, because there is no way in interface to provide the implementation of common behaviors between two entities. So from this it should be clear that when to use interface and when to use abstract class.

The complete sample code with along with the out put is given below:

 

 

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

namespace WhenAbstractClass
{
    class Program
    {
        static void Main(string[] args)
        {
            Lion lion = new Lion();
            lion.NoOfLegs();
            lion.IsLivingCreature();
            lion.DoesEatMeat();

            Goat goat = new Goat();
            goat.NoOfLegs();
            goat.IsLivingCreature();
            goat.DoesEatMeat();

        }
    }
    public abstract class common
    {
        public void NoOfLegs()
        {
            Console.WriteLine("No. of legs are: 4");
        }
        public void IsLivingCreature()
        {
            Console.WriteLine("Yes");
        }
        public abstract void DoesEatMeat();
    }
    public class Lion : common
    {
        public override void DoesEatMeat()
        {
            Console.WriteLine("Yes");
        }
    }
    public class Goat : common
    {
        public override void DoesEatMeat()
        {
            Console.WriteLine("No");
        }
    }
}
 

 

Out Put: 

Copy and pase the above code in a c# console based application :)

Be the first to rate this post

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

Tags:

C# | General

Delegate in C Sharp

November 02
by Shahid Riaz Bhatti 2. November 2008 09:36

What is delegate:

Delegate is a class which holds a reference to a method or a function. Delegate has a signature and It can only address those method or function whose signature are compatibe with the delegate.

e.g. A Delegate with a void return type and taking a string parameter can only holds a reference to a method or function which is taking a string parameter and whose return type is void.

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

namespace GenericDelegate
{
    class Program
    {
        // Declare a delegate taking a string parameter
        // and returning nothing (i.e. void)
        public delegate void MyDelegate(string param);

        static void Main(string[] args)
        {
            MyDelegate strTarget = new MyDelegate(StringTarget);
            // Invokde the method using the delegate
            strTarget.Invoke("Hello delegate");
        }
        static void StringTarget(string arg)
        {
            Console.WriteLine("arg in uppercase is: {0}", arg.ToUpper());
        }

    }
}

 

In the above example I have delcared a delegate  MyDelegate and invoked it in the main program. The target of this delegate is StringTarget. The code is self explanatory.

Generic Delegate:

The above example is limited for only those functions or methods which is taking a string parameter and whose return type is void. What if we need a delegate which can take parameter of any kind (i.e. int, string,float or any class)? The answer is Generic delegate. The example of the Generic delegate is given below:

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

namespace GenericDelegate
{
    class Program
    {
        // Declare a delegate


        public delegate void MyGenericDelegate<T>(T param);

        static void Main(string[] args)
        {
            MyGenericDelegate<string> strTarget = new MyGenericDelegate<string>(StringTarget);
            // Invokde the method using the delegate
            strTarget.Invoke("Hello Generic Delegate");

            MyGenericDelegate<int> strIntTarget = new MyGenericDelegate<int>(IntegerTarget);
            strIntTarget.Invoke(100);
        }
        static void StringTarget(string arg)
        {
            Console.WriteLine("arg in uppercase is: {0}", arg.ToLower());
        }
        static void IntegerTarget(int arg)
        {
            Console.WriteLine("Integer arg is: {0}", arg.ToString());
        }

    }
}



In the above example I have declared a delegate which is MyGenericDelegate. This delegate is taking a type of generic i.e. T. To understand the Generic delegate see the implementation in the main program. In the main program I invoked two methods by using this generic delegate. First time I gave it a target of a function which is taking a parameter of type string and second type an Integer. The Generic delegate can take any kind of parameter and can hold reference to any methods or function.

Generic delegate for Custom data type:

Generic delegate can holds a reference to a methods or function of custome data type. i.e. I can write a class (myCustomeClass) and then I can use my Generic delegate of last example which can holds a reference to a function or method which is taking a parameter of type myCustome class.

Now see the following example:

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

namespace GenericDelegate
{
    class Shahid
    {
        private string firstName = string.Empty;

        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }
        private string lastName = string.Empty;

        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }

    }



    class Program
    {
        // Declare a delegate.

         public delegate void MyGenericDelegate<T>(T param);

        static void Main(string[] args)
        {
            MyGenericDelegate<string> strTarget = new MyGenericDelegate<string>(StringTarget);
            // Invokde the method using the delegate
            strTarget.Invoke("Hello Generic Delegate");

            MyGenericDelegate<int> strIntTarget = new MyGenericDelegate<int>(IntegerTarget);
            strIntTarget.Invoke(100);

            Shahid obj = new Shahid();
            obj.FirstName = "Shahid";
            obj.LastName = "Riaz";
            MyGenericDelegate<Shahid> CustomeDataTypedelegate = new MyGenericDelegate<Shahid>(DisplayMyName);
            CustomeDataTypedelegate.Invoke(obj);

        }
        static void StringTarget(string arg)
        {
            Console.WriteLine("arg in uppercase is: {0}", arg.ToLower());
        }
        static void IntegerTarget(int arg)
        {
            Console.WriteLine("arg in uppercase is: {0}", arg.ToString());
        }
        static void DisplayMyName(Shahid obj)
        {
            Console.WriteLine("My Name is :" + obj.LastName + ", " + obj.FirstName);
            object obj;
        }

    }
}


The above example is a modified version of my last example in which I wrote a generic delegate and then use that delegate to invoke two function (one for string and one for Int). In this modified version I have made some changes which are given below:

I wrote a class names "Shahid" and added two fields in it i.e. (firstName and lastName). Also I added two properties for these two fields which are FirstName and LastName.

I also wrote a new method which is taking parameter of type "Shahid".

In the main program I declared the object of class Shahid, and then used that object to set the values for first name and last name. Then I used the GenericDelegate to invoke the method "DisplayMyName" method.

How to Put Restriction on delegate:

In the Generic delegate example we are invoking methods which can take parameter of any type. (i.e. in example I am using generic delegate to invoke the methods which are taking parameters of type "string,Integer and a custome data type which is Shahid".

Now I want my generic delegate to invoke only those methods which are taking only reference type parameter. To accomodate this requirments I have to modify myGenericDelegate. At the moment my delegate is declared as follow:

public delegate void MyGenericDelegate<T>(T param);

Now I want to modify my delegate so that it can invoke only those methods or function which are taking only reference type parameter. So I will change above delegate like this:

public delegate void MyGenericDelegate<T>(T param) where T : class;

Similarly you can modify the delegate to invoke only those functions or methods which are taking only value type parameter. like this:

public delegate void MyGenericDelegate<T>(T param) where T : struct;

Regards,


Shahid Riaz Bhatti
kick it on DotNetKicks.com
Technorati Profile

Currently rated 3.0 by 4 people

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

Tags: , ,

C#

RecentComments

Comment RSS

Most comments

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