354. Araxis Merge File Comparison Report

Produced by Araxis Merge on 2/1/2017 2:56:31 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.

354.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\DataManagement\DuplicateDetection EnableDuplicateDetectionAndRetrieveDuplicates.cs Tue Dec 20 19:51:43 2016 UTC
2 Wed Feb 1 19:56:31 2017 UTC

354.2 Comparison summary

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

354.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

354.4 Active regular expressions

No regular expressions were active.

354.5 Comparison detail

1   // ======= ========== ========== ========== ========== ========== ========== ==        
2   //  This f ile is par t of the M icrosoft D ynamics CR M SDK code  samples.        
3   //        
4   //  Copyri ght (C) Mi crosoft Co rporation.   All righ ts reserve d.        
5   //        
6   //  This s ource code  is intend ed only as  a supplem ent to Mic rosoft        
7   //  Develo pment Tool s and/or o n-line doc umentation .  See the se other        
8   //  materi als for de tailed inf ormation r egarding M icrosoft c ode sample s.        
9   //        
10   //  THIS C ODE AND IN FORMATION  ARE PROVID ED "AS IS"  WITHOUT W ARRANTY OF  ANY        
11   //  KIND,  EITHER EXP RESSED OR  IMPLIED, I NCLUDING B UT NOT LIM ITED TO TH E        
12   //  IMPLIE D WARRANTI ES OF MERC HANTABILIT Y AND/OR F ITNESS FOR  A        
13   //  PARTIC ULAR PURPO SE.        
14   // ======= ========== ========== ========== ========== ========== ========== ==        
15          
16   //<snippet EnableDupl icateDetec tionAndRet rieveDupli cates>        
17   using Syst em;        
18   using Syst em.Collect ions.Gener ic;        
19   using Syst em.Service Model;        
20   using Micr osoft.Crm. Sdk.Messag es;        
21   using Micr osoft.Xrm. Sdk;        
22   using Micr osoft.Xrm. Sdk.Client ;        
23   using Micr osoft.Xrm. Sdk.Messag es;        
24   using Micr osoft.Xrm. Sdk.Query;        
25          
26   namespace  Microsoft. Crm.Sdk.Sa mples        
27   {        
28       /// <s ummary>        
29       /// Th is sample  shows how  to enable  duplicate  detection  and retrie ve duplica te        
30       /// re cords base d on the a ctive dupl icate dete ction rule (s).        
31       /// </ summary>        
32       /// <r emarks>        
33       /// At  run-time,  you will  be given t he option  to delete  all the        
34       /// da tabase rec ords creat ed by this  program.        
35       /// </ remarks>        
36       public  class Ena bleDuplica teDetectio nAndRetrie veDuplicat es        
37       {        
38           #r egion Clas s Level Me mbers        
39           pr ivate Orga nizationSe rviceProxy  _serviceP roxy;        
40           pr ivate Guid ? _account Id1;        
41           pr ivate Guid ? _account Id2;        
42           #e ndregion        
43          
44           #r egion How  To Sample  Code        
45          
46           // / <summary >        
47           // / Enables  dupe detec tion and r etrieves d uplicates.          
48           // / </summar y>        
49           // / <param n ame="serve rConfig">C ontains se rver conne ction info rmation.</ param>        
50           // / <param n ame="promp tforDelete ">When Tru e, the use r will be  prompted t o delete a ll        
51           // / created  entities.< /param>        
52           pu blic void  Run(Server Connection .Configura tion serve rConfig,bo ol promptf orDelete)        
53           {        
54                using (_ servicePro xy = new O rganizatio nServicePr oxy(server Config.Org anizationU ri, server Config.Hom eRealmUri, serverConf ig.Credent ials, serv erConfig.D eviceCrede ntials))        
55                {        
56                    // T his statem ent is req uired to e nable earl y-bound ty pe support .        
57                    _ser viceProxy. EnableProx yTypes();        
58                    Enab leDuplicat eDetection ForOrg();        
59                    Enab leDuplicat eDetection ForEntity( Account.En tityLogica lName);        
60                    Publ ishRulesFo rEntity(Ac count.Enti tyLogicalN ame);        
61                    Crea teAccountR ecords();        
62                    Retr ieveDuplic ates();        
63                    Dele teRequired Records(pr omptforDel ete);        
64                }        
65           }        
66          
67           // / <summary >        
68           // / Create s ome accoun t records  to retriev e duplicat es        
69           // / </summar y>        
70           pr ivate void  CreateAcc ountRecord s()        
71           {        
72                var crmA ccount = n ew Account  { Name="M icrosoft"} ;        
73                         
74                _account Id1 = _ser viceProxy. Create(crm Account);        
75                _account Id2 = _ser viceProxy. Create(crm Account);        
76                Console. WriteLine( String.Con cat("Creat ing duplic ate record s:\n\tacco unt 1 - ",        
77                    _acc ountId1.Va lue, "\n\t account 2  - ", _acco untId2.Val ue));        
78           }        
79          
80           // / <summary >        
81           // / Call the  method to  retrieve  duplicate  records.          
82           // / </summar y>        
83           pr ivate void  RetrieveD uplicates( )        
84           {        
85                // Pagin gInfo is R equired.         
86                //<snipp etRetrieve Duplicates Request>        
87                var requ est = new  RetrieveDu plicatesRe quest        
88                {        
89                    Busi nessEntity  = new Acc ount { Nam e = "Micro soft" }.To Entity<Ent ity>(),        
90                    Matc hingEntity Name = Acc ount.Entit yLogicalNa me,        
91                    Pagi ngInfo = n ew PagingI nfo() { Pa geNumber =  1, Count  = 50 }        
92                };        
93          
94                Console. WriteLine( "Retrievin g duplicat es");        
95                var resp onse =(Ret rieveDupli catesRespo nse)_servi ceProxy.Ex ecute(requ est);        
96                //</snip petRetriev eDuplicate sRequest>        
97          
98                for (int  i = 0; i  < response .Duplicate Collection .Entities. Count; i++ )        
99                {        
100                    var  crmAccount  = respons e.Duplicat eCollectio n.Entities [i]        
101                         .ToEntity< Account>() ;        
102                    Cons ole.WriteL ine(crmAcc ount.Name  + ", " + c rmAccount. AccountId. Value.ToSt ring());         
103                }        
104           }        
105          
106           // / <summary >        
107           // / Enables  duplicate  detection  for the or ganization        
108           // / </summar y>        
109           pr ivate void  EnableDup licateDete ctionForOr g()        
110           {        
111                // Retri eve the or g ID        
112                var orgI d = Retrie veOrganiza tionId();        
113                if (!org Id.HasValu e)        
114                    retu rn;        
115          
116                Console. WriteLine( String.Con cat("Enabl ing duplic ate detect ion for or ganization : ",         
117                    orgI d.Value));        
118          
119                // Enabl e dupe det ection for  each type        
120                var crmO rganizatio n = new Or ganization        
121                {        
122                    Id =  orgId.Val ue,        
123                    IsDu plicateDet ectionEnab led = true ,        
124                    IsDu plicateDet ectionEnab ledForImpo rt = true,        
125                    IsDu plicateDet ectionEnab ledForOffl ineSync =  true,        
126                    IsDu plicateDet ectionEnab ledForOnli neCreateUp date = tru e,        
127                };        
128          
129                _service Proxy.Upda te(crmOrga nization);        
130           }        
131          
132           // / <summary >        
133           // / Enabling  the dupe  detection  unpublishe s the rule s.          
134           // / This wil l publish  them, and  wait for t hem to com plete publ ishing.        
135           // / </summar y>        
136           // / <param n ame="entit yName"></p aram>        
137           pr ivate void  PublishRu lesForEnti ty(string  entityName )        
138           {        
139                //<snipp etPublishD uplicateRu le>        
140                // Retri eve all ru les for th e entity        
141                var rule s = _servi ceProxy.Re trieveMult iple(        
142                    new  QueryByAtt ribute(Dup licateRule .EntityLog icalName)        
143                {        
144                    Colu mnSet = ne w ColumnSe t("duplica teruleid") ,        
145                    Attr ibutes = {  "matching entityname " },        
146                    Valu es = { ent ityName }        
147                });        
148          
149                List<Gui d> crmAsyn cOperation Ids = new  List<Guid> ();        
150                foreach  (var item  in rules.E ntities)        
151                {        
152                    Cons ole.WriteL ine(String .Concat("P ublishing  duplicate  rule: ", i tem.Id));        
153          
154                    // P ublish eac h rule and  get the j ob id sinc e it is as ync        
155                    var  response =  (PublishD uplicateRu leResponse )_serviceP roxy.Execu te(        
156                             new Pu blishDupli cateRuleRe quest { Du plicateRul eId = item .Id });        
157          
158                    crmA syncOperat ionIds.Add (response. JobId);        
159                }        
160                //</snip petPublish DuplicateR ule>        
161          
162                // Wait  until all  the rules  are publis hed before  testing t he dupe de tection        
163                WaitForA syncJobCom pletion(cr mAsyncOper ationIds);        
164           }        
165          
166           // / <summary >        
167           // / Updates  the entity  customiza tions and  publishes  the entity          
168           // / </summar y>        
169           // / <param n ame="entit yName"></p aram>        
170           pr ivate void  EnableDup licateDete ctionForEn tity(strin g entityNa me)        
171           {        
172                Console. WriteLine( String.For mat("Retri eving enti ty metadat a for {0}" ,        
173                    enti tyName));        
174          
175                // Retri eve the en tity metad ata        
176                var crmE ntity = (( RetrieveEn tityRespon se)_servic eProxy.Exe cute(        
177                    new  RetrieveEn tityReques t        
178                    {        
179                         RetrieveAs IfPublishe d = true,        
180                         LogicalNam e = entity Name        
181                    })). EntityMeta data;        
182          
183                Console. WriteLine( String.Con cat("Enabl ing duplic ate for ",  entityNam e));        
184          
185                // Updat e the dupl icate dete ction flag        
186                crmEntit y.IsDuplic ateDetecti onEnabled         
187                    new  BooleanMan agedProper ty(true);        
188          
189                // Updat e the enti ty metadat a        
190                _service Proxy.Exec ute(new Up dateEntity Request        
191                {        
192                    Enti ty = crmEn tity        
193                });        
194          
195                Console. WriteLine( String.Con cat("Publi shing ", e ntityName,  " entity" ));        
196          
197                // Publi sh the ent ity         
198                var publ ishRequest  = new Pub lishXmlReq uest        
199                {                       
200                    Para meterXml =  String.Co ncat("<imp ortexportx ml><entiti es><entity >",        
201                         entityName , "</entit y></entiti es></impor texportxml >"),        
202                };        
203          
204                _service Proxy.Exec ute(publis hRequest);        
205           }        
206          
207           // / <summary >        
208           // / There sh ould only  be one org anization  record per  Crm Org        
209           // / </summar y>        
210           // / <returns ></returns >        
211           pr ivate Guid ? Retrieve Organizati onId()        
212           {            
213                // Retri eve the fi rst record  in the or ganization  table.          
214                // There  should on ly be one  organizati on record.          
215                var enti ties = _se rviceProxy .RetrieveM ultiple(        
216                    new  QueryExpre ssion(Orga nization.E ntityLogic alName)        
217                    {        
218                         ColumnSet  = new Colu mnSet("org anizationi d"),        
219                         PageInfo =  new Pagin gInfo { Pa geNumber =  1, Count  = 1 },        
220                    });        
221          
222                if (enti ties != nu ll && enti ties.Entit ies.Count  > 0)        
223                    retu rn entitie s.Entities [0].Id;        
224          
225                return n ull;        
226           }        
227                   
228           // / <summary >        
229           //        
230           // / </summar y>        
231           // / <param n ame="promp t"></param >        
232           pr ivate void  DeleteReq uiredRecor ds(bool pr ompt)        
233           {        
234                bool toB eDeleted =  true;        
235          
236                if (prom pt)        
237                {        
238                    // A sk the use r if the c reated ent ities shou ld be dele ted.        
239                    Cons ole.Write( "\nDo you  want these  entity re cords dele ted? (y/n)  [y]: ");        
240                    Stri ng answer  = Console. ReadLine() ;        
241                    if ( answer.Sta rtsWith("y ") ||        
242                         answer.Sta rtsWith("Y ") ||        
243                         answer ==  String.Emp ty)        
244                    {        
245                         toBeDelete d = true;        
246                    }        
247                    else        
248                    {        
249                         toBeDelete d = false;        
250                    }        
251                }        
252          
253                if (toBe Deleted)        
254                {        
255                    // D elete reco rds create d in this  sample.        
256                    if ( _accountId 1.HasValue )        
257                    {        
258                         Console.Wr iteLine(St ring.Conca t("Deletin g account:  ", _accou ntId1.Valu e));        
259                         _servicePr oxy.Delete (Account.E ntityLogic alName, _a ccountId1. Value);        
260                    }        
261                    if ( _accountId 2.HasValue )        
262                    {        
263                         Console.Wr iteLine(St ring.Conca t("Deletin g account:  ", _accou ntId2.Valu e));         
264                         _servicePr oxy.Delete (Account.E ntityLogic alName, _a ccountId2. Value);        
265                    }        
266                    Cons ole.WriteL ine("Entit y records  have been  deleted.") ;        
267                }        
268           }        
269          
270           // / <summary >        
271           // / Waits fo r async jo b to compl ete        
272           // / </summar y>        
273           // / <param n ame="async JobId"></p aram>        
274           pu blic void  WaitForAsy ncJobCompl etion(IEnu merable<Gu id> asyncJ obIds)        
275           {        
276                List<Gui d> asyncJo bList = ne w List<Gui d>(asyncJo bIds);        
277                ColumnSe t cs = new  ColumnSet ("statecod e", "async operationi d");        
278                int retr yCount = 1 00;        
279          
280                while (a syncJobLis t.Count !=  0 && retr yCount > 0 )        
281                {        
282                    // R etrieve th e async op erations b ased on th e ids        
283                    var  crmAsyncJo bs = _serv iceProxy.R etrieveMul tiple(        
284                         new QueryE xpression( "asyncoper ation")        
285                         {        
286                             Column Set = cs,        
287                             Criter ia = new F ilterExpre ssion        
288                             {        
289                                 Co nditions =          
290                                 {        
291                                      new Cond itionExpre ssion("asy ncoperatio nid",        
292                                          Cond itionOpera tor.In, as yncJobList .ToArray() )        
293                                 }        
294                             }        
295                         });        
296          
297                    // C heck to se e if the o perations  are comple ted and if  so remove  them from  the Async  Guid list        
298                    fore ach (var i tem in crm AsyncJobs. Entities)        
299                         {        
300                         var crmAsy ncJob = it em.ToEntit y<AsyncOpe ration>();        
301                         if (crmAsy ncJob.Stat eCode.HasV alue &&         
302                             crmAsy ncJob.Stat eCode.Valu e == Async OperationS tate.Compl eted)        
303                             asyncJ obList.Rem ove(crmAsy ncJob.Asyn cOperation Id.Value);        
304          
305                         Console.Wr iteLine(St ring.Conca t("Async o peration s tate is ",        
306                             crmAsy ncJob.Stat eCode.Valu e.ToString (),         
307                             ", asy nc operati on id: ",  crmAsyncJo b.AsyncOpe rationId.V alue.ToStr ing()));        
308                         }        
309          
310                    // I f there ar e still jo bs remaini ng, sleep  the thread .        
311                    if ( asyncJobLi st.Count >  0)        
312                         System.Thr eading.Thr ead.Sleep( 2000);        
313                            
314                    retr yCount--;                    
315                }        
316          
317                if (retr yCount ==  0 && async JobList.Co unt > 0)        
318                {        
319                    for  (int i = 0 ; i < asyn cJobList.C ount; i++)        
320                    {        
321                         Console.Wr iteLine(St ring.Conca t(        
322                             "The f ollowing a sync opera tion has n ot complet ed: ",        
323                             asyncJ obList[i]. ToString() ));        
324                    }        
325                }        
326           }        
327          
328           #e ndregion        
329          
330           #r egion Main  method        
331           // / <summary >        
332           // / Standard  Main() me thod used  by most SD K samples.        
333           // / </summar y>        
334           // / <param n ame="args" ></param>        
335           st atic publi c void Mai n(string[]  args)        
336           {        
337                try        
338                {        
339                    // O btain the  target org anization' s Web addr ess and cl ient logon          
340                    // c redentials  from the  user.        
341                    Serv erConnecti on serverC onnect = n ew ServerC onnection( );        
342                    Serv erConnecti on.Configu ration con fig = serv erConnect. GetServerC onfigurati on();        
343          
344                    var  app = new  EnableDupl icateDetec tionAndRet rieveDupli cates();        
345                    app. Run(config , true);        
346                }        
347                catch (F aultExcept ion<Micros oft.Xrm.Sd k.Organiza tionServic eFault> ex )        
348                {        
349                    Cons ole.WriteL ine("The a pplication  terminate d with an  error.");        
350                    Cons ole.WriteL ine("Times tamp: {0}" , ex.Detai l.Timestam p);        
351                    Cons ole.WriteL ine("Code:  {0}", ex. Detail.Err orCode);        
352                    Cons ole.WriteL ine("Messa ge: {0}",  ex.Detail. Message);        
353                    Cons ole.WriteL ine("Plugi n Trace: { 0}", ex.De tail.Trace Text);        
354                    Cons ole.WriteL ine("Inner  Fault: {0 }",        
355                         null == ex .Detail.In nerFault ?  "No Inner  Fault" :  "Has Inner  Fault");        
356                }        
357                catch (S ystem.Time outExcepti on ex)        
358                {        
359                    Cons ole.WriteL ine("The a pplication  terminate d with an  error.");        
360                    Cons ole.WriteL ine("Messa ge: {0}",  ex.Message );        
361                    Cons ole.WriteL ine("Stack  Trace: {0 }", ex.Sta ckTrace);        
362                    Cons ole.WriteL ine("Inner  Fault: {0 }",        
363                         null == ex .InnerExce ption.Mess age ? "No  Inner Faul t" : ex.In nerExcepti on.Message );        
364                }        
365                catch (S ystem.Exce ption ex)        
366                {        
367                    Cons ole.WriteL ine("The a pplication  terminate d with an  error.");        
368                    Cons ole.WriteL ine(ex.Mes sage);        
369          
370                    // D isplay the  details o f the inne r exceptio n.        
371                    if ( ex.InnerEx ception !=  null)        
372                    {        
373                         Console.Wr iteLine(ex .InnerExce ption.Mess age);        
374          
375                         FaultExcep tion<Micro soft.Xrm.S dk.Organiz ationServi ceFault> f e = ex.Inn erExceptio n        
376                             as Fau ltExceptio n<Microsof t.Xrm.Sdk. Organizati onServiceF ault>;        
377                         if (fe !=  null)        
378                         {        
379                             Consol e.WriteLin e("Timesta mp: {0}",  fe.Detail. Timestamp) ;        
380                             Consol e.WriteLin e("Code: { 0}", fe.De tail.Error Code);        
381                             Consol e.WriteLin e("Message : {0}", fe .Detail.Me ssage);        
382                             Consol e.WriteLin e("Plugin  Trace: {0} ", fe.Deta il.TraceTe xt);        
383                             Consol e.WriteLin e("Inner F ault: {0}" ,        
384                                 nu ll == fe.D etail.Inne rFault ? " No Inner F ault" : "H as Inner F ault");        
385                         }        
386                    }        
387                }        
388                // Addit ional exce ptions to  catch: Sec urityToken Validation Exception,  ExpiredSe curityToke nException ,        
389                // Secur ityAccessD eniedExcep tion, Mess ageSecurit yException , and Secu rityNegoti ationExcep tion.        
390          
391                finally        
392                {        
393                    Cons ole.WriteL ine("Press  <Enter> t o exit.");        
394                    Cons ole.ReadLi ne();        
395                }        
396           }        
397           #e ndregion        
398       }        
399   }        
400   //</snippe tEnableDup licateDete ctionAndRe trieveDupl icates>