334. Araxis Merge File Comparison Report

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

334.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\Auditing UserAccessAuditing.cs Tue Dec 20 19:51:43 2016 UTC
2 Wed Feb 1 19:56:30 2017 UTC

334.2 Comparison summary

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

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

334.4 Active regular expressions

No regular expressions were active.

334.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   // <snippe tUserAcces sAuditing>        
17   using Syst em;        
18   using Syst em.Service Model;        
19   using Micr osoft.Crm. Sdk.Messag es;        
20   using Micr osoft.Xrm. Sdk;        
21   using Micr osoft.Xrm. Sdk.Client ;        
22   using Micr osoft.Xrm. Sdk.Messag es;        
23   using Micr osoft.Xrm. Sdk.Metada ta;        
24   using Micr osoft.Xrm. Sdk.Query;        
25          
26   namespace  Microsoft. Crm.Sdk.Sa mples        
27   {        
28       public  class Use rAccessAud iting        
29       {        
30           #r egion Clas s Level Me mbers        
31           pr ivate Orga nizationSe rviceProxy  _serviceP roxy;        
32          
33           pr ivate Guid  _newAccou ntId;        
34           pr ivate Guid  _systemUs erId;        
35           pr ivate stat ic DateTim e _sampleS tartTime;        
36          
37           #e ndregion        
38          
39           #r egion How  To Sample  Code        
40          
41           // / <summary >        
42           // / This sam ple demons trates how  to audit  user acces s to Micro soft Dynam ics CRM.        
43           // / The samp le first e nables use r access a uditing on  an organi zation. Ne xt, it        
44           // / creates  and modifi es an enti ty. Finall y, the sam ple displa ys a repor t of the        
45           // / audited  informatio n.        
46           // / </summar y>        
47           // / <param n ame="serve rConfig">C ontains se rver conne ction info rmation.</ param>        
48           // / <param n ame="promp tforDelete ">When Tru e, the use r will be  prompted t o delete a ll        
49           // / created  entities.< /param>        
50           pu blic void  Run(Server Connection .Configura tion serve rConfig, b ool prompt forDelete)        
51           {        
52                _sampleS tartTime =  DateTime. Now;        
53                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))        
54                {        
55                    // T his statem ent is req uired to e nable earl y-bound ty pe support .        
56                    _ser viceProxy. EnableProx yTypes();        
57          
58                    #reg ion Enable  Auditing        
59          
60                    // E nable audi ting on th e organiza tion and f or user ac cess by ed iting the        
61                    // o rganizatio n's settin gs.        
62                    // F irst, get  the organi zation's I D from the  system us er record.        
63                    var  whoAmIReq  = new WhoA mIRequest( );        
64                    var  whoAmIRes  = (WhoAmIR esponse)_s erviceProx y.Execute( whoAmIReq) ;        
65                    Guid  orgId = w hoAmIRes.O rganizatio nId;        
66                    _sys temUserId  = whoAmIRe s.UserId;        
67          
68                    // N ext, retri eve the or ganization 's record.        
69                    var  org = (Org anization) _servicePr oxy.Retrie ve(        
70                         Organizati on.EntityL ogicalName , orgId,        
71                         new Column Set("organ izationid" , "isaudit enabled",  "isuseracc essauditen abled", "u seraccessa uditingint erval"));        
72          
73                    // F inally, en able audit ing on the  organizat ion, inclu ding audit ing for        
74                    // u ser access .        
75                    bool  organizat ionAuditin gFlag = or g.IsAuditE nabled.Val ue;        
76                    bool  userAcces sAuditingF lag = org. IsUserAcce ssAuditEna bled.Value ;        
77                    if ( !organizat ionAuditin gFlag || ! userAccess AuditingFl ag)        
78                    {        
79                         org.IsAudi tEnabled =  true;        
80                         org.IsUser AccessAudi tEnabled =  true;        
81                         _servicePr oxy.Update (org);        
82                         Console.Wr iteLine("E nabled aud iting for  the organi zation and  for user  access.");        
83                         Console.Wr iteLine("A uditing in terval is  set to {0}  hours.",  org.UserAc cessAuditi ngInterval );        
84                    }        
85                    else        
86                    {        
87                         Console.Wr iteLine("A uditing wa s enabled  before the  sample be gan, so no  auditing  settings w ere change d.");        
88                    }        
89          
90                    // E nable audi ting on th e account  entity, si nce no aud its will b e created        
91                    // w hen we cre ate/update  an accoun t entity,  otherwise.        
92                    var  oldAccount Auditing =  EnableEnt ityAuditin g(Account. EntityLogi calName, t rue);        
93          
94                    #end region Ena ble Auditi ng        
95          
96                    #reg ion Make A udited Ser vice Calls        
97          
98                    Crea teRequired Records();        
99          
100                    // M ake an upd ate reques t to the A ccount ent ity to be  tracked by  auditing.        
101                    var  newAccount  = new Acc ount();        
102                    newA ccount.Acc ountId = _ newAccount Id;        
103                    newA ccount.Acc ountNumber  = "1-A";        
104                    newA ccount.Acc ountCatego ryCode = n ew OptionS etValue(        
105                         (int)Accou ntAccountC ategoryCod e.Preferre dCustomer) ;        
106                    newA ccount.Tel ephone1 =  "555-555-5 555";        
107          
108                    _ser viceProxy. Update(new Account);        
109          
110                    Cons ole.WriteL ine("Creat ed an acco unt and ma de updates  which sho uld be cap tured by a uditing.") ;        
111          
112                    #end region Mak e Audited  Service Ca lls        
113          
114                    #reg ion Revert  auditing        
115          
116                    // S et the org anization  and accoun t auditing  flags bac k to the o ld values        
117                    if ( !organizat ionAuditin gFlag || ! userAccess AuditingFl ag)        
118                    {        
119                         // Only re vert them  if they we re actuall y changed  to begin w ith.        
120                         org.IsAudi tEnabled =  organizat ionAuditin gFlag;        
121                         org.IsUser AccessAudi tEnabled =  userAcces sAuditingF lag;        
122                         _servicePr oxy.Update (org);        
123                         Console.Wr iteLine("R everted or ganization  and user  access aud iting to t heir previ ous values .");        
124                    }        
125                    else        
126                    {        
127                         Console.Wr iteLine("A uditing wa s enabled  before the  sample be gan, so no  auditing  settings w ere revert ed.");        
128                    }        
129          
130                    // R evert the  account en tity audit ing.        
131                    Enab leEntityAu diting(Acc ount.Entit yLogicalNa me, oldAcc ountAuditi ng);        
132          
133                    #end region Rev ert auditi ng        
134          
135                    #reg ion Show A udited Rec ords        
136          
137                    // S elect all  columns fo r convenie nce.        
138                    var  query = ne w QueryExp ression(Au dit.Entity LogicalNam e)        
139                    {        
140                         ColumnSet  = new Colu mnSet(true ),        
141                         Criteria =  new Filte rExpressio n(LogicalO perator.An d)        
142                    };        
143          
144                    // O nly retrie ve audit r ecords tha t track us er access.        
145                    quer y.Criteria .AddCondit ion("actio n", Condit ionOperato r.In,        
146                         (int)Audit Action.Use rAccessAud itStarted,        
147                         (int)Audit Action.Use rAccessAud itStopped,        
148                         (int)Audit Action.Use rAccessvia WebService s,        
149                         (int)Audit Action.Use rAccessvia Web);        
150          
151                    // C hange this  to false  in order t o retrieve  audit rec ords for a ll users        
152                    // w hen runnin g the samp le.        
153                    var  filterAudi tsRetrieve dByUser =  true;        
154                    if ( filterAudi tsRetrieve dByUser)        
155                    {        
156                         // Only re trieve aud it records  for the c urrent use r or the " SYSTEM"        
157                         // user.        
158                         var userFi lter = new  FilterExp ression(Lo gicalOpera tor.Or);        
159                         userFilter .AddCondit ion(        
160                             "useri d", Condit ionOperato r.Equal, _ systemUser Id);        
161                         userFilter .AddCondit ion(        
162                             "useri dname", Co nditionOpe rator.Equa l, "SYSTEM ");        
163                    }        
164                    // O nly retrie ve records  for this  sample run , so that  we don't g et too        
165                    // m any result s if audit ing was en abled prev iously.        
166                    quer y.Criteria .AddCondit ion(        
167                         "createdon ", Conditi onOperator .GreaterEq ual, _samp leStartTim e);        
168          
169                    var  results =  _servicePr oxy.Retrie veMultiple (query);        
170                    Cons ole.WriteL ine("Retri eved audit  records:" );        
171                    fore ach (Audit  audit in  results.En tities)        
172                    {        
173                         Console.Wr ite("\r\n   Action: { 0},  User:  {1},"        
174                             + "\r\ n    Creat ed On: {2} , Operatio n: {3}",        
175                             (Audit Action)aud it.Action. Value,        
176                             audit. UserId.Nam e,        
177                             audit. CreatedOn. Value.ToLo calTime(),        
178                             (Audit Operation) audit.Oper ation.Valu e);        
179          
180                         // Display  the name  of the rel ated objec t (which w ill be the  user        
181                         // for aud it records  with Acti on UserAcc essviaWebS ervices.        
182                         if (!Strin g.IsNullOr Empty(audi t.ObjectId .Name))        
183                         {        
184                             Consol e.WriteLin e(        
185                                 ", \r\n    Re lated Reco rd: {0}",  audit.Obje ctId.Name) ;        
186                         }        
187                         else        
188                         {        
189                             Consol e.WriteLin e();        
190                         }        
191                    }        
192          
193                    #end region Sho w Audited  Records        
194          
195                    Dele teRequired Records(pr omptforDel ete);        
196                }        
197           }        
198          
199           // / <summary >        
200           // / Creates  any entity  records t hat this s ample requ ires.        
201           // / </summar y>        
202           pu blic void  CreateRequ iredRecord s()        
203           {        
204                // Creat e a new ac count enti ty.         
205                Account  newAccount  = new Acc ount { Nam e = "Examp le Account " };        
206                _newAcco untId = _s erviceProx y.Create(n ewAccount) ;        
207           }        
208          
209           pr ivate bool  EnableEnt ityAuditin g(String e ntityLogic alName, bo ol flag)        
210           {        
211                // Retri eve the en tity metad ata.        
212                Retrieve EntityRequ est entity Request =  new Retrie veEntityRe quest        
213                {        
214                    Logi calName =  entityLogi calName,        
215                    Enti tyFilters  = EntityFi lters.Attr ibutes        
216                };        
217          
218                Retrieve EntityResp onse entit yResponse  =        
219                    (Ret rieveEntit yResponse) _servicePr oxy.Execut e(entityRe quest);        
220          
221                // Enabl e auditing  on the en tity. By d efault, th is also en ables audi ting        
222                // on al l the enti ty's attri butes.        
223                EntityMe tadata ent ityMetadat a = entity Response.E ntityMetad ata;        
224          
225                bool old Value = en tityMetada ta.IsAudit Enabled.Va lue;        
226                entityMe tadata.IsA uditEnable d = new Bo oleanManag edProperty (flag);        
227          
228                UpdateEn tityReques t updateEn tityReques t = new Up dateEntity Request {  Entity = e ntityMetad ata };        
229          
230                UpdateEn tityRespon se updateE ntityRespo nse =        
231                    (Upd ateEntityR esponse)_s erviceProx y.Execute( updateEnti tyRequest) ;        
232          
233                return o ldValue;        
234           }        
235          
236           // / <summary >        
237           // / Deletes  any entity  records t hat were c reated for  this samp le.        
238           // / <param n ame="promp t">Indicat es whether  to prompt  the user         
239           // / to delet e the reco rds create d in this  sample.</p aram>        
240           // / </summar y>        
241           pu blic void  DeleteRequ iredRecord s(bool pro mpt)        
242           {        
243                bool del eteRecords  = true;        
244          
245                if (prom pt)        
246                {        
247                    Cons ole.WriteL ine("\nDo  you want t o delete t he account  record? ( y/n) [y]:  ");        
248                    Stri ng answer  = Console. ReadLine() ;        
249          
250                    dele teRecords  = (answer. StartsWith ("y") || a nswer.Star tsWith("Y" ) || answe r == Strin g.Empty);        
251                }        
252          
253                if (dele teRecords)        
254                {        
255                    _ser viceProxy. Delete(Acc ount.Entit yLogicalNa me, _newAc countId);        
256                    Cons ole.WriteL ine("The a ccount rec ord has be en deleted .");        
257                }        
258          
259                if (prom pt)        
260                {        
261                    Cons ole.WriteL ine("\nDo  you want t o delete A LL audit r ecords? (y /n) [n]: " );        
262                    Stri ng answer  = Console. ReadLine() ;        
263          
264                    dele teRecords  = (answer. StartsWith ("y") || a nswer.Star tsWith("Y" ));        
265                }        
266          
267                if (dele teRecords)        
268                {        
269                    // G et the lis t of audit  partition s.        
270                    Retr ieveAuditP artitionLi stResponse  partition Request =        
271                         (RetrieveA uditPartit ionListRes ponse)_ser viceProxy. Execute(ne w Retrieve AuditParti tionListRe quest());        
272                    Audi tPartition DetailColl ection par titions =  partitionR equest.Aud itPartitio nDetailCol lection;        
273          
274                    // C reate a de lete reque st with an  end date  earlier th an possibl e.        
275                    Dele teAuditDat aRequest d eleteReque st = new D eleteAudit DataReques t();        
276                    dele teRequest. EndDate =  new DateTi me(2000, 1 , 1);        
277          
278                    // C heck if pa rtitions a re not sup ported as  is the cas e with SQL  Server St andard edi tion.        
279                    if ( partitions .IsLogical Collection )        
280                    {        
281                         // Delete  all audit  records cr eated up u ntil now.        
282                         deleteRequ est.EndDat e = DateTi me.Now;        
283                    }        
284          
285                    // O therwise,  delete all  partition s that are  older tha n the curr ent partit ion.        
286                    // H int: The p artitions  in the col lection ar e returned  in sorted  order whe re the         
287                    // p artition w ith the ol dest end d ate is at  index 0.   Also, if t he partiti on's        
288                    // e nd date is  greater t han the cu rrent date , neither  the partit ion nor an y        
289                    // a udit recor ds contain ed in the  partition  can be del eted.        
290                    else        
291                    {        
292                         for (int n  = partiti ons.Count  - 1; n >=  0; --n)        
293                         {        
294                             if (pa rtitions[n ].EndDate  <= DateTim e.Now && p artitions[ n].EndDate  > deleteR equest.End Date)        
295                             {        
296                                 de leteReques t.EndDate  = (DateTim e)partitio ns[n].EndD ate;        
297                                 br eak;        
298                             }        
299                         }        
300                    }        
301          
302                    // D elete the  audit reco rds.        
303                    if ( deleteRequ est.EndDat e != new D ateTime(20 00, 1, 1))        
304                    {        
305                         _servicePr oxy.Execut e(deleteRe quest);        
306                         Console.Wr iteLine("A udit recor ds have be en deleted .");        
307                    }        
308                    else        
309                         Console.Wr iteLine("T here were  no audit r ecords tha t could be  deleted." );        
310                }        
311           }        
312          
313           #e ndregion H ow To Samp le Code        
314          
315           #r egion Main  method        
316          
317           // / <summary >        
318           // / Standard  Main() me thod used  by most SD K samples.        
319           // / </summar y>        
320           // / <param n ame="args" ></param>        
321           st atic publi c void Mai n(string[]  args)        
322           {        
323                try        
324                {        
325                    // O btain the  target org anization' s Web addr ess and cl ient logon          
326                    // c redentials  from the  user.        
327                    Serv erConnecti on serverC onnect = n ew ServerC onnection( );        
328                    Serv erConnecti on.Configu ration con fig = serv erConnect. GetServerC onfigurati on();        
329          
330                    var  app = new  UserAccess Auditing() ;        
331                    app. Run(config , true);        
332                }        
333          
334                catch (F aultExcept ion<Micros oft.Xrm.Sd k.Organiza tionServic eFault> ex )        
335                {        
336                    Cons ole.WriteL ine("The a pplication  terminate d with an  error.");        
337                    Cons ole.WriteL ine("Times tamp: {0}" , ex.Detai l.Timestam p);        
338                    Cons ole.WriteL ine("Code:  {0}", ex. Detail.Err orCode);        
339                    Cons ole.WriteL ine("Messa ge: {0}",  ex.Detail. Message);        
340                    Cons ole.WriteL ine("Trace : {0}", ex .Detail.Tr aceText);        
341                    Cons ole.WriteL ine("Inner  Fault: {0 }",        
342                         null == ex .Detail.In nerFault ?  "No Inner  Fault" :  "Has Inner  Fault");        
343                }        
344                catch (S ystem.Time outExcepti on ex)        
345                {        
346                    Cons ole.WriteL ine("The a pplication  terminate d with an  error.");        
347                    Cons ole.WriteL ine("Messa ge: {0}",  ex.Message );        
348                    Cons ole.WriteL ine("Stack  Trace: {0 }", ex.Sta ckTrace);        
349                    Cons ole.WriteL ine("Inner  Fault: {0 }",        
350                         null == ex .InnerExce ption.Mess age ? "No  Inner Faul t" : ex.In nerExcepti on.Message );        
351                }        
352                catch (S ystem.Exce ption ex)        
353                {        
354                    Cons ole.WriteL ine("The a pplication  terminate d with an  error.");        
355                    Cons ole.WriteL ine(ex.Mes sage);        
356          
357                    // D isplay the  details o f the inne r exceptio n.        
358                    if ( ex.InnerEx ception !=  null)        
359                    {        
360                         Console.Wr iteLine(ex .InnerExce ption.Mess age);        
361          
362                         FaultExcep tion<Micro soft.Xrm.S dk.Organiz ationServi ceFault> f e = ex.Inn erExceptio n        
363                             as Fau ltExceptio n<Microsof t.Xrm.Sdk. Organizati onServiceF ault>;        
364                         if (fe !=  null)        
365                         {        
366                             Consol e.WriteLin e("Timesta mp: {0}",  fe.Detail. Timestamp) ;        
367                             Consol e.WriteLin e("Code: { 0}", fe.De tail.Error Code);        
368                             Consol e.WriteLin e("Message : {0}", fe .Detail.Me ssage);        
369                             Consol e.WriteLin e("Trace:  {0}", fe.D etail.Trac eText);        
370                             Consol e.WriteLin e("Inner F ault: {0}" ,        
371                                 nu ll == fe.D etail.Inne rFault ? " No Inner F ault" : "H as Inner F ault");        
372                         }        
373                    }        
374                }        
375                // Addit ional exce ptions to  catch: Sec urityToken Validation Exception,  ExpiredSe curityToke nException ,        
376                // Secur ityAccessD eniedExcep tion, Mess ageSecurit yException , and Secu rityNegoti ationExcep tion.        
377                finally        
378                {        
379                    Cons ole.WriteL ine("Press  <Enter> t o exit.");        
380                    Cons ole.ReadLi ne();        
381                }        
382           }        
383           #e ndregion M ain method        
384       }        
385   }        
386   // </snipp etUserAcce ssAuditing >