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

777.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 CrmServiceHelpers.vb Tue Dec 20 19:51:48 2016 UTC
2 Wed Feb 1 19:57:03 2017 UTC

777.2 Comparison summary

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

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

777.4 Active regular expressions

No regular expressions were active.

777.5 Comparison detail

1   ' ======== ========== ========== ========== ========== ========== ========== =        
2   '  This fi le is part  of the Mi crosoft Dy namics CRM  SDK code  samples.        
3   '        
4   '  Copyrig ht (C) Mic rosoft Cor poration.   All right s reserved .        
5   '        
6   '  This so urce code  is intende d only as  a suppleme nt to Micr osoft        
7   '  Develop ment Tools  and/or on -line docu mentation.   See thes e other        
8   '  materia ls for det ailed info rmation re garding Mi crosoft co de samples .        
9   '        
10   '  THIS CO DE AND INF ORMATION A RE PROVIDE D "AS IS"  WITHOUT WA RRANTY OF  ANY        
11   '  KIND, E ITHER EXPR ESSED OR I MPLIED, IN CLUDING BU T NOT LIMI TED TO THE        
12   '  IMPLIED  WARRANTIE S OF MERCH ANTABILITY  AND/OR FI TNESS FOR  A        
13   '  PARTICU LAR PURPOS E.        
14   ' ======== ========== ========== ========== ========== ========== ========== =        
15   '<snippetC rmServiceH elper>        
16   Option Exp licit On        
17   Option Str ict On        
18   Imports Mi crosoft.Vi sualBasic        
19   Imports Sy stem        
20   Imports Sy stem.Colle ctions.Gen eric        
21   Imports Sy stem.Diagn ostics.Cod eAnalysis        
22   Imports Sy stem.Direc toryServic es.Account Management        
23   Imports Sy stem.IO        
24   Imports Sy stem.Runti me.Interop Services        
25   Imports Sy stem.Secur ity        
26   Imports Sy stem.Servi ceModel        
27   Imports Sy stem.Servi ceModel.De scription        
28   Imports Sy stem.Text        
29   Imports Sy stem.Xml        
30   Imports Sy stem.Xml.L inq        
31          
32   ' These na mespaces a re found i n the Micr osoft.Xrm. Sdk.dll as sembly        
33   ' located  in the SDK \bin folde r of the S DK downloa d.        
34   Imports Mi crosoft.Xr m.Sdk        
35   Imports Mi crosoft.Xr m.Sdk.Clie nt        
36   Imports Mi crosoft.Xr m.Sdk.Disc overy        
37   Imports Mi crosoft.Cr m.Services .Utility        
38          
39          
40   Namespace  Microsoft. Crm.Sdk.Sa mples        
41       ''' <s ummary>        
42       ''' Pr ovides ser ver connec tion infor mation.        
43       ''' </ summary>        
44       Public  Class Ser verConnect ion        
45           #R egion "Inn er classes        
46           '' ' <summary >        
47           '' ' Stores M icrosoft D ynamics CR M server c onfigurati on informa tion.        
48           '' ' </summar y>        
49           Pu blic Class  Configura tion        
50                Public S erverAddre ss As Stri ng        
51                Public O rganizatio nName As S tring        
52                Public D iscoveryUr i As Uri        
53                Public O rganizatio nUri As Ur i        
54                Public H omeRealmUr i As Uri =  Nothing        
55                Public D eviceCrede ntials As  ClientCred entials =  Nothing        
56                Public C redentials  As Client Credential s = Nothin g        
57                Public E ndpointTyp e As Authe nticationP roviderTyp e        
58                             Public  UserPrinc ipalName A s String        
59   #Region "i nternal me mbers of t he class"        
60                Friend O rganizatio nServiceMa nagement A s IService Management (Of IOrgan izationSer vice)        
61                Friend O rganizatio nTokenResp onse As Se curityToke nResponse        
62                Friend A uthFailure Count As I nt16 = 0        
63   #End Regio n        
64          
65                Public O verrides O verloads F unction Eq uals(ByVal  obj As Ob ject) As B oolean        
66                    'Che ck for nul l and comp are run-ti me types.        
67                    If o bj Is Noth ing OrElse  Me.GetTyp e() IsNot  obj.GetTyp e() Then        
68                         Return Fal se        
69                    End  If        
70          
71                    Dim  c As Confi guration =  CType(obj , Configur ation)        
72          
73                    If N ot Me.Serv erAddress. Equals(c.S erverAddre ss, String Comparison .Invariant CultureIgn oreCase) T hen        
74                         Return Fal se        
75                    End  If        
76                    If N ot Me.Orga nizationNa me.Equals( c.Organiza tionName,  StringComp arison.Inv ariantCult ureIgnoreC ase) Then        
77                         Return Fal se        
78                    End  If        
79                    If M e.Endpoint Type <> c. EndpointTy pe Then        
80                         Return Fal se        
81                    End  If        
82                    If N othing IsN ot Me.Cred entials An dAlso Noth ing IsNot  c.Credenti als Then        
83                         If Me.Endp ointType =  Authentic ationProvi derType.Ac tiveDirect ory Then        
84                             If Not  Me.Creden tials.Wind ows.Client Credential .Domain.Eq uals(c.Cre dentials.W indows.Cli entCredent ial.Domain ,        
85                                                                                                Strin gCompariso n.Invarian tCultureIg noreCase)  Then        
86                                 Re turn False        
87                             End If        
88                             If Not  Me.Creden tials.Wind ows.Client Credential .UserName. Equals(c.C redentials .Windows.C lientCrede ntial.User Name,        
89                                                                                                  Str ingCompari son.Invari antCulture IgnoreCase ) Then        
90                                 Re turn False        
91                             End If        
92                         ElseIf Me. EndpointTy pe = Authe nticationP roviderTyp e.LiveId T hen        
93                             If Not  Me.Creden tials.User Name.UserN ame.Equals (c.Credent ials.UserN ame.UserNa me,        
94                                                                                 StringCom parison.In variantCul tureIgnore Case) Then        
95                                 Re turn False        
96                             End If        
97                             If Not  Me.Device Credential s.UserName .UserName. Equals(c.D eviceCrede ntials.Use rName.User Name,        
98                                                                                       Str ingCompari son.Invari antCulture IgnoreCase ) Then        
99                                 Re turn False        
100                             End If        
101                             If Not  Me.Device Credential s.UserName .Password. Equals(c.D eviceCrede ntials.Use rName.Pass word,        
102                                                                                       Str ingCompari son.Invari antCulture IgnoreCase ) Then        
103                                 Re turn False        
104                             End If        
105                         Else        
106                             If Not  Me.Creden tials.User Name.UserN ame.Equals (c.Credent ials.UserN ame.UserNa me,        
107                                                                                 StringCom parison.In variantCul tureIgnore Case) Then        
108                                 Re turn False        
109                             End If        
110          
111                         End If        
112                    End  If        
113                    Retu rn True        
114                End Func tion        
115          
116                Public O verrides F unction Ge tHashCode( ) As Integ er        
117                    Dim  returnHash Code As In teger = Me .ServerAdd ress.GetHa shCode() _        
118                                                       Xo r Me.Organ izationNam e.GetHashC ode() _        
119                                                       Xo r Me.Endpo intType.Ge tHashCode( )        
120                                      If Nothi ng IsNot M e.Credenti als Then        
121                    If M e.Endpoint Type = Aut henticatio nProviderT ype.Active Directory  Then        
122                         returnHash Code = ret urnHashCod e _        
123                             Xor Me .Credentia ls.Windows .ClientCre dential.Us erName.Get HashCode()  _        
124                             Xor Me .Credentia ls.Windows .ClientCre dential.Do main.GetHa shCode()        
125                    Else If Me.Endp ointType =  Authentic ationProvi derType.Li veId Then        
126                         returnHash Code = ret urnHashCod e _        
127                             Xor Me .Credentia ls.UserNam e.UserName .GetHashCo de() _        
128                             Xor Me .DeviceCre dentials.U serName.Us erName.Get HashCode()  _        
129                             Xor Me .DeviceCre dentials.U serName.Pa ssword.Get HashCode()        
130                    Else        
131                         returnHash Code = ret urnHashCod e _        
132                             Xor Me .Credentia ls.UserNam e.UserName .GetHashCo de()        
133                    End  If        
134                                      End If        
135                    Retu rn returnH ashCode        
136                End Func tion        
137          
138           En d Class        
139   #End Regio n ' Inner  classes        
140          
141   #Region "P ublic prop erties"        
142          
143           Pu blic confi gurations  As List(Of  Configura tion) = No thing        
144          
145   #End Regio n ' Public  propertie s        
146          
147   #Region "P rivate pro perties"        
148          
149           Pr ivate conf ig As New  Configurat ion()        
150          
151   #End Regio n ' Privat e properti es        
152          
153                    #Reg ion "Stati c methods"        
154                    '''  <summary>        
155                    '''  Obtains th e organiza tion servi ce proxy.        
156                    '''  This would  give a be tter perfo rmance tha n directly  calling G etProxy()  generic me thod        
157                    '''  as it uses  cached Or ganization ServiceMan agement in  case it i s present.        
158                    '''  </summary>        
159                    '''  <param nam e="serverC onfigurati on">An ins tance of S erverConne ction.Conf iguration< /param>        
160                    '''  <returns>A n instance  of organi zation ser vice proxy </returns>        
161                    Publ ic Shared  Function G etOrganiza tionProxy( ByVal serv erConfigur ation As S erverConne ction.Conf iguration)  As Organi zationServ iceProxy        
162                             ' If o rganizatio n service  management  exists, t hen use it        
163                             ' Othe rwise gene rate organ ization se rvice prox y from scr atch.        
164                             If Not hing IsNot  serverCon figuration .Organizat ionService Management  Then        
165                    ' Ob tain the o rganizatio n service  proxy for  the Federa ted, Micro soft accou nt, and On lineFedera ted enviro nments.         
166                    If s erverConfi guration.E ndpointTyp e <> Authe nticationP roviderTyp e.ActiveDi rectory Th en        
167                         ' get the  organizati on service  proxy.        
168                         Return Get Proxy(Of I Organizati onService,  Organizat ionService Proxy)(ser verConfigu ration)        
169          
170                         ' Obtain o rganizatio n service  proxy for  ActiveDire ctory envi ronment         
171                         ' using ex isting org anization  service ma nagement.        
172                    Else        
173                         Return New  ManagedTo kenOrganiz ationServi ceProxy(se rverConfig uration.Or ganization ServiceMan agement, s erverConfi guration.C redentials )        
174                    End  If        
175                             End If        
176          
177                             ' Obta in the org anization  service pr oxy for al l type of  environmen ts.        
178                             Return  GetProxy( Of IOrgani zationServ ice, Organ izationSer viceProxy) (serverCon figuration )        
179          
180                    End  Function        
181                    #End  Region '  Static met hods        
182          
183   #Region "P ublic meth ods"        
184           '' ' <summary >        
185           '' ' Obtains  the server  connectio n informat ion includ ing the ta rget organ ization's        
186           '' ' Uri and  user logon  credentia ls from th e user.        
187           '' ' </summar y>        
188           Pu blic Overr idable Fun ction GetS erverConfi guration()  As Config uration        
189                Dim ssl  As Boolean        
190                Dim addC onfig As B oolean        
191                Dim conf igNumber A s Integer        
192                             ' Read  the confi guration f rom the di sk, if it  exists, at  C:\Users\ <username> \AppData\R oaming\Crm Server\Cre dentials.x ml.        
193                Dim isCo nfigExist  As Boolean  = ReadCon figuration s()        
194          
195                             ' Chec k if serve r configur ation sett ings are a lready ava ilable on  the disk.        
196                If isCon figExist T hen        
197                                      ' List o f server c onfigurati ons that a re availab le from ea rlier save d settings .        
198                    Cons ole.Write( vbLf & "(0 ) Add New  Server Con figuration  (Maximum  number up  to 9)" & v bTab)        
199                    For  n As Integ er = 0 To  configurat ions.Count  - 1        
200                         Dim user A s String        
201          
202                         Select Cas e configur ations(n). EndpointTy pe        
203                             Case A uthenticat ionProvide rType.Acti veDirector y        
204                                 If  configura tions(n).C redentials  IsNot Not hing Then        
205                                      user = c onfigurati ons(n).Cre dentials.W indows.Cli entCredent ial.Domain  & "\" & _        
206                                          conf igurations (n).Creden tials.Wind ows.Client Credential .UserName        
207                                 El se        
208                                      user = " default"        
209                                 En d If        
210                             Case E lse        
211                                 If  configura tions(n).C redentials  IsNot Not hing Then        
212                                      user = c onfigurati ons(n).Cre dentials.U serName.Us erName        
213                                 El se        
214                                      user = " default"        
215                                 En d If        
216                         End Select        
217          
218                         Console.Wr ite(vbLf &  "({0}) Se rver: {1},   Org: {2} ,  User: { 3}" & vbTa b, n + 1,  configurat ions(n).Se rverAddres s, _        
219                                        config urations(n ).Organiza tionName,  user)        
220                    Next  n        
221          
222                    Cons ole.WriteL ine()        
223          
224                    Cons ole.Write( vbLf & "Sp ecify the  saved serv er configu ration num ber (1-{0} ) [{0}] :  ", configu rations.Co unt)        
225                    Dim  input As S tring = Co nsole.Read Line()        
226                    Cons ole.WriteL ine()        
227                    If i nput = Str ing.Empty  Then        
228                         input = co nfiguratio ns.Count.T oString()        
229                    End  If        
230                    If N ot Int32.T ryParse(in put, confi gNumber) T hen        
231                         configNumb er = -1        
232                    End  If        
233          
234                    If c onfigNumbe r = 0 Then        
235                         addConfig  = True        
236                    Else If configN umber > 0  AndAlso co nfigNumber  <= config urations.C ount Then        
237                         ' Return t he organiz ation Uri.        
238                         config = c onfigurati ons(config Number - 1 )        
239                                               ' Reorder  the config uration li st and sav e it to fi le to save  the recen t configur ation as a  latest on e.         
240                         If configN umber <> c onfigurati ons.Count  Then        
241                             Dim te mp As Conf iguration  = configur ations(con figuration s.Count -  1)        
242                             config urations(c onfigurati ons.Count  - 1) = con figuration s(configNu mber - 1)        
243                             config urations(c onfigNumbe r - 1) = t emp        
244                         End If        
245                         addConfig  = False        
246                    Else        
247                         Throw New  InvalidOpe rationExce ption("The  specified  server co nfiguratio n does not  exist.")        
248                    End  If        
249                Else        
250                    addC onfig = Tr ue        
251                End If        
252          
253                If addCo nfig Then        
254                    ' Ge t the serv er address . If no va lue is ent ered, defa ult to Mic rosoft Dyn amics        
255                    ' CR M Online i n the Nort h American  data cent er.        
256                    conf ig.ServerA ddress = G etServerAd dress(ssl)        
257                    If S tring.IsNu llOrWhiteS pace(confi g.ServerAd dress) The n        
258                         config.Ser verAddress  = "crm.dy namics.com "        
259                    End  If        
260          
261          
262                    ' On e of the M icrosoft D ynamics CR M Online d ata center s.        
263                    If c onfig.Serv erAddress. EndsWith(" .dynamics. com", Stri ngComparis on.Invaria ntCultureI gnoreCase)  Then        
264                         ' Check if  the organ ization is  provision ed in Micr osoft Offi ce 365.        
265                         If GetOrgT ype(config .ServerAdd ress) Then        
266                             config .Discovery Uri = New  Uri(String .Format("h ttps://dis co.{0}/XRM Services/2 011/Discov ery.svc",  config.Ser verAddress ))        
267                         Else        
268                             config .Discovery Uri = New  Uri(String .Format("h ttps://dev .{0}/XRMSe rvices/201 1/Discover y.svc", co nfig.Serve rAddress))        
269          
270                             ' Get  or set the  device cr edentials.  This is r equired fo r Microsof t account  authentica tion.         
271                             config .DeviceCre dentials =  GetDevice Credential s()        
272                         End If        
273                         ' Check if  the serve r uses Sec ure Socket  Layer (ht tps).        
274                    Else If ssl The n        
275                         config.Dis coveryUri  = New Uri( String.For mat("https ://{0}/XRM Services/2 011/Discov ery.svc",  config.Ser verAddress ))        
276                    Else        
277                         config.Dis coveryUri  = New Uri( String.For mat("http: //{0}/XRMS ervices/20 11/Discove ry.svc", c onfig.Serv erAddress) )        
278                    End  If        
279          
280                    ' Ge t the targ et organiz ation.        
281                    conf ig.Organiz ationUri =  GetOrgani zationAddr ess()        
282                    conf igurations .Add(confi g)        
283                    Dim  length As  Integer =  configurat ions.Count        
284                    Dim  i As Integ er = lengt h - 2        
285                    ' Ch eck if a n ew configu ration alr eady exist s.         
286                    ' If  found, re order list  to show l atest in u se.                                              
287                    Do W hile i > 0        
288          
289                         If configu rations(co nfiguratio ns.Count -  1).Equals (configura tions(i))  Then        
290                             config urations.R emoveAt(i)        
291                         End If        
292                         i -= 1        
293                    Loop        
294                    ' Se t max conf igurations  to 9 othe rwise over write exis ting one.        
295                    If c onfigurati ons.Count  > 9 Then        
296                         configurat ions.Remov eAt(0)        
297                    End  If        
298                Else        
299                    ' Ge t the exis ting user' s logon cr edentials.        
300                    conf ig.Credent ials = Get UserLogonC redentials (config)        
301                End If        
302                SaveConf igurations ()        
303                Return c onfig        
304           En d Function        
305          
306           '' ' <summary >        
307           '' ' Discover s the orga nizations  that the c alling use r belongs  to.        
308           '' ' </summar y>        
309           '' ' <param n ame="servi ce">A Disc overy serv ice proxy  instance.< /param>        
310           '' ' <returns >Array con taining de tailed inf ormation o n each org anization  that         
311           '' ' the user  belongs t o.</return s>        
312           Pu blic Funct ion Discov erOrganiza tions(ByVa l service  As IDiscov eryService ) As Organ izationDet ailCollect ion        
313                If servi ce Is Noth ing Then        
314                    Thro w New Argu mentNullEx ception("s ervice")        
315                End If        
316                Dim orgR equest As  New Retrie veOrganiza tionsReque st()        
317                Dim orgR esponse As  RetrieveO rganizatio nsResponse  = CType(s ervice.Exe cute(orgRe quest), Re trieveOrga nizationsR esponse)        
318          
319                Return o rgResponse .Details        
320           En d Function        
321          
322           '' ' <summary >        
323           '' ' Finds a  specific o rganizatio n detail i n the arra y of organ ization de tails        
324           '' ' returned  from the  Discovery  service.        
325           '' ' </summar y>        
326           '' ' <param n ame=orgFri endlyName" >The frien dly name o f the orga nization t o find.</p aram>        
327           '' ' <param n ame="orgDe tails">Arr ay of orga nization d etail obje ct returne d from the  discovery  service.< /param>        
328           '' ' <returns >Organizat ion detail s or null  if the org anization  was not fo und.</retu rns>        
329           '' ' <seealso  cref="Dis coveryOrga nizations" />        
330           Pu blic Funct ion FindOr ganization (ByVal org FriendlyNa me As Stri ng, ByVal  orgDetails () As Orga nizationDe tail) As O rganizatio nDetail        
331                If Strin g.IsNullOr WhiteSpace (orgFriend lyName) Th en        
332                    Thro w New Argu mentNullEx ception("o rgFriendly Name")        
333                End If        
334                If orgDe tails Is N othing The n        
335                    Thro w New Argu mentNullEx ception("o rgDetails" )        
336                End If        
337                Dim orgD etail As O rganizatio nDetail =  Nothing        
338          
339                For Each  detail As  Organizat ionDetail  In orgDeta ils        
340                    If S tring.Comp are(detail .FriendlyN ame, orgFr iendlyName , StringCo mparison.I nvariantCu ltureIgnor eCase) = 0  Then        
341                         orgDetail  = detail        
342                         Exit For        
343                    End  If        
344                Next det ail        
345                Return o rgDetail        
346           En d Function        
347          
348           '' ' <summary >        
349           '' ' Reads a  server con figuration  file.        
350           '' ' Read the  configura tion from  disk, if i t exists,  at C:\User s\YourUser Name\AppDa ta\Roaming \CrmServer \Credentia ls.xml.        
351           '' ' </summar y>        
352           '' ' <returns >Is config uration se ttings alr eady avail able on di sk.</retur ns>        
353           Pu blic Funct ion ReadCo nfiguratio ns() As Bo olean        
354                Dim isCo nfigExist  As Boolean  = False        
355          
356                If confi gurations  Is Nothing  Then        
357                    conf igurations  = New Lis t(Of Confi guration)( )        
358                End If        
359          
360                If File. Exists(Crm ServiceHel perConstan ts.ServerC redentials File) Then        
361                    Dim  configurat ionsFromFi le As XEle ment = XEl ement.Load (CrmServic eHelperCon stants.Ser verCredent ialsFile)        
362                    For  Each confi g As XElem ent In con figuration sFromFile. Nodes()        
363                         Dim newCon fig As New  Configura tion()        
364                         Dim server Address =  config.Ele ment("Serv erAddress" )        
365                         If serverA ddress IsN ot Nothing  Then        
366                             If Not  String.Is NullOrEmpt y(serverAd dress.Valu e) Then        
367                                 ne wConfig.Se rverAddres s = server Address.Va lue        
368                             End If        
369                         End If        
370                         Dim organi zationName  = config. Element("O rganizatio nName")        
371                         If organiz ationName  IsNot Noth ing Then        
372                             If Not  String.Is NullOrEmpt y(organiza tionName.V alue) Then        
373                                 ne wConfig.Or ganization Name = org anizationN ame.Value        
374                             End If        
375                         End If        
376                         Dim discov eryUri = c onfig.Elem ent("Disco veryUri")        
377                         If discove ryUri IsNo t Nothing  Then        
378                             If Not  String.Is NullOrEmpt y(discover yUri.Value ) Then        
379                                 ne wConfig.Di scoveryUri  = New Uri (discovery Uri.Value)        
380                             End If        
381                         End If        
382                         Dim organi zationUri  = config.E lement("Or ganization Uri")        
383                         If organiz ationUri I sNot Nothi ng Then        
384                             If Not  String.Is NullOrEmpt y(organiza tionUri.Va lue) Then        
385                                 ne wConfig.Or ganization Uri = New  Uri(organi zationUri. Value)        
386                             End If        
387                         End If        
388                         Dim homeRe almUri = c onfig.Elem ent("HomeR ealmUri")        
389                         If homeRea lmUri IsNo t Nothing  Then        
390                             If Not  String.Is NullOrEmpt y(homeReal mUri.Value ) Then        
391                                 ne wConfig.Ho meRealmUri  = New Uri (homeRealm Uri.Value)        
392                             End If        
393                         End If        
394          
395                         Dim vendpo intType =  config.Ele ment("Endp ointType")        
396                         If vendpoi ntType IsN ot Nothing  Then        
397                             newCon fig.Endpoi ntType = R etrieveAut henticatio nType(vend pointType. Value)        
398                         End If        
399                         If config. Element("C redentials ").HasElem ents Then        
400                             newCon fig.Creden tials =        
401                                 Pa rseInCrede ntials(con fig.Elemen t("Credent ials"),        
402                                                      new Config.End pointType,        
403                                                      new Config.Ser verAddress  + ":" + n ewConfig.O rganizatio nName + ": " + config .Element(" Credential s").Elemen t("UserNam e").Value)        
404                         End If        
405                         If newConf ig.Endpoin tType = Au thenticati onProvider Type.LiveI d Then        
406                             newCon fig.Device Credential s = GetDev iceCredent ials()        
407                         End If        
408                         Dim userPr incipalNam e = config .Element(" UserPrinci palName")        
409                         If userPri ncipalName  IsNot Not hing Then        
410                             If Not  String.Is NullOrWhit eSpace(use rPrincipal Name.Value ) Then        
411                                 ne wConfig.Us erPrincipa lName = us erPrincipa lName.Valu e        
412                             End If        
413                         End If        
414                         configurat ions.Add(n ewConfig)        
415                    Next  config        
416                End If        
417          
418                If confi gurations. Count > 0  Then        
419                    isCo nfigExist  = True        
420                End If        
421          
422                Return i sConfigExi st        
423           En d Function        
424          
425           '' ' <summary >        
426           '' ' Writes a ll server  configurat ions to a  file.        
427           '' ' </summar y>        
428           '' ' <remarks >If the fi le exists,  it is ove rwritten.< /remarks>        
429           Pu blic Sub S aveConfigu rations()        
430                If confi gurations  Is Nothing  Then        
431                    Thro w New Null ReferenceE xception(" No server  connection  configura tions were  found.")        
432                End If        
433          
434                Dim file  As New Fi leInfo(Crm ServiceHel perConstan ts.ServerC redentials File)        
435          
436                ' Create  directory  if it doe s not exis t.        
437                If Not f ile.Direct ory.Exists  Then        
438                    file .Directory .Create()        
439                End If        
440          
441                ' Replac e file if  it exists.        
442                Using fs  As FileSt ream = fil e.Open(Fil eMode.Crea te, FileAc cess.Write , FileShar e.None)        
443                    Usin g writer A s New XmlT extWriter( fs, Encodi ng.UTF8)        
444                         writer.For matting =  Formatting .Indented        
445                         writer.Wri teStartDoc ument()        
446                         writer.Wri teStartEle ment("Conf igurations ")        
447                         writer.Wri teFullEndE lement()        
448                         writer.Wri teEndDocum ent()        
449                    End  Using        
450                End Usin g        
451          
452                For Each  config As  Configura tion In co nfiguratio ns        
453                    Save Configurat ion(CrmSer viceHelper Constants. ServerCred entialsFil e, config,  True)        
454                Next con fig        
455           En d Sub        
456          
457           '' ' <summary >        
458           '' ' Writes a  server co nfiguratio n to a fil e.        
459           '' ' </summar y>        
460           '' ' <param n ame="pathn ame">The f ile name a nd system  path of th e output c onfigurati on file.</ param>        
461           '' ' <param n ame="confi g">A serve r connecti on configu ration.</p aram>        
462           '' ' <param n ame="appen d">If true , the conf iguration  is appende d to the f ile, other wise a new  file        
463           '' ' is creat ed.</param >        
464           Pu blic Sub S aveConfigu ration(ByV al pathnam e As Strin g, ByVal c onfig As C onfigurati on, ByVal  append As  Boolean)        
465                If Strin g.IsNullOr WhiteSpace (pathname)  Then        
466                    Thro w New Argu mentNullEx ception("p athname")        
467                End If        
468                If confi g Is Nothi ng Then        
469                    Thro w New Argu mentNullEx ception("c onfig")        
470                End If        
471                ' Target  is the ke y with whi ch associa ted creden tials can  be fetched  from wind ows creden tials mana ger.        
472                Dim targ et As Stri ng = confi g.ServerAd dress & ": " & config .Organizat ionName        
473                If Nothi ng IsNot c onfig.Cred entials Th en        
474                    Sele ct Case co nfig.Endpo intType        
475                         Case Authe nticationP roviderTyp e.ActiveDi rectory        
476                             target  = target  & ":" & co nfig.Crede ntials.Win dows.Clien tCredentia l.UserName        
477                         Case Authe nticationP roviderTyp e.LiveId,        
478                             Authen ticationPr oviderType .Federatio n,        
479                             Authen ticationPr oviderType .OnlineFed eration        
480                             target  = target  & ":" & co nfig.Crede ntials.Use rName.User Name        
481                         Case Else        
482                             target  = String. Empty        
483                    End  Select        
484                End If        
485          
486                Dim conf igurations FromFile A s XElement  = XElemen t.Load(pat hname)        
487                Dim newC onfig As N ew XElemen t("Configu ration",        
488                                                 New XEle ment("Serv erAddress" ,        
489                                                               confi g.ServerAd dress),        
490                                                 New XEle ment("Orga nizationNa me",        
491                                                               confi g.Organiza tionName),        
492                                                 New XEle ment("Disc overyUri",        
493                                                               If(co nfig.Disco veryUri Is Not Nothin g,        
494                                                                  co nfig.Disco veryUri.Or iginalStri ng,        
495                                                                  St ring.Empty )),        
496                                                 New XEle ment("Orga nizationUr i",        
497                                                               If(co nfig.Organ izationUri  IsNot Not hing,        
498                                                                  co nfig.Organ izationUri .OriginalS tring,        
499                                                                  St ring.Empty )),        
500                                                 New XEle ment("Home RealmUri",        
501                                                               If(co nfig.HomeR ealmUri Is Not Nothin g,        
502                                                                  co nfig.HomeR ealmUri.Or iginalStri ng,        
503                                                                  St ring.Empty )),        
504                                                 ParseOut Credential s(config.C redentials ,        
505                                                                       config.E ndpointTyp e,        
506                                                                       target),        
507                                                 New XEle ment("Endp ointType",        
508                                                               confi g.Endpoint Type.ToStr ing()),        
509                                                 New XEle ment("User PrincipalN ame",        
510                                                               If(co nfig.UserP rincipalNa me IsNot N othing,        
511                                                                  co nfig.UserP rincipalNa me, String .Empty)        
512                                                              )        
513                                                )        
514          
515                If appen d Then        
516                    conf igurations FromFile.A dd(newConf ig)        
517                Else        
518                    conf igurations FromFile.R eplaceAll( newConfig)        
519                End If        
520          
521                Using wr iter As Ne w XmlTextW riter(path name, Enco ding.UTF8)        
522                    writ er.Formatt ing = Form atting.Ind ented        
523                    conf igurations FromFile.S ave(writer )        
524                End Usin g        
525           En d Sub        
526          
527           '' ' <summary >        
528           '' ' Obtains  the user's  logon cre dentials f or the tar get server .        
529           '' ' </summar y>        
530           '' ' <param n ame="confi g">An inst ance of th e Configur ation.</pa ram>        
531           '' ' <returns >Logon cre dentials o f the user .</returns >        
532           Pu blic Share d Function  GetUserLo gonCredent ials(ByVal  config As  ServerCon nection.Co nfiguratio n) As Clie ntCredenti als        
533                Dim cred entials As  New Clien tCredentia ls()        
534                Dim user Name As St ring        
535                Dim pass word As Se cureString        
536                Dim doma in As Stri ng        
537                Dim isCr edentialEx ist As Boo lean = If( config.Cre dentials I sNot Nothi ng, True,  False)        
538                Select C ase config .EndpointT ype        
539                    ' An  on-premis es Microso ft Dynamic s CRM serv er deploym ent.         
540                    Case  Authentic ationProvi derType.Ac tiveDirect ory        
541                         ' Uses cre dentials f rom window s credenti al manager  for earli er saved c onfigurati on.        
542                         If isCrede ntialExist  AndAlso ( Not String .IsNullOrW hiteSpace( config.Org anizationN ame)) Then        
543                             domain  = config. Credential s.Windows. ClientCred ential.Dom ain        
544                             userNa me = confi g.Credenti als.Window s.ClientCr edential.U serName        
545                             If Str ing.IsNull OrWhiteSpa ce(config. Credential s.Windows. ClientCred ential.Pas sword) The n        
546                                 Co nsole.Writ e(vbLf & " Enter doma in\usernam e: ")        
547                                 Co nsole.Writ eLine(conf ig.Credent ials.Windo ws.ClientC redential. Domain _        
548                                                     & "\ " & config .Credentia ls.Windows .ClientCre dential.Us erName)        
549          
550                                 Co nsole.Writ e("        Enter Pass word: ")        
551                                 pa ssword = R eadPasswor d()        
552                             Else        
553                                 pa ssword = c onfig.Cred entials.Wi ndows.Clie ntCredenti al.SecureP assword        
554                             End If        
555                             ' Uses  default c redentials  saved in  windows cr edential m anager for  current o rganizatio n.        
556                         ElseIf (No t isCreden tialExist)  AndAlso ( Not String .IsNullOrW hiteSpace( config.Org anizationN ame)) Then        
557                             Return  Nothing        
558                             ' Prom pts users  to enter c redential  for curren t organiza tion.        
559                         Else        
560                             Dim do mainAndUse rName() As  String        
561                             Do        
562                                 Co nsole.Writ e(vbLf & " Enter doma in\usernam e: ")        
563                                 do mainAndUse rName = Co nsole.Read Line().Spl it("\"c)        
564          
565                                 '  If user do  not choos e to enter  user name        
566                                 '  then try t o use defa ult creden tial from  windows cr edential m anager.        
567                                 If  domainAnd UserName.L ength = 1  AndAlso        
568                                      String.I sNullOrWhi teSpace(do mainAndUse rName(0))  Then        
569                                      Return N othing        
570                                 En d If        
571                             Loop W hile domai nAndUserNa me.Length  <> 2 OrEls e        
572                                 St ring.IsNul lOrWhiteSp ace(domain AndUserNam e(0)) OrEl se        
573                                 St ring.IsNul lOrWhiteSp ace(domain AndUserNam e(1))        
574          
575                             domain  = domainA ndUserName (0)        
576                             userNa me = domai nAndUserNa me(1)        
577          
578                             Consol e.Write("        Ente r Password : ")        
579                             passwo rd = ReadP assword()        
580                         End If        
581                         If Nothing  IsNot pas sword Then        
582                             creden tials.Wind ows.Client Credential  =        
583                                 Ne w System.N et.Network Credential (userName,  password,  domain)        
584                         Else        
585                             creden tials.Wind ows.Client Credential  = Nothing        
586                         End If        
587          
588                         ' A Micros oft Dynami cs CRM Onl ine server  deploymen t.         
589                    Case  Authentic ationProvi derType.Li veId,        
590                         Authentica tionProvid erType.Fed eration,        
591                         Authentica tionProvid erType.Onl ineFederat ion        
592                         ' An inter net-facing  deploymen t (IFD) of  Microsoft  Dynamics  CRM.                   
593                         ' Managed  Identity/F ederated I dentity us ers using  Microsoft  Office 365 .        
594                         ' Use save d credenti als.        
595                         If isCrede ntialExist  Then        
596                             userNa me = confi g.Credenti als.UserNa me.UserNam e        
597                             If Str ing.IsNull OrWhiteSpa ce(config. Credential s.UserName .Password)  Then        
598                                 Co nsole.Writ e(vbLf & "  Enter Use rname: ")        
599                                 Co nsole.Writ eLine(conf ig.Credent ials.UserN ame.UserNa me)        
600          
601                                 Co nsole.Writ e(" Enter  Password:  ")        
602                                 pa ssword = R eadPasswor d()        
603                             Else        
604                                 pa ssword = C onvertToSe cureString (config.Cr edentials. UserName.P assword)        
605                             End If        
606                             ' For  OnlineFede ration env ironments,  initially  try to au thenticate  with the  current Us erPrincipa lName        
607                             ' for  single sig n-on scena rio.        
608                         ElseIf con fig.Endpoi ntType = A uthenticat ionProvide rType.Onli neFederati on AndAlso        
609                             config .AuthFailu reCount =  0 AndAlso        
610                             (Not S tring.IsNu llOrWhiteS pace(UserP rincipal.C urrent.Use rPrincipal Name)) The n        
611                             config .UserPrinc ipalName =  UserPrinc ipal.Curre nt.UserPri ncipalName        
612                             Return  Nothing        
613                             ' Othe rwise requ est userna me and pas sword.        
614                         Else        
615                             config .UserPrinc ipalName =  String.Em pty        
616                             If con fig.Endpoi ntType = A uthenticat ionProvide rType.Live Id Then        
617                                 Co nsole.Writ e(vbLf & "  Enter Mic rosoft acc ount: ")        
618                             Else        
619                                 Co nsole.Writ e(vbLf & "  Enter Use rname: ")        
620                             End If        
621                             userNa me = Conso le.ReadLin e()        
622                             If Str ing.IsNull OrWhiteSpa ce(userNam e) Then        
623                                 Re turn Nothi ng        
624                             End If        
625          
626                             Consol e.Write("  Enter Pass word: ")        
627                             passwo rd = ReadP assword()        
628                         End If        
629                         credential s.UserName .UserName  = userName        
630                         credential s.UserName .Password  = ConvertT oUnsecureS tring(pass word)        
631                    Case  Else        
632                         credential s = Nothin g        
633                End Sele ct        
634                Return c redentials        
635           En d Function        
636          
637           '' ' <summary >        
638           '' ' Prompts  user to en ter passwo rd in cons ole window          
639           '' ' and capt ure the en tered pass word into  SecureStri ng.        
640           '' ' </summar y>        
641           '' ' <returns >Password  stored in  a secure s tring.</re turns>        
642           Pu blic Share d Function  ReadPassw ord() As S ecureStrin g        
643                Dim ssPa ssword As  New Secure String()        
644          
645                Dim info  As Consol eKeyInfo =  Console.R eadKey(Tru e)        
646                Do While  info.Key  <> Console Key.Enter        
647                    If i nfo.Key =  ConsoleKey .Backspace  Then        
648                         If ssPassw ord.Length  <> 0 Then        
649                             ssPass word.Remov eAt(ssPass word.Lengt h - 1)        
650                             Consol e.Write(vb Back & " "  & vbBack)  ' erase l ast char        
651                         End If        
652                    Else If info.Ke yChar >= "  "c Then '  no contro l chars        
653                         ssPassword .AppendCha r(info.Key Char)        
654                         Console.Wr ite("*")        
655                    End  If        
656                    info  = Console .ReadKey(T rue)        
657                Loop        
658          
659                Console. WriteLine( )        
660                Console. WriteLine( )        
661          
662                ' Lock t he secure  string pas sword.        
663                ssPasswo rd.MakeRea dOnly()        
664          
665                Return s sPassword        
666           En d Function        
667          
668           '' ' <summary >        
669           '' ' Generic  method to  obtain dis covery/org anization  service pr oxy instan ce.        
670           '' ' </summar y>        
671           '' ' <typepar am name="T Service">        
672           '' ' Set IDis coveryServ ice or IOr ganization Service ty pe         
673           '' ' to reque st respect ive servic e proxy in stance.        
674           '' ' </typepa ram>        
675           '' ' <typepar am name="T Proxy">        
676           '' ' Set the  return typ e to eithe r Discover yServicePr oxy         
677           '' ' or Organ izationSer viceProxy  type based  on TServi ce type.        
678           '' ' </typepa ram>        
679           '' ' <param n ame="curre ntConfig"> An instanc e of exist ing Config uration</p aram>        
680           '' ' <returns >An instan ce of TPro xy         
681           '' ' i.e. Dis coveryServ iceProxy o r Organiza tionServic eProxy</re turns>        
682           Pu blic Share d Function  GetProxy( Of TServic e As Class ,        
683                                                   TProxy  As Servic eProxy(Of  TService)) (ByVal cur rentConfig  As Server Connection .Configura tion) As T Proxy        
684                ' Check  if it is o rganizatio n service  proxy requ est.        
685                Dim isOr gServiceRe quest As B oolean = G etType(TSe rvice).Equ als(GetTyp e(IOrganiz ationServi ce))        
686          
687                ' Get ap propriate  Uri from C onfigurati on.        
688                Dim serv iceUri As  Uri = If(i sOrgServic eRequest,        
689                                             c urrentConf ig.Organiz ationUri,        
690                                             c urrentConf ig.Discove ryUri)        
691          
692                ' Set se rvice mana gement for  either or ganization  service U ri or disc overy serv ice Uri.        
693                ' For or ganization  service U ri, if ser vice manag ement exis ts         
694                ' then u se it from  cache. Ot herwise cr eate new s ervice man agement fo r current  organizati on.        
695                Dim serv iceManagem ent As ISe rviceManag ement(Of T Service) =        
696                    If(i sOrgServic eRequest A ndAlso Not hing IsNot  currentCo nfig.Organ izationSer viceManage ment,        
697                       C Type(curre ntConfig.O rganizatio nServiceMa nagement,  IServiceMa nagement(O f TService )),        
698                       S erviceConf igurationF actory.Cre ateManagem ent(Of TSe rvice)(ser viceUri))        
699          
700                If isOrg ServiceReq uest Then        
701                    If c urrentConf ig.Organiz ationToken Response I s Nothing  Then        
702                         currentCon fig.Organi zationServ iceManagem ent =        
703                             CType( serviceMan agement, I ServiceMan agement(Of  IOrganiza tionServic e))        
704                    End  If        
705                    ' Se t the Endp ointType i n the curr ent Config uration ob ject         
706                    ' wh ile adding  new confi guration u sing disco very servi ce proxy.        
707                Else        
708                    ' Ge t the Endp ointType.        
709                    curr entConfig. EndpointTy pe = servi ceManageme nt.Authent icationTyp e        
710                    ' Ge t the logo n credenti als.        
711                    curr entConfig. Credential s = GetUse rLogonCred entials(cu rrentConfi g)        
712                End If        
713          
714                ' Set th e credenti als.        
715                Dim auth Credential s As New A uthenticat ionCredent ials()        
716          
717                ' If Use rPrincipal Name exist s, use it.  Otherwise , set the  logon cred entials fr om the con figuration .        
718                If Not S tring.IsNu llOrWhiteS pace(curre ntConfig.U serPrincip alName) Th en        
719                    ' Si ngle sing- on with th e Federate d Identity  organizat ion using  current Us erPrinicip alName.        
720                    auth Credential s.UserPrin cipalName  = currentC onfig.User PrincipalN ame        
721                Else        
722                    auth Credential s.ClientCr edentials  = currentC onfig.Cred entials        
723                End If        
724          
725                Dim clas sType As T ype        
726          
727                ' Obtain  discovery /organizat ion servic e proxy fo r Federate d,        
728                ' Micros oft accoun t and Onli neFederate d environm ents.         
729                If curre ntConfig.E ndpointTyp e <> Authe nticationP roviderTyp e.ActiveDi rectory Th en        
730                    If c urrentConf ig.Endpoin tType = Au thenticati onProvider Type.LiveI d Then        
731                         authCreden tials.Supp ortingCred entials =  New Authen ticationCr edentials( )        
732                         authCreden tials.Supp ortingCred entials.Cl ientCreden tials = cu rrentConfi g.DeviceCr edentials        
733                    End  If        
734          
735                    Dim  tokenCrede ntials As  Authentica tionCreden tials = se rviceManag ement.Auth enticate(a uthCredent ials)        
736          
737                    If i sOrgServic eRequest T hen        
738                         ' Set Secu rityTokenR esponse fo r the curr ent organi zation.        
739                         currentCon fig.Organi zationToke nResponse  = tokenCre dentials.S ecurityTok enResponse        
740                         ' Set clas sType to M anagedToke nOrganizat ionService Proxy.        
741                         classType  = GetType( ManagedTok enOrganiza tionServic eProxy)        
742          
743                    Else        
744                         ' Set clas sType to M anagedToke nDiscovery ServicePro xy.        
745                         classType  = GetType( ManagedTok enDiscover yServicePr oxy)        
746                    End  If        
747          
748                    ' In vokes Mana gedTokenOr ganization ServicePro xy or Mana gedTokenDi scoverySer viceProxy         
749                    ' (I ServiceMan agement<TS ervice>, S ecurityTok enResponse ) construc tor.        
750                    Retu rn CType(c lassType.G etConstruc tor(New Ty pe() {GetT ype(IServi ceManageme nt(Of TSer vice)), Ge tType(Secu rityTokenR esponse)}) .Invoke(Ne w Object()  {serviceM anagement,  tokenCred entials.Se curityToke nResponse} ), TProxy)        
751                End If        
752          
753                ' Obtain  discovery /organizat ion servic e proxy fo r ActiveDi rectory en vironment.        
754                If isOrg ServiceReq uest Then        
755                    clas sType = Ge tType(Mana gedTokenOr ganization ServicePro xy)        
756                Else        
757                    clas sType = Ge tType(Mana gedTokenDi scoverySer viceProxy)        
758                End If        
759          
760                ' Invoke s ManagedT okenDiscov eryService Proxy or M anagedToke nOrganizat ionService Proxy         
761                ' (IServ iceManagem ent<TServi ce>, Clien tCredentia ls) constr uctor.        
762                Return C Type(class Type.GetCo nstructor( New Type()  {GetType( IServiceMa nagement(O f TService )), GetTyp e(ClientCr edentials) }).Invoke( New Object () {servic eManagemen t, authCre dentials.C lientCrede ntials}),  TProxy)        
763           En d Function        
764          
765           '' ' <summary >        
766           '' ' Convert  SecureStri ng to unse cure strin g.        
767           '' ' </summar y>        
768           '' ' <param n ame="secur ePassword" >Pass Secu reString f or convers ion.</para m>        
769           '' ' <returns >unsecure  string</re turns>        
770           Pu blic Share d Function  ConvertTo UnsecureSt ring(ByVal  securePas sword As S ecureStrin g) As Stri ng        
771                If secur ePassword  Is Nothing  Then        
772                    Thro w New Argu mentNullEx ception("s ecurePassw ord")        
773                End If        
774          
775                Dim unma nagedStrin g As IntPt r = IntPtr .Zero        
776                Try        
777                    unma nagedStrin g = Marsha l.SecureSt ringToGlob alAllocUni code(secur ePassword)        
778                    Retu rn Marshal .PtrToStri ngUni(unma nagedStrin g)        
779                Finally        
780                    Mars hal.ZeroFr eeGlobalAl locUnicode (unmanaged String)        
781                End Try        
782           En d Function        
783          
784           '' ' <summary >        
785           '' ' Convert  unsecure s tring to S ecureStrin g.        
786           '' ' </summar y>        
787           '' ' <param n ame="passw ord">Pass  unsecure s tring for  conversion .</param>        
788           '' ' <returns >SecureStr ing</retur ns>        
789           Pu blic Share d Function  ConvertTo SecureStri ng(ByVal p assword As  String) A s SecureSt ring        
790                If passw ord Is Not hing Then        
791                    Thro w New Argu mentNullEx ception("p assword")        
792                End If        
793          
794                Dim secu rePassword  = New Sec ureString( )        
795                For Each  c As Char  In passwo rd        
796                    secu rePassword .AppendCha r(c)        
797                Next c        
798                securePa ssword.Mak eReadOnly( )        
799                Return s ecurePassw ord        
800           En d Function        
801   #End Regio n ' Public  methods        
802          
803   #Region "P rotected m ethods"        
804          
805           '' ' <summary >        
806           '' ' Obtains  the name a nd port of  the serve r running  the Micros oft Dynami cs CRM        
807           '' ' Discover y service.        
808           '' ' </summar y>        
809           '' ' <returns >The serve r's networ k name and  optional  TCP/IP por t.</return s>        
810           Pr otected Ov erridable  Function G etServerAd dress(<Sys tem.Runtim e.InteropS ervices.Ou t()> ByRef  ssl As Bo olean) As  String        
811                ssl = Fa lse        
812          
813                Console. Write("Ent er a CRM s erver name  and port  [crm.dynam ics.com]:  ")        
814                Dim serv er As Stri ng = Conso le.ReadLin e()        
815          
816                If serve r.EndsWith (".dynamic s.com") Or Else Strin g.IsNullOr WhiteSpace (server) T hen        
817                    ssl  = True        
818                Else        
819                    Cons ole.Write( "Is this s erver conf igured for  Secure So cket Layer  (https) ( y/n) [n]:  ")        
820                    Dim  answer As  String = C onsole.Rea dLine()        
821          
822                    If a nswer = "y " OrElse a nswer = "Y " Then        
823                         ssl = True        
824                    End  If        
825                End If        
826          
827                Return s erver        
828           En d Function        
829          
830           '' ' <summary >        
831           '' ' Is this  organizati on provisi oned in Mi crosoft Of fice 365?        
832           '' ' </summar y>        
833           '' ' <param n ame="serve r">The ser ver's netw ork name.< /param>        
834           Pr otected Ov erridable  Function G etOrgType( ByVal serv er As Stri ng) As Boo lean        
835                Dim isO3 65Org As B oolean = F alse        
836                If Strin g.IsNullOr WhiteSpace (server) T hen        
837                    Retu rn isO365O rg        
838                End If        
839                If serve r.IndexOf( "."c) = -1  Then        
840                    Retu rn isO365O rg        
841                End If        
842          
843                Console. Write("Is  this organ ization pr ovisioned  in Microso ft Office  365 (y/n)  [n]: ")        
844                Dim answ er As Stri ng = Conso le.ReadLin e()        
845          
846                If answe r = "y" Or Else answe r = "Y" Th en        
847                    isO3 65Org = Tr ue        
848                End If        
849          
850                Return i sO365Org        
851           En d Function        
852          
853           '' ' <summary >        
854           '' ' Obtains  the web ad dress (Uri ) of the t arget orga nization.        
855           '' ' </summar y>        
856           '' ' <returns >Uri of th e organiza tion servi ce or an e mpty strin g.</return s>        
857           Pr otected Ov erridable  Function G etOrganiza tionAddres s() As Uri        
858                Using se rviceProxy  As Discov eryService Proxy = Ge tDiscovery Proxy()        
859                    ' Ob tain organ ization in formation  from the D iscovery s ervice.         
860                    If s erviceProx y IsNot No thing Then        
861                         ' Obtain i nformation  about the  organizat ions that  the system  user belo ngs to.        
862                         Dim orgs A s Organiza tionDetail Collection  = Discove rOrganizat ions(servi ceProxy)        
863          
864                         If orgs.Co unt > 0 Th en        
865                             Consol e.WriteLin e(vbLf & " List of or ganization s that you  belong to :")        
866                             For n  As Integer  = 0 To or gs.Count -  1        
867                                 Co nsole.Writ e(vbLf & " ({0}) {1}  ({2})" & v bTab, n +  1, orgs(n) .FriendlyN ame, orgs( n).UrlName )        
868                             Next n        
869          
870                             Consol e.Write(vb Lf & vbLf  & "Specify  an organi zation num ber (1-{0} ) [1]: ",  orgs.Count )        
871                             Dim in put As Str ing = Cons ole.ReadLi ne()        
872                             If inp ut = Strin g.Empty Th en        
873                                 in put = "1"        
874                             End If        
875                             Dim or gNumber As  Integer        
876                             Int32. TryParse(i nput, orgN umber)        
877                             If org Number > 0  AndAlso o rgNumber < = orgs.Cou nt Then        
878                                 co nfig.Organ izationNam e = orgs(o rgNumber -  1).Friend lyName        
879                                 '  Return the  organizat ion Uri.        
880                                 Re turn New U ri(orgs(or gNumber -  1).Endpoin ts(Endpoin tType.Orga nizationSe rvice))        
881                             Else        
882                                 Th row New In validOpera tionExcept ion("The s pecified o rganizatio n does not  exist.")        
883                             End If        
884                         Else        
885                             Consol e.WriteLin e(vbLf & " You do not  belong to  any organ izations o n the spec ified serv er.")        
886                             Return  New Uri(S tring.Empt y)        
887                         End If        
888                    Else        
889                         Throw New  InvalidOpe rationExce ption("An  invalid se rver name  was specif ied.")        
890                    End  If        
891                End Usin g        
892           En d Function        
893          
894           '' ' <summary >        
895           '' ' Get the  device cre dentials b y either l oading fro m the loca l cache         
896           '' ' or reque st new dev ice creden tials by r egistering  the devic e.        
897           '' ' </summar y>        
898           '' ' <returns >Device Cr edentials. </returns>        
899           Pr otected Ov erridable  Function G etDeviceCr edentials( ) As Clien tCredentia ls        
900                Return M icrosoft.C rm.Service s.Utility. DeviceIdMa nager.Load OrRegister Device()        
901           En d Function        
902          
903           '' ' <summary >        
904           '' ' Get the  discovery  service pr oxy based  on existin g configur ation data .        
905           '' ' Added ne w way of g etting dis covery pro xy.        
906           '' ' Also pre serving ol d way of g etting dis covery pro xy to supp ort old sc enarios.        
907           '' ' </summar y>        
908           '' ' <returns >An instan ce of Disc overyServi ceProxy</r eturns>        
909           Pr ivate Func tion GetDi scoveryPro xy() As Di scoverySer viceProxy        
910                Try        
911                    ' Ob tain the d iscovery s ervice pro xy.        
912                    Dim  discoveryP roxy As Di scoverySer viceProxy  =        
913                         GetProxy(O f IDiscove ryService,  Discovery ServicePro xy)(Me.con fig)        
914                    ' Ch ecking aut henticatio n by invok ing some S DK methods .        
915                    disc overyProxy .Execute(N ew Retriev eOrganizat ionsReques t())        
916                    Retu rn discove ryProxy        
917                Catch ex  As System .ServiceMo del.Securi ty.Securit yAccessDen iedExcepti on        
918                    ' If  authentic ation fail ed using c urrent Use rPrincipal Name,         
919                    ' re quest User Name and P assword to  try to au thenticate  using use r credenti als.        
920                    If ( Not String .IsNullOrW hiteSpace( config.Use rPrincipal Name)) And Also        
921                         ex.Message .Contains( "Access is  denied.")  Then        
922                         config.Aut hFailureCo unt = CSho rt(config. AuthFailur eCount + 1 )        
923                    Else        
924                         Throw ex        
925                    End  If        
926                End Try        
927                ' You ca n also cat ch other e xceptions  to handle  a specific  situation  in your c ode, for e xample,         
928                '      S ystem.Serv iceModel.S ecurity.Ex piredSecur ityTokenEx ception        
929                '      S ystem.Serv iceModel.S ecurity.Me ssageSecur ityExcepti on        
930                '      S ystem.Serv iceModel.S ecurity.Se curityNego tiationExc eption                          
931          
932                ' Second  trial to  obtain the  discovery  service p roxy in ca se of sing le sign-on  failure.        
933                Return G etProxy(Of  IDiscover yService,  DiscoveryS erviceProx y)(Me.conf ig)        
934          
935           En d Function        
936          
937           '' ' <summary >        
938           '' ' Verify p assed stri ngs with t he support ed Authent icationPro viderType.        
939           '' ' </summar y>        
940           '' ' <param n ame="authT ype">Strin g Authenti cationType </param>        
941           '' ' <returns >Supported  Authentic atoinProvi derType</r eturns>        
942           Pr ivate Func tion Retri eveAuthent icationTyp e(ByVal au thType As  String) As  Authentic ationProvi derType        
943                Select C ase authTy pe        
944                    Case  "ActiveDi rectory"        
945                         Return Aut henticatio nProviderT ype.Active Directory        
946                    Case  "LiveId"        
947                         Return Aut henticatio nProviderT ype.LiveId        
948                    Case  "Federati on"        
949                         Return Aut henticatio nProviderT ype.Federa tion        
950                    Case  "OnlineFe deration"        
951                         Return Aut henticatio nProviderT ype.Online Federation        
952                    Case  Else        
953                         Throw New  ArgumentEx ception(St ring.Forma t("{0} is  not a vali d authenti cation typ e", authTy pe))        
954                End Sele ct        
955           En d Function        
956          
957           '' ' <summary >        
958           '' ' Parse cr edentials  from an XM L node to  required C lientCrede ntials dat a type         
959           '' ' based on  passed Au thenticati onProvider Type.        
960           '' ' </summar y>        
961           '' ' <param n ame="crede ntials">Cr edential X ML node.</ param>        
962           '' ' <param n ame="endpo intType">A uthenticat ionProvide rType of t he credent ial.</para m>        
963           '' ' <param n ame="targe t">Target  is the key  with whic h associat ed credent ials can b e fetched. </param>        
964           '' ' <returns >Required  ClientCred entials ty pe.</retur ns>        
965           Pr ivate Func tion Parse InCredenti als(ByVal  credential s As XElem ent, ByVal  endpointT ype As Aut henticatio nProviderT ype, ByVal  target As  String) A s ClientCr edentials        
966                Dim resu lt As New  ClientCred entials()        
967                If crede ntials.Has Elements T hen        
968                    Dim  cred As Cr edential =  Credentia lManager.R eadCredent ials(targe t)        
969                    Sele ct Case en dpointType        
970                         Case Authe nticationP roviderTyp e.ActiveDi rectory        
971                             If Not hing IsNot  cred AndA lso cred.U serName.Co ntains("\" ) Then        
972                                 Di m domainAn dUser() As  String =  cred.UserN ame.Split( "\"c)        
973                                 re sult.Windo ws.ClientC redential  = New Syst em.Net.Net workCreden tial() Wit h {.UserNa me = domai nAndUser(1 ), .Domain  = domainA ndUser(0),  .Password  = cred.Pa ssword}        
974                             Else        
975                                 re sult.Windo ws.ClientC redential  = New Syst em.Net.Net workCreden tial() Wit h {.UserNa me = crede ntials.Ele ment("User Name").Val ue, .Domai n = creden tials.Elem ent("Domai n").Value}        
976                             End If        
977                         Case Authe nticationP roviderTyp e.LiveId,  Authentica tionProvid erType.Fed eration, A uthenticat ionProvide rType.Onli neFederati on        
978                             If Not hing IsNot  cred Then        
979                                 re sult.UserN ame.UserNa me = cred. UserName        
980                                 re sult.UserN ame.Passwo rd = cred. Password        
981                             Else        
982                                 re sult.UserN ame.UserNa me = crede ntials.Ele ment("User Name").Val ue        
983                             End If        
984                         Case Else        
985                    End  Select        
986                Else        
987                    Retu rn Nothing        
988                End If        
989          
990                Return r esult        
991           En d Function        
992          
993           '' ' <summary >        
994           '' ' Parse Cl ientCreden tials into  XML node.          
995           '' ' </summar y>        
996           '' ' <param n ame="clien tCredentia ls_Renamed ">ClientCr edentials  type.</par am>        
997           '' ' <param n ame="endpo intType">A uthenticat ionProvide rType of t he credent ials.</par am>        
998           '' ' <param n ame="targe t">Target  is the key  with whic h associat ed credent ials can b e fetched. </param>        
999           '' ' <returns >XML node  containing  credentia ls data.</ returns>        
1000           Pr ivate Func tion Parse OutCredent ials(ByVal  clientCre dentials_R enamed As  ClientCred entials, B yVal endpo intType As  Authentic ationProvi derType, B yVal targe t As Strin g) As XEle ment        
1001                If clien tCredentia ls_Renamed  IsNot Not hing Then        
1002                    Dim  cred As Cr edential =  Credentia lManager.R eadCredent ials(targe t)        
1003                    Sele ct Case en dpointType        
1004                         Case Authe nticationP roviderTyp e.ActiveDi rectory        
1005                             If cre d Is Nothi ng Then        
1006                                 '  Add entry  in windows  credentia l manager  for future  use.        
1007                                 If  Not Strin g.IsNullOr WhiteSpace (clientCre dentials_R enamed.Win dows.Clien tCredentia l.Password ) Then        
1008                                      Credenti alManager. WriteCrede ntials(tar get, New C redential( clientCred entials_Re named.Wind ows.Client Credential .Domain &  "\" & clie ntCredenti als_Rename d.Windows. ClientCred ential.Use rName, cli entCredent ials_Renam ed.Windows .ClientCre dential.Pa ssword), T rue)        
1009                                 En d If        
1010                             Else        
1011                                 '  Replace if  the passw ord has be en changed .        
1012                                 If  Not clien tCredentia ls_Renamed .Windows.C lientCrede ntial.Pass word.Equal s(cred.Pas sword) The n        
1013                                      Credenti alManager. DeleteCred entials(ta rget, Fals e)        
1014                                      Credenti alManager. WriteCrede ntials(tar get, New C redential( clientCred entials_Re named.Wind ows.Client Credential .Domain &  "\" & clie ntCredenti als_Rename d.Windows. ClientCred ential.Use rName, cli entCredent ials_Renam ed.Windows .ClientCre dential.Pa ssword), T rue)        
1015                                 En d If        
1016                             End If        
1017                             Return  New XElem ent("Crede ntials", N ew XElemen t("UserNam e", client Credential s_Renamed. Windows.Cl ientCreden tial.UserN ame), New  XElement(" Domain", c lientCrede ntials_Ren amed.Windo ws.ClientC redential. Domain))        
1018                         Case Authe nticationP roviderTyp e.LiveId,  Authentica tionProvid erType.Fed eration, A uthenticat ionProvide rType.Onli neFederati on        
1019                             If cre d Is Nothi ng Then        
1020                                 '  Add entry  in windows  credentia l manager  for future  use.        
1021                                 If  Not Strin g.IsNullOr WhiteSpace (clientCre dentials_R enamed.Use rName.Pass word) Then        
1022                                      Credenti alManager. WriteCrede ntials(tar get, New C redential( clientCred entials_Re named.User Name.UserN ame, clien tCredentia ls_Renamed .UserName. Password),  True)        
1023                                 En d If        
1024                             Else        
1025                                 '  Replace if  the passw ord has be en changed .        
1026                                 If  Not clien tCredentia ls_Renamed .UserName. Password.E quals(cred .Password)  Then        
1027                                      Credenti alManager. DeleteCred entials(ta rget, Fals e)        
1028                                      Credenti alManager. WriteCrede ntials(tar get, New C redential( clientCred entials_Re named.User Name.UserN ame, clien tCredentia ls_Renamed .UserName. Password),  True)        
1029                                 En d If        
1030                             End If        
1031                             Return  New XElem ent("Crede ntials", N ew XElemen t("UserNam e", client Credential s_Renamed. UserName.U serName))        
1032                         Case Else        
1033                    End  Select        
1034                End If        
1035          
1036                Return N ew XElemen t("Credent ials", "")        
1037           En d Function        
1038   #End Regio n ' Privat e methods        
1039          
1040                    #Reg ion "Priva te Classes "        
1041                    '''  <summary>        
1042                    '''  private st atic class  to store  constants  required b y the CrmS erviceHelp er class.        
1043                    '''  </summary>        
1044                    Priv ate NotInh eritable C lass CrmSe rviceHelpe rConstants        
1045                             ''' <s ummary>        
1046                             ''' Cr edentials  file path.        
1047                             ''' </ summary>        
1048                             Public  Shared Re adOnly Ser verCredent ialsFile A s String =  Path.Comb ine(Path.C ombine(Env ironment.G etFolderPa th(Environ ment.Speci alFolder.A pplication Data), "Cr mServer"),  "Credenti als.xml")        
1049                    End  Class        
1050                    #End  Region                 
1051           En d Class        
1052           #R egion "Oth er Classes "        
1053                   
1054       Friend  NotInheri table Clas s Credenti al        
1055           Pr ivate _use rName As S ecureStrin g        
1056           Pr ivate _pas sword As S ecureStrin g        
1057          
1058           Fr iend Sub N ew(ByVal c red As CRE DENTIAL_ST RUCT)        
1059                _userNam e = Conver tToSecureS tring(cred .userName)        
1060                Dim size  As Intege r = CInt(c red.creden tialBlobSi ze)        
1061                If size  <> 0 Then        
1062                    Dim  bpassword( size - 1)  As Byte        
1063                    Mars hal.Copy(c red.creden tialBlob,  bpassword,  0, size)        
1064                    _pas sword = Co nvertToSec ureString( Encoding.U nicode.Get String(bpa ssword))        
1065                Else        
1066                    _pas sword = Co nvertToSec ureString( String.Emp ty)        
1067                End If        
1068           En d Sub        
1069          
1070           Pu blic Sub N ew(ByVal u serName As  String, B yVal passw ord As Str ing)        
1071                If (Stri ng.IsNullO rWhiteSpac e(userName )) Then        
1072                    Thro w New Argu mentNullEx ception("u serName")        
1073                End If        
1074          
1075                If (Stri ng.IsNullO rWhiteSpac e(password )) Then        
1076                    Thro w New Argu mentNullEx ception("p assword")        
1077                End If        
1078          
1079                _userNam e = Conver tToSecureS tring(user Name)        
1080                _passwor d = Conver tToSecureS tring(pass word)        
1081           En d Sub        
1082          
1083           Pu blic ReadO nly Proper ty UserNam e() As Str ing        
1084                Get        
1085                    Retu rn Convert ToUnsecure String(_us erName)        
1086                End Get        
1087           En d Property        
1088          
1089           Pu blic ReadO nly Proper ty Passwor d() As Str ing        
1090                Get        
1091                    Retu rn Convert ToUnsecure String(_pa ssword)        
1092                End Get        
1093           En d Property        
1094          
1095           '' ' <summary >        
1096           '' ' This con verts a Se cureString  password  to plain t ext        
1097           '' ' </summar y>        
1098           '' ' <param n ame="secur ePassword" >SecureStr ing passwo rd</param>        
1099           '' ' <returns >plain tex t password </returns>        
1100           Pr ivate Func tion Conve rtToUnsecu reString(B yVal secre t As Secur eString) A s String        
1101                If secre t Is Nothi ng Then        
1102                    Retu rn String. Empty        
1103                End If        
1104          
1105                Dim unma nagedStrin g As IntPt r = IntPtr .Zero        
1106                Try        
1107                    unma nagedStrin g = Marsha l.SecureSt ringToGlob alAllocUni code(secre t)        
1108                    Retu rn Marshal .PtrToStri ngUni(unma nagedStrin g)        
1109                Finally        
1110                    Mars hal.ZeroFr eeGlobalAl locUnicode (unmanaged String)        
1111                End Try        
1112           En d Function        
1113          
1114           '' ' <summary >        
1115           '' ' This con verts a st ring to Se cureString        
1116           '' ' </summar y>        
1117           '' ' <param n ame="passw ord">plain  text pass word</para m>        
1118           '' ' <returns >SecureStr ing passwo rd</return s>        
1119           Pr ivate Func tion Conve rtToSecure String(ByV al secret  As String)  As Secure String        
1120                If Strin g.IsNullOr Empty(secr et) Then        
1121                    Retu rn Nothing        
1122                End If        
1123          
1124                Dim secu rePassword  As New Se cureString ()        
1125                Dim pass wordChars( ) As Char  = secret.T oCharArray ()        
1126                For Each  pwdChar A s Char In  passwordCh ars        
1127                    secu rePassword .AppendCha r(pwdChar)        
1128                Next pwd Char        
1129                securePa ssword.Mak eReadOnly( )        
1130                Return s ecurePassw ord        
1131           En d Function        
1132          
1133           '' ' <summary >        
1134           '' ' This str ucture map s to the C REDENTIAL  structure  used by na tive code.  We can us e this to  marshal ou r values.        
1135           '' ' </summar y>        
1136                    <Str uctLayout( LayoutKind .Sequentia l, CharSet  := CharSe t.Unicode) > _        
1137           Fr iend Struc ture CREDE NTIAL_STRU CT        
1138                Public f lags As UI nt32        
1139                Public t ype As UIn t32        
1140                Public t argetName  As String        
1141                Public c omment As  String        
1142                Public l astWritten  As System .Runtime.I nteropServ ices.ComTy pes.FILETI ME        
1143                Public c redentialB lobSize As  UInt32        
1144                Public c redentialB lob As Int Ptr        
1145                Public p ersist As  UInt32        
1146                Public a ttributeCo unt As UIn t32        
1147                Public c redAttribu te As IntP tr        
1148                Public t argetAlias  As String        
1149                Public u serName As  String        
1150           En d Structur e        
1151          
1152          
1153       End Cl ass        
1154          
1155       ''' <s ummary>        
1156       ''' Th is class e xposes met hods to re ad, write  and delete  user cred entials        
1157       ''' </ summary>        
1158       Friend  NotInheri table Clas s Credenti alManager        
1159           '' ' <summary >        
1160           '' ' Target N ame agains t which al l credenti als are st ored on th e disk.        
1161           '' ' </summar y>        
1162           Pu blic Const  TargetNam e As Strin g = "Micro soft_CRMSD K:"        
1163          
1164           '' ' <summary >        
1165           '' ' Cache co ntaining s ecrets in- memory (us ed to impr ove perfor mance and  avoid IO o perations) .        
1166           '' ' </summar y>        
1167           Pr ivate Shar ed credent ialCache A s New Dict ionary(Of  String, Cr edential)( )        
1168          
1169           Pr ivate Sub  New()        
1170           En d Sub        
1171           Pu blic Share d Function  GetCreden tialTarget (ByVal tar get As Uri ) As Uri        
1172                If targe t Is Nothi ng Then        
1173                    Thro w New Argu mentNullEx ception("t arget")        
1174                End If        
1175          
1176                Return N ew Uri(tar get.GetLef tPart(UriP artial.Aut hority))        
1177           En d Function        
1178          
1179           Pr ivate Enum  CRED_TYPE  As Intege r        
1180                GENERIC  = 1        
1181                DOMAIN_P ASSWORD =  2        
1182                DOMAIN_C ERTIFICATE  = 3        
1183                DOMAIN_V ISIBLE_PAS SWORD = 4        
1184                MAXIMUM  = 5        
1185           En d Enum        
1186          
1187           Fr iend Enum  CRED_PERSI ST As UInt eger        
1188                SESSION  = 1        
1189                LOCAL_MA CHINE = 2        
1190                ENTERPRI SE = 3        
1191           En d Enum        
1192          
1193           Pr ivate NotI nheritable  Class Nat iveMethods        
1194                <DllImpo rt("advapi 32.dll", S etLastErro r:=True, E ntryPoint: ="CredRead W", CharSe t:=CharSet .Unicode)>  _        
1195                Public S hared Func tion CredR ead(ByVal  target As  String, By Val type A s CRED_TYP E, ByVal r eservedFla g As Integ er, <Syste m.Runtime. InteropSer vices.Out( ), Marshal As(Unmanag edType.Cus tomMarshal er, Marsha lTypeRef:= GetType(Cr edentialMa rshaler))>  ByRef cre dential As  Credentia l) As <Mar shalAs(Unm anagedType .Bool)> Bo olean        
1196                End Func tion        
1197          
1198                <DllImpo rt("Advapi 32.dll", S etLastErro r:=True, E ntryPoint: ="CredWrit eW", CharS et:=CharSe t.Unicode) > _        
1199                Public S hared Func tion CredW rite(ByRef  credentia l As Crede ntial.CRED ENTIAL_STR UCT, ByVal  flags As  UInt32) As  <MarshalA s(Unmanage dType.Bool )> Boolean        
1200                End Func tion        
1201          
1202                <DllImpo rt("Advapi 32.dll", E ntryPoint: ="CredFree ", SetLast Error:=Tru e)> _        
1203                Public S hared Func tion CredF ree(ByVal  cred As In tPtr) As < MarshalAs( UnmanagedT ype.Bool)>  Boolean        
1204                End Func tion        
1205          
1206                <DllImpo rt("advapi 32.dll", E ntryPoint: ="CredDele teW", Char Set:=CharS et.Unicode )> _        
1207                Public S hared Func tion CredD elete(ByVa l target A s String,  ByVal type  As Intege r, ByVal f lags As In teger) As  <MarshalAs (Unmanaged Type.Bool) > Boolean        
1208                End Func tion        
1209           En d Class        
1210          
1211           Pr ivate NotI nheritable  Class Cre dentialMar shaler        
1212                Implemen ts ICustom Marshaler        
1213                Private  Shared _in stance As  Credential Marshaler        
1214          
1215                Public S ub CleanUp ManagedDat a(ByVal Ma nagedObj A s Object)  Implements  ICustomMa rshaler.Cl eanUpManag edData        
1216                    ' No thing to d o since al l data can  be garbag e collecte d.        
1217                End Sub        
1218          
1219                Public S ub CleanUp NativeData (ByVal pNa tiveData A s IntPtr)  Implements  ICustomMa rshaler.Cl eanUpNativ eData        
1220                    If p NativeData  = IntPtr. Zero Then        
1221                         Return        
1222                    End  If        
1223                    Nati veMethods. CredFree(p NativeData )        
1224                End Sub        
1225          
1226                Public F unction Ge tNativeDat aSize() As  Integer I mplements  ICustomMar shaler.Get NativeData Size        
1227                    Thro w New NotI mplemented Exception( "The metho d or opera tion is no t implemen ted.")        
1228                End Func tion        
1229          
1230                Public F unction Ma rshalManag edToNative (ByVal obj  As Object ) As IntPt r Implemen ts ICustom Marshaler. MarshalMan agedToNati ve        
1231                    Thro w New NotI mplemented Exception( "Not imple mented yet ")        
1232                End Func tion        
1233          
1234                Public F unction Ma rshalNativ eToManaged (ByVal pNa tiveData A s IntPtr)  As Object  Implements  ICustomMa rshaler.Ma rshalNativ eToManaged        
1235                    If p NativeData  = IntPtr. Zero Then        
1236                         Return Not hing        
1237                    End  If        
1238                    Retu rn New Cre dential(CT ype(Marsha l.PtrToStr ucture(pNa tiveData,  GetType(Cr edential.C REDENTIAL_ STRUCT)),  Credential .CREDENTIA L_STRUCT))        
1239                End Func tion        
1240          
1241          
1242                Public S hared Func tion GetIn stance(ByV al cookie  As String)  As ICusto mMarshaler        
1243                    If N othing Is  _instance  Then        
1244                         _instance  = New Cred entialMars haler()        
1245                    End  If        
1246                    Retu rn _instan ce        
1247                End Func tion        
1248           En d Class        
1249          
1250           Pu blic Share d Function  ReadCrede ntials(ByV al target  As String)  As Creden tial        
1251                Dim cach edCredenti al As Cred ential = N othing        
1252          
1253                ' Try to  read the  username f rom cache        
1254                If crede ntialCache .TryGetVal ue(TargetN ame & targ et, cached Credential ) Then        
1255                    Retu rn cachedC redential        
1256                End If        
1257          
1258                Dim cred ential_Ren amed As Cr edential =  Nothing        
1259                Dim bSuc cess As Bo olean = Na tiveMethod s.CredRead (TargetNam e & target , CRED_TYP E.GENERIC,  0, creden tial_Renam ed)        
1260                ' No mat ch found.        
1261                If Not b Success Th en        
1262                    Retu rn Nothing        
1263                End If        
1264          
1265                credenti alCache(Ta rgetName &  target.To String())  = credenti al_Renamed        
1266                Return c redential_ Renamed        
1267           En d Function        
1268          
1269           Pu blic Share d Function  ReadWindo wsCredenti al(ByVal t arget As U ri) As Cre dential        
1270                Dim cred ential_Ren amed As Cr edential =  Nothing        
1271                Dim bSuc cess As Bo olean = Na tiveMethod s.CredRead (target.Ho st, CRED_T YPE.DOMAIN _PASSWORD,  0, creden tial_Renam ed)        
1272                If Not b Success Th en        
1273                    Thro w New Inva lidOperati onExceptio n("Unable  to read wi ndows cred entials fo r Uri {0}.  ErrorCode  {1}",        
1274                                          New  System.Com ponentMode l.Win32Exc eption(Mar shal.GetLa stWin32Err or()))        
1275                End If        
1276                             Return  credentia l_Renamed        
1277           En d Function        
1278           '' ' <summary >        
1279           '' ' Fetches  the creden tials.        
1280           '' ' </summar y>        
1281           '' ' <param n ame="targe t">Target  is the key  with whic h associat ed credent ials can b e fetched< /param>        
1282           '' ' <param n ame="userC redentials ">It is th e in param eter which  contains  the userna me and pas sword</par am>        
1283           '' ' <param n ame="allow PhysicalSt ore">If al lowPhysica lStore is  true then  the creden tials are  stored on  disk</para m>        
1284           Pu blic Share d Sub Writ eCredentia ls(ByVal t arget As S tring, ByV al userCre dentials A s Credenti al, ByVal  allowPhysi calStore A s Boolean)        
1285                If Strin g.IsNullOr WhiteSpace (target) T hen        
1286                    Thro w New Argu mentNullEx ception("t arget")        
1287                End If        
1288                If userC redentials  Is Nothin g Then        
1289                    Thro w New Argu mentNullEx ception("u serCredent ials")        
1290                End If        
1291                If allow PhysicalSt ore = Noth ing Then        
1292                    Thro w New Argu mentNullEx ception("a llowPhysic alStore")        
1293                End If        
1294                ' Cache  the userna me and pas sword in m emory        
1295                credenti alCache(Ta rgetName &  target) =  userCrede ntials        
1296          
1297                ' Store  the creden tials if a llowed        
1298                Dim pass wordToStor e As Strin g = If(all owPhysical Store, use rCredentia ls.Passwor d, String. Empty)        
1299                Dim cred ential As  New Creden tial.CREDE NTIAL_STRU CT()        
1300                Try        
1301                    cred ential.tar getName =  TargetName  & target        
1302                    cred ential.typ e = CUInt( CRED_TYPE. GENERIC)        
1303                    cred ential.use rName = us erCredenti als.UserNa me        
1304                    cred ential.att ributeCoun t = 0        
1305                    cred ential.per sist = CUI nt(CRED_PE RSIST.LOCA L_MACHINE)        
1306                    Dim  bpassword( ) As Byte  = Encoding .Unicode.G etBytes(pa sswordToSt ore)        
1307                    cred ential.cre dentialBlo bSize = CU Int(bpassw ord.Length )        
1308                    cred ential.cre dentialBlo b = Marsha l.AllocCoT askMem(bpa ssword.Len gth)        
1309                    Mars hal.Copy(b password,  0, credent ial.creden tialBlob,  bpassword. Length)        
1310                    If N ot NativeM ethods.Cre dWrite(cre dential, 0 ) Then        
1311                         Throw New  System.Com ponentMode l.Win32Exc eption(Mar shal.GetLa stWin32Err or())        
1312                    End  If        
1313                Finally        
1314                    If I ntPtr.Zero  <> creden tial.crede ntialBlob  Then        
1315                         Marshal.Fr eeCoTaskMe m(credenti al.credent ialBlob)        
1316                    End  If        
1317                End Try        
1318           En d Sub        
1319          
1320           '' ' <summary >        
1321           '' ' Deletes  the creden tials.        
1322           '' ' </summar y>        
1323           '' ' <param n ame="targe t">Target  is the key  with whic h associat ed credent ials can b e fetched< /param>        
1324           '' ' <param n ame="softD elete">If  a softDele te is done  then cred entials ar e deleted  only from  memory.         
1325           '' ' They are  completel y removed  otherwise. </param>        
1326           Pu blic Share d Sub Dele teCredenti als(ByVal  target As  String, By Val softDe lete As Bo olean)        
1327                             If Str ing.IsNull OrWhiteSpa ce(target)  Then        
1328                                      Throw Ne w Argument NullExcept ion("targe t")        
1329                             End If        
1330                If Nothi ng = softD elete Then        
1331                    Thro w New Argu mentNullEx ception("s oftDelete" )        
1332                End If        
1333                If softD elete Then        
1334                    ' Re moves only  the passw ord        
1335                    Try        
1336                         Dim tempCr edential A s Credenti al = ReadC redentials (target)        
1337                         WriteCrede ntials(tar get, New C redential( tempCreden tial.UserN ame, Strin g.Empty),  True)        
1338                    Catc h e1 As Ex ception        
1339                         ' Do nothi ng        
1340                    End  Try        
1341                Else        
1342                    ' Re moves the  entry comp letely        
1343                    Nati veMethods. CredDelete (TargetNam e & target , CInt(CRE D_TYPE.GEN ERIC), 0)        
1344                    cred entialCach e.Remove(T argetName  & target)        
1345                End If        
1346           En d Sub        
1347       End Cl ass        
1348          
1349       ''' <s ummary>        
1350       ''' Wr apper clas s for Disc overyServi ceProxy to  support a uto refres h security  token.        
1351       ''' </ summary>        
1352       Friend  NotInheri table Clas s ManagedT okenDiscov eryService Proxy        
1353           In herits Dis coveryServ iceProxy        
1354           Pr ivate _pro xyManager  As AutoRef reshSecuri tyToken(Of  Discovery ServicePro xy, IDisco veryServic e)        
1355          
1356           Pu blic Sub N ew(ByVal s erviceUri  As Uri, By Val userCr edentials  As ClientC redentials )        
1357                MyBase.N ew(service Uri, Nothi ng, userCr edentials,  Nothing)        
1358                Me._prox yManager =  New AutoR efreshSecu rityToken( Of Discove ryServiceP roxy, IDis coveryServ ice)(Me)        
1359           En d Sub        
1360          
1361           Pu blic Sub N ew(ByVal s erviceMana gement As  IServiceMa nagement(O f IDiscove ryService) , ByVal se curityToke nRes As Se curityToke nResponse)        
1362                MyBase.N ew(service Management , security TokenRes)        
1363                Me._prox yManager =  New AutoR efreshSecu rityToken( Of Discove ryServiceP roxy, IDis coveryServ ice)(Me)        
1364           En d Sub        
1365          
1366           Pu blic Sub N ew(ByVal s erviceMana gement As  IServiceMa nagement(O f IDiscove ryService) , ByVal us erCredenti als As Cli entCredent ials)        
1367                MyBase.N ew(service Management , userCred entials)        
1368                Me._prox yManager =  New AutoR efreshSecu rityToken( Of Discove ryServiceP roxy, IDis coveryServ ice)(Me)        
1369           En d Sub        
1370          
1371           Pr otected Ov errides Fu nction Aut henticateD eviceCore( ) As Secur ityTokenRe sponse        
1372                Return M e._proxyMa nager.Auth enticateDe vice()        
1373           En d Function        
1374          
1375           Pr otected Ov errides Su b Authenti cateCore()        
1376                Me._prox yManager.P repareCred entials()        
1377                MyBase.A uthenticat eCore()        
1378           En d Sub        
1379          
1380           Pr otected Ov errides Su b Validate Authentica tion()        
1381                Me._prox yManager.R enewTokenI fRequired( )        
1382                MyBase.V alidateAut henticatio n()        
1383           En d Sub        
1384       End Cl ass        
1385          
1386       ''' <s ummary>        
1387       ''' Wr apper clas s for Orga nizationSe rviceProxy  to suppor t auto ref resh secur ity token        
1388       ''' </ summary>        
1389       Friend  NotInheri table Clas s ManagedT okenOrgani zationServ iceProxy        
1390           In herits Org anizationS erviceProx y        
1391           Pr ivate _pro xyManager  As AutoRef reshSecuri tyToken(Of  Organizat ionService Proxy, IOr ganization Service)        
1392          
1393           Pu blic Sub N ew(ByVal s erviceUri  As Uri, By Val userCr edentials  As ClientC redentials )        
1394                MyBase.N ew(service Uri, Nothi ng, userCr edentials,  Nothing)        
1395                Me._prox yManager =  New AutoR efreshSecu rityToken( Of Organiz ationServi ceProxy, I Organizati onService) (Me)        
1396           En d Sub        
1397          
1398           Pu blic Sub N ew(ByVal s erviceMana gement As  IServiceMa nagement(O f IOrganiz ationServi ce), ByVal  securityT okenRes As  SecurityT okenRespon se)        
1399                MyBase.N ew(service Management , security TokenRes)        
1400                Me._prox yManager =  New AutoR efreshSecu rityToken( Of Organiz ationServi ceProxy, I Organizati onService) (Me)        
1401           En d Sub        
1402          
1403           Pu blic Sub N ew(ByVal s erviceMana gement As  IServiceMa nagement(O f IOrganiz ationServi ce), ByVal  userCrede ntials As  ClientCred entials)        
1404                MyBase.N ew(service Management , userCred entials)        
1405                Me._prox yManager =  New AutoR efreshSecu rityToken( Of Organiz ationServi ceProxy, I Organizati onService) (Me)        
1406           En d Sub        
1407          
1408           Pr otected Ov errides Fu nction Aut henticateD eviceCore( ) As Secur ityTokenRe sponse        
1409                Return M e._proxyMa nager.Auth enticateDe vice()        
1410           En d Function        
1411          
1412           Pr otected Ov errides Su b Authenti cateCore()        
1413                Me._prox yManager.P repareCred entials()        
1414                MyBase.A uthenticat eCore()        
1415           En d Sub        
1416          
1417           Pr otected Ov errides Su b Validate Authentica tion()        
1418                Me._prox yManager.R enewTokenI fRequired( )        
1419                MyBase.V alidateAut henticatio n()        
1420           En d Sub        
1421       End Cl ass        
1422          
1423       ''' <s ummary>        
1424       ''' Cl ass that w raps acqui ring the s ecurity to ken for a  service        
1425       ''' </ summary>        
1426       Public  NotInheri table Clas s AutoRefr eshSecurit yToken(Of  TProxy As  ServicePro xy(Of TSer vice), TSe rvice As C lass)        
1427           Pr ivate _dev iceCredent ials As Cl ientCreden tials        
1428           Pr ivate _pro xy As TPro xy        
1429          
1430           '' ' <summary >        
1431           '' ' Instanti ates an in stance of  the proxy  class        
1432           '' ' </summar y>        
1433           '' ' <param n ame="proxy ">Proxy th at will be  used to a uthenticat e the user </param>        
1434           Pu blic Sub N ew(ByVal p roxy As TP roxy)        
1435                If Nothi ng Is prox y Then        
1436                    Thro w New Argu mentNullEx ception("p roxy")        
1437                End If        
1438          
1439                Me._prox y = proxy        
1440           En d Sub        
1441          
1442           '' ' <summary >        
1443           '' ' Prepares  authentic ation befo re authen6 ticated        
1444           '' ' </summar y>        
1445           Pu blic Sub P repareCred entials()        
1446                If Nothi ng Is Me._ proxy.Clie ntCredenti als Then        
1447                    Retu rn        
1448                End If        
1449          
1450                Select C ase Me._pr oxy.Servic eConfigura tion.Authe nticationT ype        
1451                    Case  Authentic ationProvi derType.Ac tiveDirect ory        
1452                         Me._proxy. ClientCred entials.Us erName.Use rName = No thing        
1453                         Me._proxy. ClientCred entials.Us erName.Pas sword = No thing        
1454                    Case  Authentic ationProvi derType.Fe deration,  Authentica tionProvid erType.Liv eId        
1455                         Me._proxy. ClientCred entials.Wi ndows.Clie ntCredenti al = Nothi ng        
1456                    Case  Else        
1457                         Return        
1458                End Sele ct        
1459           En d Sub        
1460          
1461           '' ' <summary >        
1462           '' ' Authenti cates the  device tok en        
1463           '' ' </summar y>        
1464           '' ' <returns >Generated  SecurityT okenRespon se for the  device</r eturns>        
1465           Pu blic Funct ion Authen ticateDevi ce() As Se curityToke nResponse        
1466                If Nothi ng Is Me._ deviceCred entials Th en        
1467                    Me._ deviceCred entials =  DeviceIdMa nager.Load OrRegister Device(Me. _proxy.Ser viceConfig uration.Cu rrentIssue r.IssuerAd dress.Uri)        
1468                End If        
1469          
1470                Return M e._proxy.S erviceConf iguration. Authentica teDevice(M e._deviceC redentials )        
1471           En d Function        
1472          
1473           '' ' <summary >        
1474           '' ' Renews t he token ( if it is n ear expira tion or ha s expired)        
1475           '' ' </summar y>        
1476           Pu blic Sub R enewTokenI fRequired( )        
1477                If Nothi ng IsNot M e._proxy.S ecurityTok enResponse  AndAlso D ate.UtcNow .AddMinute s(15) >= M e._proxy.S ecurityTok enResponse .Response. Lifetime.E xpires The n        
1478                    Try        
1479                         Me._proxy. Authentica te()        
1480                    Catc h e1 As Co mmunicatio nException        
1481                         If Nothing  Is Me._pr oxy.Securi tyTokenRes ponse OrEl se Date.Ut cNow >= Me ._proxy.Se curityToke nResponse. Response.L ifetime.Ex pires Then        
1482                             Throw        
1483                         End If        
1484          
1485                         ' Ignore t he excepti on         
1486                    End  Try        
1487                End If        
1488           En d Sub        
1489       End Cl ass        
1490   #End Regio n        
1491   End Namesp ace        
1492   '</snippet CrmService Helper>