778. Araxis Merge File Comparison Report

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

778.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\VB\HelperCode DeviceIdManager.vb Tue Dec 20 19:51:48 2016 UTC
2 Wed Feb 1 19:57:03 2017 UTC

778.2 Comparison summary

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

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

778.4 Active regular expressions

No regular expressions were active.

778.5 Comparison detail

1   ' ======== ========== ========== ========== ========== ========== ========== =        
2   '        
3   '  This fi le is part  of the Mi crosoft Dy namics CRM  SDK code  samples.        
4   '        
5   '  Copyrig ht (C) Mic rosoft Cor poration.   All right s reserved .        
6   '        
7   '  This so urce code  is intende d only as  a suppleme nt to Micr osoft        
8   '  Develop ment Tools  and/or on -line docu mentation.   See thes e other        
9   '  materia ls for det ailed info rmation re garding Mi crosoft co de samples .        
10   '        
11   '  THIS CO DE AND INF ORMATION A RE PROVIDE D "AS IS"  WITHOUT WA RRANTY OF  ANY        
12   '  KIND, E ITHER EXPR ESSED OR I MPLIED, IN CLUDING BU T NOT LIMI TED TO THE        
13   '  IMPLIED  WARRANTIE S OF MERCH ANTABILITY  AND/OR FI TNESS FOR  A        
14   '  PARTICU LAR PURPOS E.        
15   '        
16   ' ======== ========== ========== ========== ========== ========== ========== =        
17   '<snippetD eviceIdMan ager>        
18   Imports Sy stem        
19   Imports Sy stem.Colle ctions.Gen eric        
20   Imports Sy stem.Compo nentModel        
21   Imports Sy stem.Diagn ostics.Cod eAnalysis        
22   Imports Sy stem.Globa lization        
23   Imports Sy stem.IO        
24   Imports Sy stem.Net        
25   Imports Sy stem.Runti me.Seriali zation        
26   Imports Sy stem.Secur ity.Crypto graphy        
27   Imports Sy stem.Servi ceModel.De scription        
28   Imports Sy stem.Text        
29   Imports Sy stem.Xml        
30   Imports Sy stem.Xml.S erializati on        
31          
32   Namespace  Microsoft. Crm.Servic es.Utility        
33       ''' <s ummary>        
34       ''' Ma nagement u tility for  the Devic e Id        
35       ''' </ summary>        
36       Public  NotInheri table Clas s DeviceId Manager        
37           #R egion "Fie lds"        
38           Pr ivate Shar ed ReadOnl y RandomIn stance As  New Random ()        
39          
40           Pu blic Const  MaxDevice NameLength  As Intege r = 24        
41           Pu blic Const  MaxDevice PasswordLe ngth As In teger = 24        
42           #E nd Region        
43          
44           #R egion "Con structor"        
45           Pr ivate Sub  New()        
46           En d Sub        
47           Sh ared Sub N ew()        
48                PersistT oFile = Tr ue        
49           En d Sub        
50           #E nd Region        
51          
52           #R egion "Pro perties"        
53           '' ' <summary >        
54           '' ' Indicate s whether  the regist ered devic e credenti als should  be persis ted to the  database        
55           '' ' </summar y>        
56           Pu blic Share d Property  PersistTo File() As  Boolean        
57          
58                    '''  <summary>        
59                    '''  Indicates  that the c redentials  should be  persisted  to the di sk if regi stration f ails with  DeviceAlre adyExists.        
60                    '''  </summary>        
61                    '''  <remarks>        
62                    '''  If the dev ice alread y exists,  there is a  possibili ty that th e credenti als are th e same as  the curren t credenti als that        
63                    '''  are being  registered . This is  especially  true in a utomated e nvironment s where th e same cre dentials a re used co ntinually  (to avoid        
64                    '''  registerin g spurious  device cr edentials.        
65                    '''  </remarks>        
66                    Publ ic Shared  Property P ersistIfDe viceAlread yExists()  As Boolean        
67           #E nd Region        
68          
69           #R egion "Met hods"        
70           '' ' <summary >        
71           '' ' Loads th e device c redentials  (if they  exist).        
72           '' ' </summar y>        
73           '' ' <returns ></returns >        
74           Pu blic Share d Function  LoadOrReg isterDevic e() As Cli entCredent ials        
75                Return L oadOrRegis terDevice( Nothing)        
76           En d Function        
77          
78           '' ' <summary >        
79           '' ' Loads th e device c redentials  (if they  exist).        
80           '' ' </summar y>        
81           '' ' <param n ame="devic eName">Dev ice name t hat should  be regist ered</para m>        
82           '' ' <param n ame="devic ePassword" >Device pa ssword tha t should b e register ed</param>        
83           Pu blic Share d Function  LoadOrReg isterDevic e(ByVal de viceName A s String,  ByVal devi cePassword  As String ) As Clien tCredentia ls        
84                Return L oadOrRegis terDevice( Nothing, d eviceName,  devicePas sword)        
85           En d Function        
86          
87           '' ' <summary >        
88           '' ' Loads th e device c redentials  (if they  exist).        
89           '' ' </summar y>        
90           '' ' <param n ame="issue rUri">URL  for the cu rrent toke n issuer</ param>        
91           '' ' <remarks >        
92           '' ' The issu erUri can  be retriev ed from th e IService Configurat ion interf ace's Curr entIssuer  property.        
93           '' ' </remark s>        
94           Pu blic Share d Function  LoadOrReg isterDevic e(ByVal is suerUri As  Uri) As C lientCrede ntials        
95                Return L oadOrRegis terDevice( issuerUri,  Nothing,  Nothing)        
96           En d Function        
97          
98           '' ' <summary >        
99           '' ' Loads th e device c redentials  (if they  exist).        
100           '' ' </summar y>        
101           '' ' <param n ame="issue rUri">URL  for the cu rrent toke n issuer</ param>        
102           '' ' <param n ame="devic eName">Dev ice name t hat should  be regist ered</para m>        
103           '' ' <param n ame="devic ePassword" >Device pa ssword tha t should b e register ed</param>        
104           '' ' <remarks >        
105           '' ' The issu erUri can  be retriev ed from th e IService Configurat ion interf ace's Curr entIssuer  property.        
106           '' ' </remark s>        
107           Pu blic Share d Function  LoadOrReg isterDevic e(ByVal is suerUri As  Uri, ByVa l deviceNa me As Stri ng, ByVal  devicePass word As St ring) _        
108                   As Cl ientCreden tials        
109                Dim cred entials As  ClientCre dentials =  LoadDevic eCredentia ls(issuerU ri)        
110                If Nothi ng Is cred entials Th en        
111                    cred entials =  RegisterDe vice(Guid. NewGuid(),  issuerUri , deviceNa me, device Password)        
112                End If        
113          
114                Return c redentials        
115           En d Function        
116          
117           '' ' <summary >        
118           '' ' Register s the give n device w ith Micros oft accoun t with a r andom appl ication ID        
119           '' ' </summar y>        
120           '' ' <returns >ClientCre dentials t hat were r egistered< /returns>        
121           Pu blic Share d Function  RegisterD evice() As  ClientCre dentials        
122                Return R egisterDev ice(Guid.N ewGuid())        
123           En d Function        
124          
125           '' ' <summary >        
126           '' ' Register s the give n device w ith Micros oft accoun t        
127           '' ' </summar y>        
128           '' ' <param n ame="appli cationId"> ID for the  applicati on</param>        
129           '' ' <returns >ClientCre dentials t hat were r egistered< /returns>        
130           Pu blic Share d Function  RegisterD evice(ByVa l applicat ionId As G uid) As Cl ientCreden tials        
131                Return R egisterDev ice(applic ationId, C Type(Nothi ng, Uri))        
132           En d Function        
133          
134           '' ' <summary >        
135           '' ' Register s the give n device w ith Micros oft accoun t        
136           '' ' </summar y>        
137           '' ' <param n ame="appli cationId"> ID for the  applicati on</param>        
138           '' ' <param n ame="issue rUri">URL  for the cu rrent toke n issuer</ param>        
139           '' ' <returns >ClientCre dentials t hat were r egistered< /returns>        
140           '' ' <remarks >        
141           '' ' The issu erUri can  be retriev ed from th e IService Configurat ion interf ace's Curr entIssuer  property.        
142           '' ' </remark s>        
143           Pu blic Share d Function  RegisterD evice(ByVa l applicat ionId As G uid, ByVal  issuerUri  As Uri) A s ClientCr edentials        
144                Return R egisterDev ice(applic ationId, i ssuerUri,  Nothing, N othing)        
145           En d Function        
146          
147           '' ' <summary >        
148           '' ' Register s the give n device w ith Micros oft accoun t        
149           '' ' </summar y>        
150           '' ' <param n ame="appli cationId"> ID for the  applicati on</param>        
151           '' ' <param n ame="devic eName">Dev ice name t hat should  be regist ered</para m>        
152           '' ' <param n ame="devic ePassword" >Device pa ssword tha t should b e register ed</param>        
153           '' ' <returns >ClientCre dentials t hat were r egistered< /returns>        
154           Pu blic Share d Function  RegisterD evice(ByVa l applicat ionId As G uid, ByVal  deviceNam e As Strin g, ByVal d evicePassw ord As Str ing) _        
155                   As Cl ientCreden tials        
156                Return R egisterDev ice(applic ationId, C Type(Nothi ng, Uri),  deviceName , devicePa ssword)        
157           En d Function        
158          
159           '' ' <summary >        
160           '' ' Register s the give n device w ith Micros oft accoun t        
161           '' ' </summar y>        
162           '' ' <param n ame="appli cationId"> ID for the  applicati on</param>        
163           '' ' <param n ame="issue rUri">URL  for the cu rrent toke n issuer</ param>        
164           '' ' <param n ame="devic eName">Dev ice name t hat should  be regist ered</para m>        
165           '' ' <param n ame="devic ePassword" >Device pa ssword tha t should b e register ed</param>        
166           '' ' <returns >ClientCre dentials t hat were r egistered< /returns>        
167           '' ' <remarks >        
168           '' ' The issu erUri can  be retriev ed from th e IService Configurat ion interf ace's Curr entIssuer  property.        
169           '' ' </remark s>        
170           Pu blic Share d Function  RegisterD evice(ByVa l applicat ionId As G uid, ByVal  issuerUri  As Uri, B yVal devic eName As S tring, _        
171                                                     ByVa l devicePa ssword As  String) As  ClientCre dentials        
172                If Strin g.IsNullOr Empty(devi ceName) An dAlso (Not  PersistTo File) Then        
173                    Thro w New Argu mentNullEx ception("d eviceName" , "If Pers istToFile  is false,  then devic eName must  be specif ied.")        
174                ElseIf S tring.IsNu llOrEmpty( deviceName ) <> Strin g.IsNullOr Empty(devi cePassword ) Then        
175                    Thro w New Argu mentNullEx ception("d eviceName" , _        
176                                                       "E ither devi ceName/dev icePasswor d should b oth be spe cified or  they shoul d be null. ")        
177                End If        
178          
179                             Dim de vice As Li veDevice =  GenerateD evice(devi ceName, de vicePasswo rd)        
180                             Return  RegisterD evice(appl icationId,  issuerUri , device)        
181           En d Function        
182          
183           '' ' <summary >        
184           '' ' Loads th e device's  credentia ls from th e file sys tem        
185           '' ' </summar y>        
186           '' ' <returns >Device Cr edentials  (if set) o r null</re turns>        
187           Pu blic Share d Function  LoadDevic eCredentia ls() As Cl ientCreden tials        
188                Return L oadDeviceC redentials (Nothing)        
189           En d Function        
190          
191           '' ' <summary >        
192           '' ' Loads th e device's  credentia ls from th e file sys tem        
193           '' ' </summar y>        
194           '' ' <param n ame="issue rUri">URL  for the cu rrent toke n issuer</ param>        
195           '' ' <returns >Device Cr edentials  (if set) o r null</re turns>        
196           '' ' <remarks >        
197           '' ' The issu erUri can  be retriev ed from th e IService Configurat ion interf ace's Curr entIssuer  property.        
198           '' ' </remark s>        
199           Pu blic Share d Function  LoadDevic eCredentia ls(ByVal i ssuerUri A s Uri) As  ClientCred entials        
200                'If the  credential s should n ot be pers isted to a  file, the n they won 't be pres ent on the  disk.        
201                If Not P ersistToFi le Then        
202                    Retu rn Nothing        
203                End If        
204          
205                             Dim en vironment  As Environ mentConfig uration =  DiscoverEn vironmentI nternal(is suerUri)        
206          
207                Dim devi ce As Live Device = R eadExistin gDevice(en vironment)        
208                If Nothi ng Is devi ce OrElse  Nothing Is  device.Us er Then        
209                    Retu rn Nothing        
210                End If        
211          
212                Return d evice.User .ToClientC redentials ()        
213           En d Function        
214          
215           '' ' <summary >        
216           '' ' Discover s the Wind ows Live e nvironment  based on  the Token  Issuer        
217           '' ' </summar y>        
218           Pu blic Share d Function  DiscoverE nvironment (ByVal iss uerUri As  Uri) As St ring        
219                             Return  DiscoverE nvironment Internal(i ssuerUri). Environmen t        
220                    End  Function        
221                    #End  Region        
222          
223                    #Reg ion "Priva te Methods "        
224                    Priv ate Shared  Function  DiscoverEn vironmentI nternal(By Val issuer Uri As Uri ) As Envir onmentConf iguration        
225                If Nothi ng Is issu erUri Then        
226                                      Return N ew Environ mentConfig uration(En vironmentT ype.LiveDe viceID, "l ogin.live. com", Noth ing)        
227                End If        
228          
229                             Dim se archList A s New Dict ionary(Of  Environmen tType, Str ing)()        
230                             search List.Add(E nvironment Type.LiveD eviceID, " login.live ")        
231                             search List.Add(E nvironment Type.OrgDe viceID, "l ogin.micro softonline ")        
232          
233                             For Ea ch searchP air As Key ValuePair( Of Environ mentType,  String) In  searchLis t        
234                                      If issue rUri.Host. Length > s earchPair. Value.Leng th AndAlso  issuerUri .Host.Star tsWith(sea rchPair.Va lue, Strin gCompariso n.OrdinalI gnoreCase)  Then        
235                                               Dim enviro nment As S tring = is suerUri.Ho st.Substri ng(searchP air.Value. Length)        
236          
237                                               'Parse out  the envir onment        
238                    If " -"c = envi ronment.Ch ars(0) The n        
239                         Dim separa torIndex A s Integer  = environm ent.IndexO f("."c, 1)        
240                         If -1 <> s eparatorIn dex Then        
241                                                                envi ronment =  environmen t.Substrin g(1, separ atorIndex  - 1)        
242                                                       El se        
243                                                                envi ronment =  Nothing        
244                                                       En d If        
245                                               Else        
246                                                       en vironment  = Nothing        
247                                               End If        
248          
249                                               Return New  Environme ntConfigur ation(sear chPair.Key , issuerUr i.Host, en vironment)        
250                                      End If        
251                             Next s earchPair        
252          
253                'In all  other case s the envi ronment is  either no t applicab le or it i s a produc tion syste m        
254                             Return  New Envir onmentConf iguration( Environmen tType.Live DeviceID,  issuerUri. Host, Noth ing)        
255           En d Function        
256          
257           Pr ivate Shar ed Sub Ser ialize(Of  T)(ByVal s tream As S tream, ByV al value A s T)        
258                Dim seri alizer As  New XmlSer ializer(Ge tType(T),  String.Emp ty)        
259          
260                Dim xmlN amespaces  As New Xml Serializer Namespaces ()        
261                xmlNames paces.Add( String.Emp ty, String .Empty)        
262          
263                serializ er.Seriali ze(stream,  value, xm lNamespace s)        
264           En d Sub        
265          
266                    Priv ate Shared  Function  Deserializ e(Of T)(By Val operat ionName As  String, B yVal strea m As Strea m) As T        
267                             'Read  the XML in to memory  so that th e data can  be used i n an excep tion if ne cessary        
268                             Using  reader As  New Stream Reader(str eam)        
269                                      Return D eserialize (Of T)(ope rationName , reader.R eadToEnd() )        
270                             End Us ing        
271                    End  Function        
272          
273                    Priv ate Shared  Function  Deserializ e(Of T)(By Val operat ionName As  String, B yVal xml A s String)  As T        
274                             'Attem pt to dese rialize th e data. If  deseriali zation fai ls, includ e the XML  in the exc eption tha t is throw n for furt her        
275                             'inves tigation        
276                             Using  reader As  New String Reader(xml )        
277                                      Try        
278                                               Dim serial izer As Ne w XmlSeria lizer(GetT ype(T), St ring.Empty )        
279                                               Return CTy pe(seriali zer.Deseri alize(read er), T)        
280                                      Catch ex  As Invali dOperation Exception        
281                                               Throw New  InvalidOpe rationExce ption(Stri ng.Format( CultureInf o.Invarian tCulture,  "Unable to  Deseriali ze XML (Op eration =  {0}):{1}{2 }", operat ionName, E nvironment .NewLine,  xml), ex)        
282                                      End Try        
283                             End Us ing        
284           En d Function        
285          
286                    Priv ate Shared  Function  GetDeviceF ile(ByVal  environmen t As Envir onmentConf iguration)  As FileIn fo        
287                             Return  New FileI nfo(String .Format(Cu ltureInfo. InvariantC ulture, Li veIdConsta nts.FileNa meFormat,  environmen t.Type,If( String.IsN ullOrEmpty (environme nt.Environ ment), Not hing, "-"  & environm ent.Enviro nment.ToUp perInvaria nt())))        
288                    End  Function        
289          
290                    Priv ate Shared  Function  RegisterDe vice(ByVal  applicati onId As Gu id, ByVal  issuerUri  As Uri, By Val device  As LiveDe vice) As C lientCrede ntials        
291                             Dim en vironment  As Environ mentConfig uration =  DiscoverEn vironmentI nternal(is suerUri)        
292          
293                Dim requ est As New  DeviceReg istrationR equest(app licationId , device)        
294          
295                             Dim ur l As Strin g = String .Format(Cu ltureInfo. InvariantC ulture, Li veIdConsta nts.Regist rationEndp ointUriFor mat, envir onment.Hos tName)        
296          
297                Dim resp onse As De viceRegist rationResp onse = Exe cuteRegist rationRequ est(url, r equest)        
298                If Not r esponse.Is Success Th en        
299                                      Dim thro wException  As Boolea n = True        
300                                      If Devic eRegistrat ionErrorCo de.DeviceA lreadyExis ts = respo nse.Error. Registrati onErrorCod e Then        
301                                               If Not Per sistToFile  Then        
302                                                       'I f the file  is not pe rsisted, t he registr ation will  always oc cur (since  the crede ntials are  not        
303                                                       'p ersisted t o the disk . However,  the crede ntials may  already e xist. To a void an ex ception be ing contin ually        
304                                                       'p rocessed b y the call ing user,  DeviceAlre adyExists  will be ig nored if t he credent ials are n ot persist ed to the  disk.        
305                                                       Re turn devic e.User.ToC lientCrede ntials()        
306                                               ElseIf Per sistIfDevi ceAlreadyE xists Then        
307                                                       '  This flag  indicates  that the         
308                                                       th rowExcepti on = False        
309                                               End If        
310                    End  If        
311          
312                                      If throw Exception  Then        
313                                               Throw New  DeviceRegi strationFa iledExcept ion(respon se.Error.R egistratio nErrorCode , response .ErrorSubC ode)        
314                                      End If        
315                             End If        
316          
317                             If Per sistToFile  OrElse Pe rsistIfDev iceAlready Exists The n        
318                    Writ eDevice(en vironment,  device)        
319                End If        
320          
321                Return d evice.User .ToClientC redentials ()        
322           En d Function        
323          
324                    Priv ate Shared  Function  GenerateDe vice(ByVal  deviceNam e As Strin g, ByVal d evicePassw ord As Str ing) As Li veDevice        
325                             ' If t he deviceN ame hasn't  been spec ified, it  should be  generated  using rand om charact ers.        
326                             Dim us erNameCred entials As  DeviceUse rName        
327                             If Str ing.IsNull OrEmpty(de viceName)  Then        
328                                      userName Credential s = Genera teDeviceUs erName()        
329                             Else        
330                                      userName Credential s = New De viceUserNa me() With  {.DeviceNa me = devic eName, .De cryptedPas sword = de vicePasswo rd}        
331                             End If        
332          
333                             Return  New LiveD evice() Wi th {.User  = userName Credential s, .Versio n = 1}        
334                    End  Function        
335          
336                    Priv ate Shared  Function  ReadExisti ngDevice(B yVal envir onment As  Environmen tConfigura tion) As L iveDevice        
337                'Retriev e the file  info        
338                Dim file  As FileIn fo = GetDe viceFile(e nvironment )        
339                If Not f ile.Exists  Then        
340                    Retu rn Nothing        
341                End If        
342          
343                Using st ream As Fi leStream =  file.Open (FileMode. Open, File Access.Rea d, FileSha re.Read)        
344                                      Return D eserialize (Of LiveDe vice)("Loa ding Devic e Credenti als from D isk", stre am)        
345                End Usin g        
346           En d Function        
347          
348                    Priv ate Shared  Sub Write Device(ByV al environ ment As En vironmentC onfigurati on, ByVal  device As  LiveDevice )        
349                Dim file  As FileIn fo = GetDe viceFile(e nvironment )        
350                If Not f ile.Direct ory.Exists  Then        
351                    file .Directory .Create()        
352                End If        
353          
354                Using st ream As Fi leStream =  file.Open (FileMode. CreateNew,  FileAcces s.Write, F ileShare.N one)        
355                    Seri alize(stre am, device )        
356                End Usin g        
357           En d Sub        
358          
359           Pr ivate Shar ed Functio n ExecuteR egistratio nRequest(B yVal url A s String,  ByVal regi strationRe quest As D eviceRegis trationReq uest) _        
360                   As De viceRegist rationResp onse        
361                'Create  the reques t that wil l submit t he request  to the se rver        
362                Dim requ est As Web Request =  WebRequest .Create(ur l)        
363                request. ContentTyp e = "appli cation/soa p+xml; cha rset=UTF-8 "        
364                request. Method = " POST"        
365                request. Timeout =  180000        
366          
367                'Write t he envelop e to the R equestStre am        
368                Using st ream As St ream = req uest.GetRe questStrea m()        
369                    Seri alize(stre am, regist rationRequ est)        
370                End Usin g        
371          
372                ' Read t he respons e into an  XmlDocumen t and retu rn that do c        
373                Try        
374                    Usin g response  As WebRes ponse = re quest.GetR esponse()        
375                         Using stre am As Stre am = respo nse.GetRes ponseStrea m()        
376                                                       Re turn Deser ialize(Of  DeviceRegi strationRe sponse)("D eserializi ng Registr ation Resp onse", str eam)        
377                         End Using        
378                    End  Using        
379                Catch ex  As WebExc eption        
380                                      System.D iagnostics .Trace.Tra ceError("L ive ID Dev ice Regist ration Fai led (HTTP  Code: {0}) : {1}", ex .Status, e x.Message)        
381                    If N othing IsN ot ex.Resp onse Then        
382                         Using stre am As Stre am = ex.Re sponse.Get ResponseSt ream()        
383                                                       Re turn Deser ialize(Of  DeviceRegi strationRe sponse)("D eserializi ng Failed  Registrati on Respons e", stream )        
384                         End Using        
385                    End  If        
386          
387                    Thro w        
388                End Try        
389           En d Function        
390          
391           Pr ivate Shar ed Functio n Generate DeviceUser Name() As  DeviceUser Name        
392                Dim user Name As Ne w DeviceUs erName()        
393                userName .DeviceNam e = Genera teRandomSt ring(LiveI dConstants .ValidDevi ceNameChar acters, Ma xDeviceNam eLength)        
394                userName .Decrypted Password =  GenerateR andomStrin g(LiveIdCo nstants.Va lidDeviceP asswordCha racters, M axDevicePa sswordLeng th)        
395          
396                Return u serName        
397           En d Function        
398          
399           Pr ivate Shar ed Functio n Generate RandomStri ng(ByVal c haracterSe t As Strin g, ByVal c ount As In teger) As  String        
400                'Create  an array o f the char acters tha t will hol d the fina l list of  random cha racters        
401                Dim valu e(count -  1) As Char        
402          
403                'Convert  the chara cter set t o an array  that can  be randoml y accessed        
404                Dim [set ]() As Cha r = charac terSet.ToC harArray()        
405          
406                SyncLock  RandomIns tance        
407                    'Pop ulate the  array with  random ch aracters f rom the ch aracter se t        
408                    For  i As Integ er = 0 To  count - 1        
409                         value(i) =  [set](Ran domInstanc e.Next(0,  [set].Leng th))        
410                    Next  i        
411                End Sync Lock        
412          
413                Return N ew String( value)        
414           En d Function        
415           #E nd Region        
416          
417           #R egion "Pri vate Class es"        
418                    Priv ate Enum E nvironment Type        
419                             LiveDe viceID        
420                             OrgDev iceID        
421                    End  Enum        
422          
423                    Priv ate NotInh eritable C lass Envir onmentConf iguration        
424                             Public  Sub New(B yVal type  As Environ mentType,  ByVal host Name As St ring, ByVa l environm ent As Str ing)        
425                                      If Strin g.IsNullOr WhiteSpace (hostName)  Then        
426                                               Throw New  ArgumentNu llExceptio n("hostNam e")        
427                                      End If        
428          
429                                      Me.Type  = type        
430                                      Me.HostN ame = host Name        
431                                      Me.Envir onment = e nvironment        
432                             End Su b        
433          
434                             #Regio n "Propert ies"        
435                             Privat e privateT ype As Env ironmentTy pe        
436                             Public  Property  Type() As  Environmen tType        
437                                      Get        
438                                               Return pri vateType        
439                                      End Get        
440                                      Private  Set(ByVal  value As E nvironment Type)        
441                                               privateTyp e = value        
442                                      End Set        
443                             End Pr operty        
444          
445                             Privat e privateH ostName As  String        
446                             Public  Property  HostName()  As String        
447                                      Get        
448                                               Return pri vateHostNa me        
449                                      End Get        
450                                      Private  Set(ByVal  value As S tring)        
451                                               privateHos tName = va lue        
452                                      End Set        
453                             End Pr operty        
454          
455                             Privat e privateE nvironment  As String        
456                             Public  Property  Environmen t() As Str ing        
457                                      Get        
458                                               Return pri vateEnviro nment        
459                                      End Get        
460                                      Private  Set(ByVal  value As S tring)        
461                                               privateEnv ironment =  value        
462                                      End Set        
463                             End Pr operty        
464                             #End R egion        
465                    End  Class        
466          
467                    Priv ate NotInh eritable C lass LiveI dConstants        
468                             Public  Const Reg istrationE ndpointUri Format As  String = " https://{0 }/ppsecure /DeviceAdd Credential .srf"        
469          
470                             Public  Shared Re adOnly Fil eNameForma t As Strin g = Path.C ombine(Pat h.Combine( Environmen t.GetFolde rPath(Envi ronment.Sp ecialFolde r.UserProf ile), "Liv eDeviceID" ), "{0}{1} .xml")        
471          
472                Public C onst Valid DeviceName Characters  As String  = "012345 6789abcdef ghijklmnop qrstuvqxyz "        
473          
474                'Consist s of the l ist of cha racters sp ecified in  the docum entation        
475                Public C onst Valid DevicePass wordCharac ters As St ring = _        
476                    "abc defghijklm nopqrstuvw xyzABCDEFG HIJKLMNOPQ RSTUVWXYZ0 123456789! @#$%^*()-_ =+;,./?`~"        
477           En d Class        
478           #E nd Region        
479       End Cl ass        
480          
481       #Regio n "Public  Classes &  Enums"        
482       ''' <s ummary>        
483       ''' In dicates an  error dur ing regist ration        
484       ''' </ summary>        
485       Public  Enum Devi ceRegistra tionErrorC ode        
486           '' ' <summary >        
487           '' ' Unspecif ied or Unk nown Error  occurred        
488           '' ' </summar y>        
489           Un known = 0        
490          
491           '' ' <summary >        
492           '' ' Interfac e Disabled        
493           '' ' </summar y>        
494           In terfaceDis abled = 1        
495          
496           '' ' <summary >        
497           '' ' Invalid  Request Fo rmat        
498           '' ' </summar y>        
499           In validReque stFormat =  3        
500          
501           '' ' <summary >        
502           '' ' Unknown  Client Ver sion        
503           '' ' </summar y>        
504           Un knownClien tVersion =  4        
505          
506           '' ' <summary >        
507           '' ' Blank Pa ssword        
508           '' ' </summar y>        
509           Bl ankPasswor d = 6        
510          
511           '' ' <summary >        
512           '' ' Missing  Device Use r Name or  Password        
513           '' ' </summar y>        
514           Mi ssingDevic eUserNameO rPassword  = 7        
515          
516           '' ' <summary >        
517           '' ' Invalid  Parameter  Syntax        
518           '' ' </summar y>        
519           In validParam eterSyntax  = 8        
520          
521           '' ' <summary >        
522           '' ' Invalid  Characters  are used  in the dev ice creden tials.        
523           '' ' </summar y>        
524           In validChara ctersInCre dentials =  9        
525          
526           '' ' <summary >        
527           '' ' Internal  Error        
528           '' ' </summar y>        
529           In ternalErro r = 11        
530          
531           '' ' <summary >        
532           '' ' Device A lready Exi sts        
533           '' ' </summar y>        
534           De viceAlread yExists =  13        
535       End En um        
536          
537       ''' <s ummary>        
538       ''' In dicates th at Device  Registrati on failed        
539       ''' </ summary>        
540       <Seria lizable> _        
541       Public  NotInheri table Clas s DeviceRe gistration FailedExce ption        
542           In herits Exc eption        
543           '' ' <summary >        
544           '' ' Construc t an insta nce of the  DeviceReg istrationF ailedExcep tion class        
545           '' ' </summar y>        
546           Pu blic Sub N ew()        
547                MyBase.N ew()        
548           En d Sub        
549          
550           '' ' <summary >        
551           '' ' Construc t an insta nce of the  DeviceReg istrationF ailedExcep tion class        
552           '' ' </summar y>        
553           '' ' <param n ame="messa ge">Messag e to pass< /param>        
554           Pu blic Sub N ew(ByVal m essage As  String)        
555                MyBase.N ew(message )        
556           En d Sub        
557          
558           '' ' <summary >        
559           '' ' Construc t an insta nce of the  DeviceReg istrationF ailedExcep tion class        
560           '' ' </summar y>        
561           '' ' <param n ame="messa ge">Messag e to pass< /param>        
562           '' ' <param n ame="inner Exception" >Exception  to includ e</param>        
563           Pu blic Sub N ew(ByVal m essage As  String, By Val innerE xception A s Exceptio n)        
564                MyBase.N ew(message , innerExc eption)        
565           En d Sub        
566          
567           '' ' <summary >        
568           '' ' Construc t an insta nce of the  DeviceReg istrationF ailedExcep tion class        
569           '' ' </summar y>        
570           '' ' <param n ame="code" >Error cod e that occ urred</par am>        
571           '' ' <param n ame="subCo de">Subcod e that occ urred</par am>        
572           Pu blic Sub N ew(ByVal c ode As Dev iceRegistr ationError Code, ByVa l subCode  As String)        
573                Me.New(c ode, subCo de, Nothin g)        
574           En d Sub        
575          
576           '' ' <summary >        
577           '' ' Construc t an insta nce of the  DeviceReg istrationF ailedExcep tion class        
578           '' ' </summar y>        
579           '' ' <param n ame="code" >Error cod e that occ urred</par am>        
580           '' ' <param n ame="subCo de">Subcod e that occ urred</par am>        
581           '' ' <param n ame="inner Exception" >Inner exc eption</pa ram>        
582           Pu blic Sub N ew(ByVal c ode As Dev iceRegistr ationError Code, ByVa l subCode  As String,  ByVal inn erExceptio n As Excep tion)        
583                MyBase.N ew(String. Concat(cod e.ToString (), ": ",  subCode),  innerExcep tion)        
584                Me.Regis trationErr orCode = c ode        
585           En d Sub        
586          
587           '' ' <summary >        
588           '' ' Construc t an insta nce of the  DeviceReg istrationF ailedExcep tion class        
589           '' ' </summar y>        
590           '' ' <param n ame="si">< /param>        
591           '' ' <param n ame="sc">< /param>        
592           Pr ivate Sub  New(ByVal  si As Seri alizationI nfo, ByVal  sc As Str eamingCont ext)        
593                MyBase.N ew(si, sc)        
594           En d Sub        
595          
596           #R egion "Pro perties"        
597           '' ' <summary >        
598           '' ' Error co de that oc curred dur ing regist ration        
599           '' ' </summar y>        
600           Pr ivate priv ateRegistr ationError Code As De viceRegist rationErro rCode        
601           Pu blic Prope rty Regist rationErro rCode() As  DeviceReg istrationE rrorCode        
602                Get        
603                    Retu rn private Registrati onErrorCod e        
604                End Get        
605                Private  Set(ByVal  value As D eviceRegis trationErr orCode)        
606                    priv ateRegistr ationError Code = val ue        
607                End Set        
608           En d Property        
609           #E nd Region        
610          
611           #R egion "Met hods"        
612           Pu blic Overr ides Sub G etObjectDa ta(ByVal i nfo As Ser ialization Info, ByVa l context  As Streami ngContext)        
613                MyBase.G etObjectDa ta(info, c ontext)        
614           En d Sub        
615           #E nd Region        
616       End Cl ass        
617          
618       #Regio n "Seriali zation Cla sses"        
619       #Regio n "DeviceR egistratio nRequest C lass"        
620       <Edito rBrowsable (EditorBro wsableStat e.Never),  XmlRoot("D eviceAddRe quest")> _        
621       Public  NotInheri table Clas s DeviceRe gistration Request        
622           #R egion "Con structors"        
623           Pu blic Sub N ew()        
624           En d Sub        
625          
626           Pu blic Sub N ew(ByVal a pplication Id As Guid , ByVal de vice As Li veDevice)        
627                Me.New()        
628                If Nothi ng Is devi ce Then        
629                    Thro w New Argu mentNullEx ception("d evice")        
630                End If        
631          
632                Me.Clien tInfo = Ne w DeviceRe gistration ClientInfo () With {. Applicatio nId = appl icationId,  .Version  = "1.0"}        
633                Me.Authe ntication  = New Devi ceRegistra tionAuthen tication()  With {.Me mberName =  device.Us er.DeviceI d, _        
634                                                                                       .Pa ssword = d evice.User .Decrypted Password}        
635           En d Sub        
636           #E nd Region        
637          
638           #R egion "Pro perties"        
639           <X mlElement( "ClientInf o")> _        
640           Pu blic Prope rty Client Info() As  DeviceRegi strationCl ientInfo        
641          
642           <X mlElement( "Authentic ation")> _        
643           Pu blic Prope rty Authen tication()  As Device Registrati onAuthenti cation        
644           #E nd Region        
645       End Cl ass        
646       #End R egion        
647          
648       #Regio n "DeviceR egistratio nClientInf o Class"        
649       <Edito rBrowsable (EditorBro wsableStat e.Never),  XmlRoot("C lientInfo" )> _        
650       Public  NotInheri table Clas s DeviceRe gistration ClientInfo        
651           #R egion "Pro perties"        
652           <X mlAttribut e("name")>  _        
653           Pu blic Prope rty Applic ationId()  As Guid        
654          
655           <X mlAttribut e("version ")> _        
656           Pu blic Prope rty Versio n() As Str ing        
657           #E nd Region        
658       End Cl ass        
659       #End R egion        
660          
661       #Regio n "DeviceR egistratio nAuthentic ation Clas s"        
662       <Edito rBrowsable (EditorBro wsableStat e.Never),  XmlRoot("A uthenticat ion")> _        
663       Public  NotInheri table Clas s DeviceRe gistration Authentica tion        
664           #R egion "Pro perties"        
665           <X mlElement( "Membernam e")> _        
666           Pu blic Prope rty Member Name() As  String        
667          
668           <X mlElement( "Password" )> _        
669           Pu blic Prope rty Passwo rd() As St ring        
670           #E nd Region        
671       End Cl ass        
672       #End R egion        
673          
674       #Regio n "DeviceR egistratio nResponse  Class"        
675       <Edito rBrowsable (EditorBro wsableStat e.Never),  XmlRoot("D eviceAddRe sponse")>  _        
676       Public  NotInheri table Clas s DeviceRe gistration Response        
677           #R egion "Pro perties"        
678           <X mlElement( "success") > _        
679           Pu blic Prope rty IsSucc ess() As B oolean        
680          
681           <X mlElement( "puid")> _        
682           Pu blic Prope rty Puid()  As String        
683          
684           <X mlElement( "Error")>  _        
685           Pu blic Prope rty [Error ]() As Dev iceRegistr ationRespo nseError        
686          
687           <X mlElement( "ErrorSubc ode")> _        
688           Pu blic Prope rty ErrorS ubCode() A s String        
689           #E nd Region        
690       End Cl ass        
691       #End R egion        
692          
693       #Regio n "DeviceR egistratio nResponse  Class"        
694       <Edito rBrowsable (EditorBro wsableStat e.Never),  XmlRoot("E rror")> _        
695       Public  NotInheri table Clas s DeviceRe gistration ResponseEr ror        
696           Pr ivate _cod e As Strin g        
697          
698           #R egion "Pro perties"        
699           <X mlAttribut e("Code")>  _        
700           Pu blic Prope rty Code()  As String        
701                Get        
702                    Retu rn Me._cod e        
703                End Get        
704          
705                Set(ByVa l value As  String)        
706                    Me._ code = val ue        
707          
708                    'Par se the err or code        
709                    If N ot String. IsNullOrEm pty(value)  Then        
710                         'Parse the  error cod e        
711                         If value.S tartsWith( "dc", Stri ngComparis on.Ordinal ) Then        
712                             Dim co de_Renamed  As Intege r        
713                             If Int eger.TryPa rse(value. Substring( 2), Number Styles.Int eger, Cult ureInfo.In variantCul ture, code _Renamed)  _        
714                                     AndAlso S ystem.Enum .IsDefined (GetType(D eviceRegis trationErr orCode), c ode_Rename d) Then        
715                                 Me .Registrat ionErrorCo de = CType (System.En um.ToObjec t(GetType( DeviceRegi strationEr rorCode),  code_Renam ed), Devic eRegistrat ionErrorCo de)        
716                             End If        
717                         End If        
718                    End  If        
719                End Set        
720           En d Property        
721          
722           Pr ivate priv ateRegistr ationError Code As De viceRegist rationErro rCode        
723           <X mlIgnore>  _        
724           Pu blic Prope rty Regist rationErro rCode() As  DeviceReg istrationE rrorCode        
725                Get        
726                    Retu rn private Registrati onErrorCod e        
727                End Get        
728                Private  Set(ByVal  value As D eviceRegis trationErr orCode)        
729                    priv ateRegistr ationError Code = val ue        
730                End Set        
731           En d Property        
732           #E nd Region        
733       End Cl ass        
734       #End R egion        
735          
736       #Regio n "LiveDev ice Class"        
737       <Edito rBrowsable (EditorBro wsableStat e.Never),  XmlRoot("D ata")> _        
738       Public  NotInheri table Clas s LiveDevi ce        
739           #R egion "Pro perties"        
740           <X mlAttribut e("version ")> _        
741           Pu blic Prope rty Versio n() As Int eger        
742          
743           <X mlElement( "User")> _        
744           Pu blic Prope rty User()  As Device UserName        
745          
746           <S uppressMes sage("Micr osoft.Desi gn", "CA10 59:Members ShouldNotE xposeCerta inConcrete Types", _        
747                MessageI d:="System .Xml.XmlNo de", Justi fication:= "This is r equired fo r proper X ML Seriali zation"),  XmlElement ("Token")>  _        
748           Pu blic Prope rty Token( ) As XmlNo de        
749          
750           <X mlElement( "Expiry")>  _        
751           Pu blic Prope rty Expiry () As Stri ng        
752          
753           <X mlElement( "ClockSkew ")> _        
754           Pu blic Prope rty ClockS kew() As S tring        
755           #E nd Region        
756       End Cl ass        
757       #End R egion        
758          
759       #Regio n "DeviceU serName Cl ass"        
760       <Edito rBrowsable (EditorBro wsableStat e.Never)>  _        
761       Public  NotInheri table Clas s DeviceUs erName        
762           Pr ivate _enc ryptedPass word As St ring        
763                    Priv ate _decry ptedPasswo rd As Stri ng        
764           Pr ivate _enc ryptedValu eIsUpdated  As Boolea n        
765          
766           #R egion "Con stants"        
767           Pr ivate Cons t UserName Prefix As  String = " 11"        
768           #E nd Region        
769          
770           #R egion "Con structors"        
771           Pu blic Sub N ew()        
772                Me.UserN ameType =  "Logical"        
773           En d Sub        
774           #E nd Region        
775          
776           #R egion "Pro perties"        
777           <X mlAttribut e("usernam e")> _        
778           Pu blic Prope rty Device Name() As  String        
779          
780           <X mlAttribut e("type")>  _        
781           Pu blic Prope rty UserNa meType() A s String        
782          
783           <X mlElement( "Pwd")> _        
784           Pu blic Prope rty Encryp tedPasswor d() As Str ing        
785                Get        
786                    Me.T hrowIfNoEn cryption()        
787          
788                    If N ot Me._enc ryptedValu eIsUpdated  Then        
789                                               Me._encryp tedPasswor d = Me.Enc rypt(Me._d ecryptedPa ssword)        
790                         Me._encryp tedValueIs Updated =  True        
791                    End  If        
792          
793                    Retu rn Me._enc ryptedPass word        
794                End Get        
795          
796                Set(ByVa l value As  String)        
797                    Me.T hrowIfNoEn cryption()        
798                    Me.U pdateCrede ntials(val ue, Nothin g)        
799                End Set        
800           En d Property        
801          
802           Pu blic ReadO nly Proper ty DeviceI d() As Str ing        
803                Get        
804                    Retu rn UserNam ePrefix &  DeviceName        
805                End Get        
806           En d Property        
807          
808           <X mlIgnore>  _        
809           Pu blic Prope rty Decryp tedPasswor d() As Str ing        
810                Get        
811                                      Return M e._decrypt edPassword        
812                End Get        
813          
814                Set(ByVa l value As  String)        
815                    Me.U pdateCrede ntials(Not hing, valu e)        
816                End Set        
817           En d Property        
818          
819           Pr ivate Read Only Prope rty IsEncr yptionEnab led() As B oolean        
820                Get        
821                    'If  the object  is not go ing to be  persisted  to a file,  then the  value does  not need  to be encr ypted. Thi s is extra        
822                    'ove rhead and  will not f unction in  partial t rust.        
823                    Retu rn DeviceI dManager.P ersistToFi le        
824                End Get        
825           En d Property        
826           #E nd Region        
827          
828           #R egion "Met hods"        
829           Pu blic Funct ion ToClie ntCredenti als() As C lientCrede ntials        
830                Dim cred entials As  New Clien tCredentia ls()        
831                credenti als.UserNa me.UserNam e = Me.Dev iceId        
832                credenti als.UserNa me.Passwor d = Me.Dec ryptedPass word        
833          
834                Return c redentials        
835           En d Function        
836          
837           Pr ivate Sub  ThrowIfNoE ncryption( )        
838                If Not M e.IsEncryp tionEnable d Then        
839                    Thro w New NotS upportedEx ception("N ot support ed when De viceIdMana ger.UseEnc ryptionApi s is false .")        
840                End If        
841           En d Sub        
842          
843           Pr ivate Sub  UpdateCred entials(By Val encryp tedValue A s String,  ByVal decr yptedValue  As String )        
844                Dim isVa lueUpdated  As Boolea n = False        
845                If Strin g.IsNullOr Empty(encr yptedValue ) AndAlso  String.IsN ullOrEmpty (decrypted Value) The n        
846                    isVa lueUpdated  = True        
847                ElseIf S tring.IsNu llOrEmpty( encryptedV alue) Then        
848                    If M e.IsEncryp tionEnable d Then        
849                         encryptedV alue = Me. Encrypt(de cryptedVal ue)        
850                         isValueUpd ated = Tru e        
851                    Else        
852                         encryptedV alue = Not hing        
853                         isValueUpd ated = Fal se        
854                    End  If        
855                Else        
856                    Me.T hrowIfNoEn cryption()        
857          
858                    decr yptedValue  = Me.Decr ypt(encryp tedValue)        
859                    isVa lueUpdated  = True        
860                End If        
861          
862                Me._encr yptedPassw ord = encr yptedValue        
863                             Me._de cryptedPas sword = de cryptedVal ue        
864                Me._encr yptedValue IsUpdated  = isValueU pdated        
865           En d Sub        
866          
867           Pr ivate Func tion Encry pt(ByVal v alue As St ring) As S tring        
868                If Strin g.IsNullOr Empty(valu e) Then        
869                    Retu rn value        
870                End If        
871          
872                Dim encr yptedBytes () As Byte  = Protect edData.Pro tect(Encod ing.UTF8.G etBytes(va lue), Noth ing, DataP rotectionS cope.Curre ntUser)        
873                Return C onvert.ToB ase64Strin g(encrypte dBytes)        
874           En d Function        
875          
876           Pr ivate Func tion Decry pt(ByVal v alue As St ring) As S tring        
877                If Strin g.IsNullOr Empty(valu e) Then        
878                    Retu rn value        
879                End If        
880          
881                Dim decr yptedBytes () As Byte  = Protect edData.Unp rotect(Con vert.FromB ase64Strin g(value),  Nothing, D ataProtect ionScope.C urrentUser )        
882                If Nothi ng Is decr yptedBytes  OrElse 0  = decrypte dBytes.Len gth Then        
883                    Retu rn Nothing        
884                End If        
885          
886                Return E ncoding.UT F8.GetStri ng(decrypt edBytes, 0 , decrypte dBytes.Len gth)        
887           En d Function        
888           #E nd Region        
889       End Cl ass        
890       #End R egion        
891       #End R egion        
892       #End R egion        
893   End Namesp ace        
894   '</snippet DeviceIdMa nager>