466. Araxis Merge File Comparison Report

Produced by Araxis Merge on 2/1/2017 2:56:46 PM Eastern Standard Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

466.1 Files compared

# Location File Last Modified
1 C:\Araxis_Merge_Comprasion\Pub_un\BTSSS_CIF_122016.zip\BTSSS_CIF_12_20_16\clean\CRM\trunk\SDK\SampleCode\CS\Metadata\Diagram DiagramBuilder.cs Tue Dec 20 19:51:46 2016 UTC
2 Wed Feb 1 19:56:46 2017 UTC

466.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 0 0
Changed 0 0
Inserted 0 0
Removed 1 618

466.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

466.4 Active regular expressions

No regular expressions were active.

466.5 Comparison detail

1   // ======= ========== ========== ========== ========== ========== ========== ==        
2   //  File:                 Diagra mBuilder.c s        
3   //  Summar y:    This  sample co mmand-line  tool crea tes a         
4   //               Micr osoft Offi ce Visio d iagram tha t details  relationsh ips        
5   //               betw een Micros oft CRM en tities. Fi rst, this  sample rea ds        
6   //               all  the entity  names fro m the para meter list  or defaul ts        
7   //               to a ll entitie s. Second,  it create s a Visio  object for          
8   //               the  entity and  all of th e entities  related t o the enti ty,        
9   //               and  then it li nks them t ogether. F inally, th e file is  saved.        
10   // ======= ========== ========== ========== ========== ========== ========== ==        
11   //        
12   //  This f ile is par t of the M icrosoft C RM 2011 SD K Code Sam ples.        
13   //        
14   //  Copyri ght (C) Mi crosoft Co rporation.   All righ ts reserve d.        
15   //        
16   //  This s ource code  is intend ed only as  a supplem ent to Mic rosoft        
17   //  Develo pment Tool s and/or o n-line doc umentation .  See the se other        
18   //  materi als for de tailed inf ormation r egarding M icrosoft c ode sample s.        
19   //        
20   //  THIS C ODE AND IN FORMATION  ARE PROVID ED "AS IS"  WITHOUT W ARRANTY OF  ANY        
21   //  KIND,  EITHER EXP RESSED OR  IMPLIED, I NCLUDING B UT NOT LIM ITED TO TH E        
22   //  IMPLIE D WARRANTI ES OF MERC HANTABILIT Y AND/OR F ITNESS FOR  A        
23   //  PARTIC ULAR PURPO SE.        
24   //        
25   // ======= ========== ========== ========== ========== ========== ========== ==        
26          
27   using Syst em;        
28   using Syst em.Text;        
29   using Syst em.Text.Re gularExpre ssions;        
30   using Syst em.IO;        
31   using Syst em.Diagnos tics;        
32   using Syst em.Collect ions;        
33          
34   using Visi oApi = Mic rosoft.Off ice.Intero p.Visio;        
35          
36   using Syst em.Service Model;        
37   using Syst em.Service Model.Desc ription;        
38   using Syst em.Collect ions.Gener ic;        
39   using Syst em.Xml.Ser ialization ;        
40   using Syst em.Xml;        
41          
42          
43   // These n amespaces  are found  in the Mic rosoft.Xrm .Sdk.dll a ssembly        
44   // found i n the SDK\ bin folder .        
45   using Micr osoft.Xrm. Sdk;        
46   using Micr osoft.Xrm. Sdk.Query;        
47   using Micr osoft.Xrm. Sdk.Metada ta;        
48   using Micr osoft.Xrm. Sdk.Client ;        
49   using Micr osoft.Xrm. Sdk.Messag es;        
50          
51   // This na mespace is  found in  Microsoft. Crm.Sdk.Pr oxy.dll as sembly        
52   // found i n the SDK\ bin folder .        
53   using Micr osoft.Crm. Sdk.Messag es;        
54          
55          
56   namespace  Microsoft. Crm.Sdk.Sa mples        
57   {        
58       /// <s ummary>        
59       /// Cr eate a Vis io diagram  detailing  relations hips betwe en Microso ft CRM ent ities.        
60       ///        
61       /// Fi rst, this  sample rea ds in all  the entity  names. It  then crea tes a visi o object f or        
62       /// th e entity a nd all of  the entiti es related  to the en tity, and  links them  together.        
63       /// Fi nally,it s aves the f ile to dis k.        
64       /// </ summary>        
65       public  class Dia gramBuilde r        
66       {        
67           #r egion Clas s Level Me mbers        
68          
69           // / <summary >        
70           // / Stores t he organiz ation serv ice proxy.        
71           // / </summar y>        
72           pu blic stati c Organiza tionServic eProxy _se rviceProxy ;        
73          
74           //  Specify w hich langu age code t o use in t he sample.  If you ar e using a  language        
75           //  other tha n US Engli sh, you wi ll need to  modify th is value a ccordingly .        
76           //  See http: //msdn.mic rosoft.com /en-us/lib rary/0h88f ahh.aspx        
77           pu blic const  int _lang uageCode =  1033;        
78          
79          
80           pr ivate Visi oApi.Appli cation _ap plication;        
81           pr ivate Visi oApi.Docum ent _docum ent;        
82           pr ivate Retr ieveAllEnt itiesRespo nse _metad ataRespons e;        
83           pr ivate Arra yList _pro cessedRela tionships;        
84          
85           pr ivate cons t double X _POS1 = 0;        
86           pr ivate cons t double Y _POS1 = 0;        
87           pr ivate cons t double X _POS2 = 1. 75;        
88           pr ivate cons t double Y _POS2 = 0. 6;        
89          
90           co nst double  SHDW_PATT ERN = 0;        
91           co nst double  BEGIN_ARR OW_MANY =  29;        
92           co nst double  BEGIN_ARR OW = 0;        
93           co nst double  END_ARROW  = 29;        
94           co nst double  LINE_COLO R_MANY = 1 0;        
95           co nst double  LINE_COLO R = 8;        
96           co nst double  LINE_PATT ERN_MANY =  2;        
97           co nst double  LINE_PATT ERN = 1;        
98           co nst string  LINE_WEIG HT = "2pt" ;        
99           co nst double  ROUNDING  = 0.0625;        
100           co nst double  HEIGHT =  0.25;        
101           co nst short  NAME_CHARA CTER_SIZE  = 12;        
102           co nst short  FONT_STYLE  = 225;              
103           co nst short  VISIO_SECT ION_OJBECT _INDEX = 1 ;        
104           St ring Versi onName;        
105          
106           //  Excluded  entities.        
107           //  These ent ities exis t in the m etadata bu t are not  to be draw n in the d iagram.        
108           st atic Hasht able _excl udedEntity Table = ne w Hashtabl e();        
109           st atic strin g[] _exclu dedEntitie s = new st ring[] {        
110                                                           "activity party" ,   "annotatio n" ,  "app ointment"  ,   "async operation"  , "attrib utemap" ,           
111                                                           "bulkdele tefailure"  ,  "bulki mport" ,   "bulkopera tionlog" ,    "busine ssunit" ,   "business unitmap" ,            
112                                                           "commitme nt" ,  "co nnection"  ,          
113                                                           "displays tringmap"  ,  "docume ntindex" ,   "duplica terecord"   ,          
114                                                           "email" ,    "entity map" ,          
115                                                           "fax" ,            
116                                                           "imagedes criptor" ,   "importc onfig" ,   "integrati onstatus"  ,   "inter naladdress " ,           
117                                                           "letter"  ,          
118                                                           "msdyn_wa llsavedque ry" ,  "ms dyn_wallsa vedqueryus ersettings " ,           
119                                                           "owner" ,           
120                                                           "partnera pplication " ,  "phon ecall" ,    "pluginty pe" ,  "po stfollow"  ,  "postre garding" ,    "postro le" ,          
121                                                           "principa lobjectatt ributeacce ss" ,  "pr ivilegeobj ecttypecod es" ,   "p rocesssess ion" ,  "p rocessstag e" ,          
122                                                           "recurrin gappointme ntmaster"  ,    "role template"  ,  "rolete mplatepriv ileges" ,           
123                                                           "servicea ppointment " ,  "shar epointdocu mentlocati on" , "sta tusmap" ,   "stringma p" ,  "str ingmapbit"  ,           
124                                                           "subscrip tion" ,  " systemuser " ,          
125                                                           "task" ,    "tracelo g" ,  "tra ceregardin g" ,          
126                                                           "userenti tyinstance data"  };        
127          
128           //  Excluded  relationsh ip list.        
129           //  Those ent ity relati onships th at should  not be inc luded in t he diagram .        
130           st atic Hasht able _excl udedRelati onsTable =  new Hasht able();        
131           st atic strin g[] _exclu dedRelatio ns = new s tring[] {  "owningtea m", "organ izationid"  };        
132           #e ndregion C lass Level  Members        
133          
134           pu blic Diagr amBuilder( )        
135           {        
136                // Build  a hashtab le from th e array of  excluded  entities.  This will        
137                // allow  for faste r lookups  when deter mining if  an entity  is to be e xcluded.        
138                for (int  n = 0; n  < _exclude dEntities. Length; n+ +)        
139                {        
140                    _exc ludedEntit yTable.Add (_excluded Entities[n ].GetHashC ode(), _ex cludedEnti ties[n]);        
141                }        
142          
143                // Do th e same for  excluded  relationsh ips.        
144                for (int  n = 0; n  < _exclude dRelations .Length; n ++)        
145                {        
146                    _exc ludedRelat ionsTable. Add(_exclu dedRelatio ns[n].GetH ashCode(),  _excluded Relations[ n]);        
147                }        
148                _process edRelation ships = ne w ArrayLis t(128);        
149           }        
150          
151          
152           // / <summary >        
153           // / Main ent ry point f or the app lication.        
154           // / </summar y>        
155           // / <param n ame="CmdAr gs">Entiti es to plac e on the d iagram</pa ram>        
156           pu blic stati c int Main (string[]  args)        
157           {        
158                String f ilename =  String.Emp ty;        
159                VisioApi .Applicati on applica tion;        
160                VisioApi .Document  document;        
161                DiagramB uilder bui lder = new  DiagramBu ilder();        
162          
163                try        
164                {        
165                    // O btain the  target org anization' s Web addr ess and cl ient logon          
166                    // c redentials  from the  user.        
167                    Serv erConnecti on serverC onnect = n ew ServerC onnection( );        
168                    Serv erConnecti on.Configu ration con fig = serv erConnect. GetServerC onfigurati on();        
169          
170                    // C onnect to  the Organi zation ser vice.         
171                    // T he using s tatement a ssures tha t the serv ice proxy  will be pr operly dis posed.        
172                    usin g (_servic eProxy = S erverConne ction.GetO rganizatio nProxy(con fig))        
173                    {        
174                         // This st atement is  required  to enable  early-boun d type sup port.        
175                         _servicePr oxy.Enable ProxyTypes ();        
176          
177                         // Load Vi sio and cr eate a new  document.        
178                         applicatio n = new Vi sioApi.App lication() ;        
179                         applicatio n.Visible  = false; / / Not show ing the UI  increases  rendering  speed          
180                         builder.Ve rsionName  = applicat ion.Versio n;        
181                         document =  applicati on.Documen ts.Add(Str ing.Empty) ;        
182                         builder._a pplication  = applica tion;        
183                         builder._d ocument =  document;        
184          
185                         // Load th e metadata .        
186                         Console.Wr iteLine("L oading Met adata...") ;        
187                         RetrieveAl lEntitiesR equest req uest = new  RetrieveA llEntities Request()        
188                         {        
189                             Entity Filters =  EntityFilt ers.Entity  | EntityF ilters.Att ributes |  EntityFilt ers.Relati onships,        
190                             Retrie veAsIfPubl ished = tr ue,        
191          
192                         };        
193                         RetrieveAl lEntitiesR esponse re sponse = ( RetrieveAl lEntitiesR esponse)_s erviceProx y.Execute( request);        
194                         builder._m etadataRes ponse = re sponse;        
195          
196                         // Diagram  all entit ies if giv en no comm and-line p arameters,  otherwise  diagram        
197                         // those e ntered as  command-li ne paramet ers.        
198                         if (args.L ength < 1)        
199                         {        
200                             ArrayL ist entiti es = new A rrayList() ;        
201          
202                             foreac h (EntityM etadata en tity in re sponse.Ent ityMetadat a)        
203                             {        
204                                 //  Only draw  an entity  if it doe s not exis t in the e xcluded en tity table .        
205                                 if  (!_exclud edEntityTa ble.Contai nsKey(enti ty.Logical Name.GetHa shCode()))        
206                                 {        
207                                      entities .Add(entit y.LogicalN ame);        
208                                 }        
209                                 el se        
210                                 {        
211                                      Console. WriteLine( "Excluding  entity: { 0}", entit y.LogicalN ame);        
212                                 }        
213                             }        
214          
215                             builde r.BuildDia gram((stri ng[])entit ies.ToArra y(typeof(s tring)), " All Entiti es");        
216                             filena me = "AllE ntities.vs d";        
217                         }        
218                         else        
219                         {        
220                             builde r.BuildDia gram(args,  String.Jo in(", ", a rgs));        
221                             filena me = Strin g.Concat(a rgs[0], ". vsd");        
222                         }        
223          
224                         // Save th e diagram  in the cur rent direc tory using  the name  of the fir st        
225                         // entity  argument o r "AllEnti ties" if n one were g iven. Clos e the Visi o applicat ion.         
226                         document.S aveAs(Dire ctory.GetC urrentDire ctory() +  "\\" + fil ename);        
227                         applicatio n.Quit();        
228                    }        
229                }        
230                catch (F aultExcept ion<Micros oft.Xrm.Sd k.Organiza tionServic eFault> ex )        
231                {        
232                    Cons ole.WriteL ine("The a pplication  terminate d with an  error.");        
233                    Cons ole.WriteL ine("Times tamp: {0}" , ex.Detai l.Timestam p);        
234                    Cons ole.WriteL ine("Code:  {0}", ex. Detail.Err orCode);        
235                    Cons ole.WriteL ine("Messa ge: {0}",  ex.Detail. Message);        
236                    Cons ole.WriteL ine("Plugi n Trace: { 0}", ex.De tail.Trace Text);        
237                    Cons ole.WriteL ine("Inner  Fault: {0 }",        
238                         null == ex .Detail.In nerFault ?  "No Inner  Fault" :  "Has Inner  Fault");        
239                }        
240                catch (S ystem.Time outExcepti on ex)        
241                {        
242                    Cons ole.WriteL ine("The a pplication  terminate d with an  error.");        
243                    Cons ole.WriteL ine("Messa ge: {0}",  ex.Message );        
244                    Cons ole.WriteL ine("Stack  Trace: {0 }", ex.Sta ckTrace);        
245                    Cons ole.WriteL ine("Inner  Fault: {0 }",        
246                         null == ex .InnerExce ption.Mess age ? "No  Inner Faul t" : ex.In nerExcepti on.Message );        
247                }        
248                catch (S ystem.Exce ption ex)        
249                {        
250                    Cons ole.WriteL ine("The a pplication  terminate d with an  error.");        
251                    Cons ole.WriteL ine(ex.Mes sage);        
252          
253                    // D isplay the  details o f the inne r exceptio n.        
254                    if ( ex.InnerEx ception !=  null)        
255                    {        
256                         Console.Wr iteLine(ex .InnerExce ption.Mess age);        
257          
258                         FaultExcep tion<Micro soft.Xrm.S dk.Organiz ationServi ceFault> f e        
259                             = ex.I nnerExcept ion        
260                             as Fau ltExceptio n<Microsof t.Xrm.Sdk. Organizati onServiceF ault>;        
261                         if (fe !=  null)        
262                         {        
263                             Consol e.WriteLin e("Timesta mp: {0}",  fe.Detail. Timestamp) ;        
264                             Consol e.WriteLin e("Code: { 0}", fe.De tail.Error Code);        
265                             Consol e.WriteLin e("Message : {0}", fe .Detail.Me ssage);        
266                             Consol e.WriteLin e("Plugin  Trace: {0} ", fe.Deta il.TraceTe xt);        
267                             Consol e.WriteLin e("Inner F ault: {0}" ,        
268                                 nu ll == fe.D etail.Inne rFault ? " No Inner F ault" : "H as Inner F ault");        
269                         }        
270                    }        
271                }        
272                // Addit ional exce ptions to  catch: Sec urityToken Validation Exception,  ExpiredSe curityToke nException ,        
273                // Secur ityAccessD eniedExcep tion, Mess ageSecurit yException , and Secu rityNegoti ationExcep tion.        
274          
275                finally        
276                {        
277                    //Co nsole.Writ eLine("Ren dering com plete.");        
278                    Cons ole.WriteL ine("Rende ring compl ete.  Pres s any key  to continu e.");        
279                    Cons ole.ReadLi ne();        
280                }        
281                return 0 ;        
282           }        
283          
284           // / <summary >        
285           // / Create a  new page  in a Visio  file show ing all th e direct e ntity rela tionships  participat ed in        
286           // / by the p assed-in a rray of en tities.        
287           // / </summar y>        
288           // / <param n ame="entit ies">Core  entities f or the dia gram</para m>        
289           // / <param n ame="pageT itle">Page  title</pa ram>        
290           pr ivate void  BuildDiag ram(string [] entitie s, string  pageTitle)        
291           {        
292                // Get t he default  page of o ur new doc ument        
293                VisioApi .Page page  = _docume nt.Pages[1 ];        
294                page.Nam e = pageTi tle;        
295          
296                // Get t he metadat a for each  passed-in  entity, d raw it, an d draw its  relations hips.        
297                foreach  (string en tityName i n entities )        
298                {        
299                    Cons ole.Write( "Processin g entity:  {0} ", ent ityName);        
300          
301                    Enti tyMetadata  entity =  GetEntityM etadata(en tityName);        
302          
303                    // C reate a Vi sio rectan gle shape.        
304                    Visi oApi.Shape  rect;        
305          
306                    try        
307                    {        
308                         // There i s no "Get  Try", so w e have to  rely on an  exception  to tell u s it does  not exists        
309                         // We have  to skip s ome entiti es because  they may  have alrea dy been ad ded by rel ationships  of anothe r entity        
310                         rect = pag e.Shapes.g et_ItemU(e ntity.Sche maName);        
311                    }        
312                    catc h (System. Runtime.In teropServi ces.COMExc eption)        
313                    {        
314                         rect = Dra wEntityRec tangle(pag e, entity. SchemaName , entity.O wnershipTy pe.Value);        
315                         Console.Wr ite('.');  // Show pr ogress        
316                    }        
317          
318                    // D raw all re lationship s TO this  entity.        
319                    Draw Relationsh ips(entity , rect, en tity.ManyT oManyRelat ionships,  false);        
320                    Cons ole.Write( '.'); // S how progre ss        
321                    Draw Relationsh ips(entity , rect, en tity.ManyT oOneRelati onships, f alse);        
322          
323                    // D raw all re lationship os FROM th is entity        
324                    Draw Relationsh ips(entity , rect, en tity.OneTo ManyRelati onships, t rue);        
325                    Cons ole.WriteL ine('.');  // Show pr ogress        
326                }        
327          
328                // Arran ge the sha pes to fit  the page.        
329                page.Lay out();        
330                page.Res izeToFitCo ntents();        
331           }        
332          
333           // / <summary >        
334           // / Draw on  a Visio pa ge the ent ity relati onships de fined in t he passed- in relatio nship coll ection.        
335           // / </summar y>        
336           // / <param n ame="entit y">Core en tity</para m>        
337           // / <param n ame="rect" >Shape rep resenting  the core e ntity</par am>        
338           // / <param n ame="relat ionshipCol lection">C ollection  of entity  relationsh ips to dra w</param>        
339           // / <param n ame="areRe ferencingR elationshi ps">Whethe r or not t he core en tity is th e referenc ing entity  in the re lationship </param>        
340           pr ivate void  DrawRelat ionships(E ntityMetad ata entity , VisioApi .Shape rec t, Relatio nshipMetad ataBase[]  relationsh ipCollecti on, bool a reReferenc ingRelatio nships)        
341           {        
342                ManyToMa nyRelation shipMetada ta current ManyToMany Relationsh ip = null;        
343                OneToMan yRelations hipMetadat a currentO neToManyRe lationship  = null;        
344                EntityMe tadata ent ity2 = nul l;        
345                Attribut eMetadata  attribute2  = null;        
346                Attribut eMetadata  attribute  = null;        
347                Guid met adataID =  Guid.NewGu id();        
348                bool isM anyToMany  = false;        
349          
350                // Draw  each relat ionship in  the relat ionship co llection.        
351                foreach  (Relations hipMetadat aBase enti tyRelation ship in re lationship Collection )        
352                {        
353                    enti ty2 = null ;        
354          
355                    if ( entityRela tionship i s ManyToMa nyRelation shipMetada ta)        
356                    {        
357                         isManyToMa ny = true;        
358                         currentMan yToManyRel ationship  = entityRe lationship  as ManyTo ManyRelati onshipMeta data;        
359                         // The ent ity passed  in is not  necessari ly the ori ginator of  this rela tionship.        
360                         if (String .Compare(e ntity.Logi calName, c urrentMany ToManyRela tionship.E ntity1Logi calName, t rue) != 0)        
361                         {        
362                             entity 2 = GetEnt ityMetadat a(currentM anyToManyR elationshi p.Entity1L ogicalName );        
363                         }        
364                         else        
365                         {        
366                             entity 2 = GetEnt ityMetadat a(currentM anyToManyR elationshi p.Entity2L ogicalName );        
367                         }        
368                         attribute2  = GetAttr ibuteMetad ata(entity 2, entity2 .PrimaryId Attribute) ;        
369                         attribute  = GetAttri buteMetada ta(entity,  entity.Pr imaryIdAtt ribute);        
370                         metadataID  = current ManyToMany Relationsh ip.Metadat aId.Value;        
371                    }        
372                    else  if (entit yRelations hip is One ToManyRela tionshipMe tadata)        
373                    {        
374                         isManyToMa ny = false ;        
375                         currentOne ToManyRela tionship =  entityRel ationship  as OneToMa nyRelation shipMetada ta;        
376                         entity2 =  GetEntityM etadata(ar eReferenci ngRelation ships ? cu rrentOneTo ManyRelati onship.Ref erencingEn tity : cur rentOneToM anyRelatio nship.Refe rencedEnti ty);        
377                         attribute2  = GetAttr ibuteMetad ata(entity 2, areRefe rencingRel ationships  ? current OneToManyR elationshi p.Referenc ingAttribu te : curre ntOneToMan yRelations hip.Refere ncedAttrib ute);        
378                         attribute  = GetAttri buteMetada ta(entity,  areRefere ncingRelat ionships ?  currentOn eToManyRel ationship. Referenced Attribute  : currentO neToManyRe lationship .Referenci ngAttribut e);        
379                         metadataID  = current OneToManyR elationshi p.Metadata Id.Value;        
380                    }        
381                    // V erify rela tionship i s either M anyToManyM etadata or  OneToMany Metadata        
382                    if ( entity2 !=  null)        
383                    {        
384                         if (_proce ssedRelati onships.Co ntains(met adataID))        
385                         {        
386                             // Ski p relation ships we h ave alread y drawn        
387                             contin ue;        
388                         }        
389                         else        
390                         {        
391                             // Rec ord we are  drawing t his relati onship        
392                             _proce ssedRelati onships.Ad d(metadata ID);        
393          
394                             // Def ine conven ience vari ables base d upon the  direction  of refere ncing with  respect t o the core  entity.        
395                             VisioA pi.Shape r ect2;        
396          
397          
398                             // Do  not draw r elationshi ps involvi ng the ent ity itself , SystemUs er, Busine ssUnit,        
399                             // or  those that  are inten tionally e xcluded.        
400                             if (St ring.Compa re(entity2 .LogicalNa me, "syste muser", tr ue) != 0 & &        
401                                 St ring.Compa re(entity2 .LogicalNa me, "busin essunit",  true) != 0  &&        
402                                 St ring.Compa re(entity2 .LogicalNa me, rect.N ame, true)  != 0 &&        
403                                 St ring.Compa re(entity. LogicalNam e, "system user", tru e) != 0 &&        
404                                 St ring.Compa re(entity. LogicalNam e, "busine ssunit", t rue) != 0  &&        
405                                 !_ excludedEn tityTable. ContainsKe y(entity2. LogicalNam e.GetHashC ode()) &&        
406                            !_exclu dedRelatio nsTable.Co ntainsKey( attribute. LogicalNam e.GetHashC ode()))        
407                             {        
408                                 //  Either fi nd or crea te a shape  that repr esents thi s secondar y entity,  and add th e name of        
409                                 //  the invol ved attrib ute to the  shape's t ext.        
410                                 tr y        
411                                 {        
412                                      rect2 =  rect.Conta iningPage. Shapes.get _ItemU(ent ity2.Schem aName);        
413          
414                                      if (rect 2.Text.Ind exOf(attri bute2.Sche maName) ==  -1)        
415                                      {        
416                                          rect 2.get_Cell sSRC(VISIO _SECTION_O JBECT_INDE X, (short) VisioApi.V isRowIndic es.visRowX FormOut, ( short)Visi oApi.VisCe llIndices. visXFormHe ight).Resu ltIU += 0. 25;        
417                                          rect 2.Text +=  "\n" + att ribute2.Sc hemaName;        
418          
419                                          // I f the attr ibute is a  primary k ey for the  entity, a ppend a [P K] label t o the attr ibute name  to indica te this.        
420                                          if ( String.Com pare(entit y2.Primary IdAttribut e, attribu te2.Logica lName) ==  0)        
421                                          {        
422                                               rect2.Text  += "  [PK ]";        
423                                          }        
424                                      }        
425                                 }        
426                                 ca tch (Syste m.Runtime. InteropSer vices.COME xception)        
427                                 {        
428                                      rect2 =  DrawEntity Rectangle( rect.Conta iningPage,  entity2.S chemaName,  entity2.O wnershipTy pe.Value);        
429                                      rect2.Te xt += "\n"  + attribu te2.Schema Name;        
430          
431                                      // If th e attribut e is a pri mary key f or the ent ity, appen d a [PK] l abel to th e attribut e name to  indicate s o.        
432                                      if (Stri ng.Compare (entity2.P rimaryIdAt tribute, a ttribute2. LogicalNam e) == 0)        
433                                      {        
434                                          rect 2.Text +=  "  [PK]";        
435                                      }        
436                                 }        
437          
438                                 //  Add the n ame of the  involved  attribute  to the cor e entity's  text, if  not alread y present.        
439                                 if  (rect.Tex t.IndexOf( attribute. SchemaName ) == -1)        
440                                 {        
441                                      rect.get _CellsSRC( VISIO_SECT ION_OJBECT _INDEX, (s hort)Visio Api.VisRow Indices.vi sRowXFormO ut, (short )VisioApi. VisCellInd ices.visXF ormHeight) .ResultIU  += HEIGHT;        
442                                      rect.Tex t += "\n"  + attribut e.SchemaNa me;        
443          
444                                      // If th e attribut e is a pri mary key f or the ent ity, appen d a [PK] l abel to th e attribut e name to  indicate s o.        
445                                      if (Stri ng.Compare (entity.Pr imaryIdAtt ribute, at tribute.Lo gicalName)  == 0)        
446                                      {        
447                                          rect .Text += "   [PK]";        
448                                      }        
449                                 }        
450          
451                                 //  Update th e style of  the entit y name        
452                                 Vi sioApi.Cha racters ch aracters =  rect.Char acters;        
453                                 Vi sioApi.Cha racters ch aracters2  = rect2.Ch aracters;        
454                                        
455                                 // set the fo nt family  of the tex t to segoe  for the v isio 2013.        
456                                 if  (VersionN ame == "15 .0")        
457                                 {        
458                                      characte rs.set_Cha rProps((sh ort)VisioA pi.VisCell Indices.vi sCharacter Font, (sho rt)FONT_ST YLE);        
459                                      characte rs2.set_Ch arProps((s hort)Visio Api.VisCel lIndices.v isCharacte rFont, (sh ort)FONT_S TYLE);        
460                                 }        
461                                 sw itch (enti ty2.Owners hipType)        
462                                 {        
463                                      case Own ershipType s.Business Owned:        
464                                          // s et the fon t color of  the text        
465                                          char acters.set _CharProps ((short)Vi sioApi.Vis CellIndice s.visChara cterColor,  (short)Vi sioApi.Vis DefaultCol ors.visBla ck);        
466                                          char acters2.se t_CharProp s((short)V isioApi.Vi sCellIndic es.visChar acterColor , (short)V isioApi.Vi sDefaultCo lors.visBl ack);        
467                                          brea k;        
468                                      case Own ershipType s.Organiza tionOwned:        
469                                          // s et the fon t color of  the text        
470                                          char acters.set _CharProps ((short)Vi sioApi.Vis CellIndice s.visChara cterColor,  (short)Vi sioApi.Vis DefaultCol ors.visBla ck);        
471                                          char acters2.se t_CharProp s((short)V isioApi.Vi sCellIndic es.visChar acterColor , (short)V isioApi.Vi sDefaultCo lors.visBl ack);        
472                                          brea k;        
473                                      case Own ershipType s.UserOwne d:        
474                                          // s et the fon t color of  the text        
475                                          char acters.set _CharProps ((short)Vi sioApi.Vis CellIndice s.visChara cterColor,  (short)Vi sioApi.Vis DefaultCol ors.visWhi te);        
476                                          char acters2.se t_CharProp s((short)V isioApi.Vi sCellIndic es.visChar acterColor , (short)V isioApi.Vi sDefaultCo lors.visWh ite);        
477                                          brea k;        
478                                      default:        
479                                          brea k;        
480                                 }        
481          
482                                 //  Draw the  directiona l, dynamic  connector  between t he two ent ity shapes .        
483                                 if  (areRefer encingRela tionships)        
484                                 {        
485                                      DrawDire ctionalDyn amicConnec tor(rect,  rect2, isM anyToMany) ;        
486                                 }        
487                                 el se        
488                                 {        
489                                      DrawDire ctionalDyn amicConnec tor(rect2,  rect, isM anyToMany) ;        
490                                 }        
491                             }        
492                             else        
493                             {        
494                                 De bug.WriteL ine(String .Format("< {0} - {1}>  not drawn .", rect.N ame, entit y2.Logical Name), "Re lationship ");        
495                             }        
496                         }        
497                    }        
498                }        
499           }        
500          
501           // / <summary >        
502           // / Draw an  "Entity" R ectangle        
503           // / </summar y>        
504           // / <param n ame="page" >The Page  on which t o draw</pa ram>        
505           // / <param n ame="entit yName">The  name of t he entity< /param>        
506           // / <param n ame="owner ship">The  ownership  type of th e entity</ param>        
507           // / <returns >The newly  drawn rec tangle</re turns>        
508           pr ivate Visi oApi.Shape  DrawEntit yRectangle (VisioApi. Page page,  string en tityName,  OwnershipT ypes owner ship)        
509           {        
510                VisioApi .Shape rec t = page.D rawRectang le(X_POS1,  Y_POS1, X _POS2, Y_P OS2);        
511                rect.Nam e = entity Name;        
512                rect.Tex t = entity Name + " " ;        
513          
514                // Deter mine the s hape fill  color base d on entit y ownershi p.        
515                string f illColor;        
516          
517                // Updat e the styl e of the e ntity name        
518                VisioApi .Character s characte rs = rect. Characters ;        
519                characte rs.Begin =  0;        
520                characte rs.End = e ntityName. Length;        
521                characte rs.set_Cha rProps((sh ort)VisioA pi.VisCell Indices.vi sCharacter Style, (sh ort)VisioA pi.VisCell Vals.visBo ld);        
522                characte rs.set_Cha rProps((sh ort)VisioA pi.VisCell Indices.vi sCharacter Size, NAME _CHARACTER _SIZE);        
523                //set th e font fam ily of the  text to s egoe for t he visio 2 013.        
524                if (Vers ionName ==  "15.0")        
525                characte rs.set_Cha rProps((sh ort)VisioA pi.VisCell Indices.vi sCharacter Font, (sho rt)FONT_ST YLE);         
526                     
527                switch ( ownership)        
528                {        
529                    case  Ownership Types.Busi nessOwned:                             
530                         fillColor  = "RGB(255 ,140,0)";  // orange        
531                         characters .set_CharP rops((shor t)VisioApi .VisCellIn dices.visC haracterCo lor, (shor t)VisioApi .VisDefaul tColors.vi sBlack);//  set the f ont color  of the tex t        
532                         break;        
533                    case  Ownership Types.Orga nizationOw ned:                              
534                         fillColor  = "RGB(127 , 186, 0)" ; // green        
535                         characters .set_CharP rops((shor t)VisioApi .VisCellIn dices.visC haracterCo lor, (shor t)VisioApi .VisDefaul tColors.vi sBlack);//  set the f ont color  of the tex t        
536                         break;        
537                    case  Ownership Types.User Owned:                              
538                         fillColor  = "RGB(0,2 4,143)"; / / blue         
539                         characters .set_CharP rops((shor t)VisioApi .VisCellIn dices.visC haracterCo lor, (shor t)VisioApi .VisDefaul tColors.vi sWhite);//  set the f ont color  of the tex t        
540                         break;        
541                    defa ult:        
542                         fillColor  = "RGB(255 ,255,255)" ; // White        
543                         characters .set_CharP rops((shor t)VisioApi .VisCellIn dices.visC haracterCo lor, (shor t)VisioApi .VisDefaul tColors.vi sDarkBlue) ;// set th e font col or of the  text        
544                         break;        
545                }        
546          
547                // Set t he fill co lor, place ment prope rties, and  line weig ht of the  shape.        
548                rect.get _CellsSRC( VISIO_SECT ION_OJBECT _INDEX, (s hort)Visio Api.VisRow Indices.vi sRowMisc,  (short)Vis ioApi.VisC ellIndices .visLOFlag s).Formula U = ((int) VisioApi.V isCellVals .visLOFlag sPlacable) .ToString( );        
549                rect.get _CellsSRC( VISIO_SECT ION_OJBECT _INDEX, (s hort)Visio Api.VisRow Indices.vi sRowFill,  (short)Vis ioApi.VisC ellIndices .visFillFo regnd).For mulaU = fi llColor;                     
550                return r ect;        
551           }        
552          
553           // / <summary >        
554           // / Draw a d irectional , dynamic  connector  between tw o entities , represen ting an en tity relat ionship.        
555           // / </summar y>        
556           // / <param n ame="shape From">Shap e initiati ng the rel ationship< /param>        
557           // / <param n ame="shape To">Shape  referenced  by the re lationship </param>        
558           // / <param n ame="isMan yToMany">W hether or  not it is  a many-to- many entit y relation ship</para m>        
559           pr ivate void  DrawDirec tionalDyna micConnect or(VisioAp i.Shape sh apeFrom, V isioApi.Sh ape shapeT o, bool is ManyToMany )        
560           {        
561                // Add a  dynamic c onnector t o the page .        
562                VisioApi .Shape con nectorShap e = shapeF rom.Contai ningPage.D rop(_appli cation.Con nectorTool DataObject , 0.0, 0.0 );        
563          
564                // Set t he connect or propert ies, using  different  arrows, c olors, and  patterns  for many-t o-many rel ationships .        
565                connecto rShape.get _CellsSRC( VISIO_SECT ION_OJBECT _INDEX, (s hort)Visio Api.VisRow Indices.vi sRowFill,  (short)Vis ioApi.VisC ellIndices .visFillSh dwPattern) .ResultIU  = SHDW_PAT TERN;        
566                connecto rShape.get _CellsSRC( VISIO_SECT ION_OJBECT _INDEX, (s hort)Visio Api.VisRow Indices.vi sRowLine,  (short)Vis ioApi.VisC ellIndices .visLineBe ginArrow). ResultIU =  isManyToM any ? BEGI N_ARROW_MA NY : BEGIN _ARROW;        
567                connecto rShape.get _CellsSRC( VISIO_SECT ION_OJBECT _INDEX, (s hort)Visio Api.VisRow Indices.vi sRowLine,  (short)Vis ioApi.VisC ellIndices .visLineEn dArrow).Re sultIU = E ND_ARROW;        
568                connecto rShape.get _CellsSRC( VISIO_SECT ION_OJBECT _INDEX, (s hort)Visio Api.VisRow Indices.vi sRowLine,  (short)Vis ioApi.VisC ellIndices .visLineCo lor).Resul tIU = isMa nyToMany ?  LINE_COLO R_MANY : L INE_COLOR;        
569                connecto rShape.get _CellsSRC( VISIO_SECT ION_OJBECT _INDEX, (s hort)Visio Api.VisRow Indices.vi sRowLine,  (short)Vis ioApi.VisC ellIndices .visLinePa ttern).Res ultIU = is ManyToMany  ? LINE_PA TTERN : LI NE_PATTERN ;        
570                connecto rShape.get _CellsSRC( VISIO_SECT ION_OJBECT _INDEX, (s hort)Visio Api.VisRow Indices.vi sRowFill,  (short)Vis ioApi.VisC ellIndices .visLineRo unding).Re sultIU = R OUNDING;        
571          
572                // Conne ct the sta rting poin t.        
573                VisioApi .Cell cell BeginX = c onnectorSh ape.get_Ce llsSRC(VIS IO_SECTION _OJBECT_IN DEX, (shor t)VisioApi .VisRowInd ices.visRo wXForm1D,  (short)Vis ioApi.VisC ellIndices .vis1DBegi nX);        
574                cellBegi nX.GlueTo( shapeFrom. get_CellsS RC(VISIO_S ECTION_OJB ECT_INDEX,  (short)Vi sioApi.Vis RowIndices .visRowXFo rmOut, (sh ort)VisioA pi.VisCell Indices.vi sXFormPinX ));        
575          
576                // Conne ct the end ing point.        
577                VisioApi .Cell cell EndX = con nectorShap e.get_Cell sSRC(VISIO _SECTION_O JBECT_INDE X, (short) VisioApi.V isRowIndic es.visRowX Form1D, (s hort)Visio Api.VisCel lIndices.v is1DEndX);        
578                cellEndX .GlueTo(sh apeTo.get_ CellsSRC(V ISIO_SECTI ON_OJBECT_ INDEX, (sh ort)VisioA pi.VisRowI ndices.vis RowXFormOu t, (short) VisioApi.V isCellIndi ces.visXFo rmPinX));        
579           }        
580          
581           // / <summary >        
582           // / Retrieve s an entit y from the  local cop y of CRM M etadata        
583           // / </summar y>        
584           // / <param n ame="entit yName">The  name of t he entity  to find</p aram>        
585           // / <returns >NULL if t he entity  was not fo und, other wise the e ntity's me tadata</re turns>        
586           pr ivate Enti tyMetadata  GetEntity Metadata(s tring enti tyName)        
587           {        
588                foreach  (EntityMet adata md i n _metadat aResponse. EntityMeta data)        
589                {        
590                    if ( md.Logical Name == en tityName)        
591                    {        
592                         return md;        
593                    }        
594                }        
595          
596                return n ull;        
597           }        
598          
599           // / <summary >        
600           // / Retrieve s an attri bute from  an EntityM etadata ob ject        
601           // / </summar y>        
602           // / <param n ame="entit y">The ent ity metada ta that co ntains the  attribute </param>        
603           // / <param n ame="attri buteName"> The name o f the attr ibute to f ind</param >        
604           // / <returns >NULL if t he attribu te was not  found, ot herwise th e attribut e's metada ta</return s>        
605           pr ivate Attr ibuteMetad ata GetAtt ributeMeta data(Entit yMetadata  entity, st ring attri buteName)        
606           {        
607                foreach  (Attribute Metadata a ttrib in e ntity.Attr ibutes)        
608                {        
609                    if ( attrib.Log icalName = = attribut eName)        
610                    {        
611                         return att rib;        
612                    }        
613                }        
614          
615                return n ull;        
616           }        
617       }        
618   }