-1

In Visio VBA (or COM API)

How can i get a shape without expecting an exception when the shape name is not found?

... in my visio page, there might or might not be a Rectangle Shape with the name "DraftText".

i want to check that it is there and if yes, do smth.

my code seems like:

Shape waterMarkRect = page.Shapes["DraftText"];
if (waterMarkRect == null)
{
   waterMarkRect = page.DrawRectangle(0, 0, 50, 15);
   waterMarkRect.Name = "DraftText";
   waterMarkRect.NameU = waterMarkRect.Name;
   waterMarkRect.Text = "INCONSISTANT";

   Layer wMarkLayer = page.Layers["WMark"] ?? page.Layers.Add("WMark");
   wMarkLayer.Add(waterMarkRect, 0);
}
...
...

The problem is that, if the shape "DraftText" is not there, i get a COM Exception.

as i am against using try catch block as a coding utility,

i am searching for a way to check for the shape existance prior to taking it such as IDictionary.TryGetValue(, out);

or if(page.Shapes.Contain("DraftText"))...

Any Ideas?

Tomer W
  • 3,395
  • 2
  • 29
  • 44

2 Answers2

1

Doing it through VBA, I just do a "on error resume next" before attempting to get the shape by name, and on error goto PROC_ERR to resume error handling afterward.

If you can't disable the exception, you could loop over every shape and check its name against the one you're looking for. This would take a lot longer to perform compared with the built-in lookup by name, though.

Jon Fournier
  • 4,299
  • 3
  • 33
  • 43
  • On Error is same as try {} catch() {} It is bad practice i try to avoid any means necessery. itterating is an option, i dont like, but might be if nothing is possible. i'll +1 for now, if no answer will be applicable, i'll V it :) Thanks for your replay. – Tomer W Apr 04 '12 at 15:54
0

Using try catch block

Shape waterMarkRect = null;
try { 
    waterMarkRect = page.Shapes["DraftText"];
}
catch (Exception){
}

if (waterMarkRect == null)
{
   waterMarkRect = page.DrawRectangle(0, 0, 50, 15);
   waterMarkRect.Name = "DraftText";
   waterMarkRect.NameU = waterMarkRect.Name;
   waterMarkRect.Text = "INCONSISTANT";

   Layer wMarkLayer = page.Layers["WMark"] ?? page.Layers.Add("WMark");
   wMarkLayer.Add(waterMarkRect, 0);
}
Jones
  • 1,480
  • 19
  • 34
  • 1
    I Guess this is most likely to be what's possible, you might want to add a check for what Exception was caught `catch(COMException ex){if(ex.ErrorCode != 0x00000) throw;}` so you wont miss a true exception – Tomer W Jul 31 '12 at 06:48