Produced by Araxis Merge on 2/1/2017 2:56:43 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.
| # | Location | File | Last Modified |
|---|---|---|---|
| 1 | C:\Araxis_Merge_Comprasion\Pub_un\BTSSS_CIF_122016.zip\BTSSS_CIF_12_20_16\clean\CRM\trunk\SDK\SampleCode\CS\HelperCode | CrmServiceHelpers.cs | Tue Dec 20 19:51:44 2016 UTC |
| 2 | Wed Feb 1 19:56:43 2017 UTC |
| Description | Between Files 1 and 2 |
|
|---|---|---|
| Text Blocks | Lines | |
| Unchanged | 0 | 0 |
| Changed | 0 | 0 |
| Inserted | 0 | 0 |
| Removed | 1 | 1734 |
| 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 |
No regular expressions were active.
| 1 | // ======= ========== ========== ========== ========== ========== ========== == | |||||
| 2 | // This f ile is par t of the M icrosoft D ynamics CR M SDK code samples. | |||||
| 3 | // | |||||
| 4 | // Copyri ght (C) Mi crosoft Co rporation. All righ ts reserve d. | |||||
| 5 | // | |||||
| 6 | // This s ource code is intend ed only as a supplem ent to Mic rosoft | |||||
| 7 | // Develo pment Tool s and/or o n-line doc umentation . See the se other | |||||
| 8 | // materi als for de tailed inf ormation r egarding M icrosoft c ode sample s. | |||||
| 9 | // | |||||
| 10 | // THIS C ODE AND IN FORMATION ARE PROVID ED "AS IS" WITHOUT W ARRANTY OF ANY | |||||
| 11 | // KIND, EITHER EXP RESSED OR IMPLIED, I NCLUDING B UT NOT LIM ITED TO TH E | |||||
| 12 | // IMPLIE D WARRANTI ES OF MERC HANTABILIT Y AND/OR F ITNESS FOR A | |||||
| 13 | // PARTIC ULAR PURPO SE. | |||||
| 14 | // ======= ========== ========== ========== ========== ========== ========== == | |||||
| 15 | //<snippet CrmService Helper> | |||||
| 16 | using Syst em; | |||||
| 17 | using Syst em.Collect ions.Gener ic; | |||||
| 18 | using Syst em.Diagnos tics.CodeA nalysis; | |||||
| 19 | using Syst em.Directo ryServices .AccountMa nagement; | |||||
| 20 | using Syst em.IO; | |||||
| 21 | using Syst em.Runtime .InteropSe rvices; | |||||
| 22 | using Syst em.Securit y; | |||||
| 23 | using Syst em.Service Model; | |||||
| 24 | using Syst em.Service Model.Desc ription; | |||||
| 25 | using Syst em.Text; | |||||
| 26 | using Syst em.Xml; | |||||
| 27 | using Syst em.Xml.Lin q; | |||||
| 28 | ||||||
| 29 | // These n amespaces are found in the Mic rosoft.Xrm .Sdk.dll a ssembly | |||||
| 30 | // located in the SD K\bin fold er of the SDK downlo ad. | |||||
| 31 | using Micr osoft.Xrm. Sdk; | |||||
| 32 | using Micr osoft.Xrm. Sdk.Client ; | |||||
| 33 | using Micr osoft.Xrm. Sdk.Discov ery; | |||||
| 34 | using Micr osoft.Crm. Services.U tility; | |||||
| 35 | ||||||
| 36 | ||||||
| 37 | namespace Microsoft. Crm.Sdk.Sa mples | |||||
| 38 | { | |||||
| 39 | /// <s ummary> | |||||
| 40 | /// Pr ovides ser ver connec tion infor mation. | |||||
| 41 | /// </ summary> | |||||
| 42 | public class Ser verConnect ion | |||||
| 43 | { | |||||
| 44 | #r egion Inne r classes | |||||
| 45 | // / <summary > | |||||
| 46 | // / Stores M icrosoft D ynamics CR M server c onfigurati on informa tion. | |||||
| 47 | // / </summar y> | |||||
| 48 | pu blic class Configura tion | |||||
| 49 | { | |||||
| 50 | public S tring Serv erAddress; | |||||
| 51 | public S tring Orga nizationNa me; | |||||
| 52 | public U ri Discove ryUri; | |||||
| 53 | public U ri Organiz ationUri; | |||||
| 54 | public U ri HomeRea lmUri = nu ll; | |||||
| 55 | public C lientCrede ntials Dev iceCredent ials = nul l; | |||||
| 56 | public C lientCrede ntials Cre dentials = null; | |||||
| 57 | public A uthenticat ionProvide rType Endp ointType; | |||||
| 58 | public S tring User PrincipalN ame; | |||||
| 59 | #region internal m embers of the class | |||||
| 60 | internal IServiceM anagement< IOrganizat ionService > Organiza tionServic eManagemen t; | |||||
| 61 | internal SecurityT okenRespon se Organiz ationToken Response; | |||||
| 62 | internal Int16 Aut hFailureCo unt = 0; | |||||
| 63 | #endregi on | |||||
| 64 | ||||||
| 65 | public o verride bo ol Equals( object obj ) | |||||
| 66 | { | |||||
| 67 | //Ch eck for nu ll and com pare run-t ime types. | |||||
| 68 | if ( obj == nul l || GetTy pe() != ob j.GetType( )) return false; | |||||
| 69 | ||||||
| 70 | Conf iguration c = (Confi guration)o bj; | |||||
| 71 | ||||||
| 72 | if ( !this.Serv erAddress. Equals(c.S erverAddre ss, String Comparison .Invariant CultureIgn oreCase)) | |||||
| 73 | return fal se; | |||||
| 74 | if ( !this.Orga nizationNa me.Equals( c.Organiza tionName, StringComp arison.Inv ariantCult ureIgnoreC ase)) | |||||
| 75 | return fal se; | |||||
| 76 | if ( this.Endpo intType != c.Endpoin tType) | |||||
| 77 | return fal se; | |||||
| 78 | if ( null != th is.Credent ials && nu ll != c.Cr edentials) | |||||
| 79 | { | |||||
| 80 | if (this.E ndpointTyp e == Authe nticationP roviderTyp e.ActiveDi rectory) | |||||
| 81 | { | |||||
| 82 | ||||||
| 83 | if (!t his.Creden tials.Wind ows.Client Credential .Domain.Eq uals( | |||||
| 84 | c. Credential s.Windows. ClientCred ential.Dom ain, Strin gCompariso n.Invarian tCultureIg noreCase)) | |||||
| 85 | re turn false ; | |||||
| 86 | if (!t his.Creden tials.Wind ows.Client Credential .UserName. Equals( | |||||
| 87 | c. Credential s.Windows. ClientCred ential.Use rName, Str ingCompari son.Invari antCulture IgnoreCase )) | |||||
| 88 | re turn false ; | |||||
| 89 | ||||||
| 90 | } | |||||
| 91 | else if (t his.Endpoi ntType == Authentica tionProvid erType.Liv eId) | |||||
| 92 | { | |||||
| 93 | if (!t his.Creden tials.User Name.UserN ame.Equals (c.Credent ials.UserN ame.UserNa me, | |||||
| 94 | St ringCompar ison.Invar iantCultur eIgnoreCas e)) | |||||
| 95 | re turn false ; | |||||
| 96 | if (!t his.Device Credential s.UserName .UserName. Equals( | |||||
| 97 | c. DeviceCred entials.Us erName.Use rName, Str ingCompari son.Invari antCulture IgnoreCase )) | |||||
| 98 | re turn false ; | |||||
| 99 | if (!t his.Device Credential s.UserName .Password. Equals( | |||||
| 100 | c. DeviceCred entials.Us erName.Pas sword, Str ingCompari son.Invari antCulture IgnoreCase )) | |||||
| 101 | re turn false ; | |||||
| 102 | } | |||||
| 103 | else | |||||
| 104 | { | |||||
| 105 | ||||||
| 106 | if (!t his.Creden tials.User Name.UserN ame.Equals (c.Credent ials.UserN ame.UserNa me, | |||||
| 107 | St ringCompar ison.Invar iantCultur eIgnoreCas e)) | |||||
| 108 | re turn false ; | |||||
| 109 | ||||||
| 110 | } | |||||
| 111 | } | |||||
| 112 | retu rn true; | |||||
| 113 | } | |||||
| 114 | ||||||
| 115 | public o verride in t GetHashC ode() | |||||
| 116 | { | |||||
| 117 | int returnHash Code = thi s.ServerAd dress.GetH ashCode() | |||||
| 118 | ^ this.Org anizationN ame.GetHas hCode() | |||||
| 119 | ^ this.End pointType. GetHashCod e(); | |||||
| 120 | if ( null != th is.Credent ials) | |||||
| 121 | { | |||||
| 122 | if (this.E ndpointTyp e == Authe nticationP roviderTyp e.ActiveDi rectory) | |||||
| 123 | return HashCode = returnHas hCode | |||||
| 124 | ^ this.Crede ntials.Win dows.Clien tCredentia l.UserName .GetHashCo de() | |||||
| 125 | ^ this.Crede ntials.Win dows.Clien tCredentia l.Domain.G etHashCode (); | |||||
| 126 | else if (t his.Endpoi ntType == Authentica tionProvid erType.Liv eId) | |||||
| 127 | return HashCode = returnHas hCode | |||||
| 128 | ^ this.Crede ntials.Use rName.User Name.GetHa shCode() | |||||
| 129 | ^ this.Devic eCredentia ls.UserNam e.UserName .GetHashCo de() | |||||
| 130 | ^ this.Devic eCredentia ls.UserNam e.Password .GetHashCo de(); | |||||
| 131 | else | |||||
| 132 | return HashCode = returnHas hCode | |||||
| 133 | ^ this.Crede ntials.Use rName.User Name.GetHa shCode(); | |||||
| 134 | } | |||||
| 135 | retu rn returnH ashCode; | |||||
| 136 | } | |||||
| 137 | ||||||
| 138 | } | |||||
| 139 | #e ndregion I nner class es | |||||
| 140 | ||||||
| 141 | #r egion Publ ic propert ies | |||||
| 142 | ||||||
| 143 | pu blic List< Configurat ion> confi gurations = null; | |||||
| 144 | ||||||
| 145 | #e ndregion P ublic prop erties | |||||
| 146 | ||||||
| 147 | #r egion Priv ate proper ties | |||||
| 148 | ||||||
| 149 | pr ivate Conf iguration config = n ew Configu ration(); | |||||
| 150 | ||||||
| 151 | #e ndregion P rivate pro perties | |||||
| 152 | ||||||
| 153 | #r egion Stat ic methods | |||||
| 154 | // / <summary > | |||||
| 155 | // / Obtains the organi zation ser vice proxy . | |||||
| 156 | // / This wou ld give a better per formance t han direct ly calling GetProxy( ) generic method | |||||
| 157 | // / as it us es cached Organizati onServiceM anagement in case it is presen t. | |||||
| 158 | // / </summar y> | |||||
| 159 | // / <param n ame="serve rConfigura tion">An i nstance of ServerCon nection.Co nfiguratio n</param> | |||||
| 160 | // / <returns >An instan ce of orga nization s ervice pro xy</return s> | |||||
| 161 | pu blic stati c Organiza tionServic eProxy Get Organizati onProxy( | |||||
| 162 | ServerCo nnection.C onfigurati on serverC onfigurati on) | |||||
| 163 | { | |||||
| 164 | // If or ganization service m anagement exists, th en use it. | |||||
| 165 | // Other wise gener ate organi zation ser vice proxy from scra tch. | |||||
| 166 | if (null != server Configurat ion.Organi zationServ iceManagem ent) | |||||
| 167 | { | |||||
| 168 | // O btain the organizati on service proxy for the Feder ated, Micr osoft acco unt, and O nlineFeder ated envir onments. | |||||
| 169 | if ( serverConf iguration. EndpointTy pe != Auth entication ProviderTy pe.ActiveD irectory) | |||||
| 170 | { | |||||
| 171 | // get the organizat ion servic e proxy. | |||||
| 172 | return Get Proxy<IOrg anizationS ervice, Or ganization ServicePro xy>(server Configurat ion); | |||||
| 173 | ||||||
| 174 | } | |||||
| 175 | // O btain orga nization s ervice pro xy for Act iveDirecto ry environ ment | |||||
| 176 | // u sing exist ing organi zation ser vice manag ement. | |||||
| 177 | else | |||||
| 178 | { | |||||
| 179 | return new ManagedTo kenOrganiz ationServi ceProxy( | |||||
| 180 | server Configurat ion.Organi zationServ iceManagem ent, | |||||
| 181 | server Configurat ion.Creden tials); | |||||
| 182 | } | |||||
| 183 | } | |||||
| 184 | ||||||
| 185 | // Obtai n the orga nization s ervice pro xy for all type of e nvironment s. | |||||
| 186 | return G etProxy<IO rganizatio nService, Organizati onServiceP roxy>(serv erConfigur ation); | |||||
| 187 | ||||||
| 188 | } | |||||
| 189 | #e ndregion S tatic meth ods | |||||
| 190 | ||||||
| 191 | #r egion Publ ic methods | |||||
| 192 | // / <summary > | |||||
| 193 | // / Obtains the server connectio n informat ion includ ing the ta rget organ ization's | |||||
| 194 | // / Uri and user logon credentia ls from th e user. | |||||
| 195 | // / </summar y> | |||||
| 196 | pu blic virtu al Configu ration Get ServerConf iguration( ) | |||||
| 197 | { | |||||
| 198 | Boolean ssl; | |||||
| 199 | Boolean addConfig; | |||||
| 200 | int conf igNumber; | |||||
| 201 | // Read the config uration fr om the dis k, if it e xists, at C:\Users\< username>\ AppData\Ro aming\CrmS erver\Cred entials.xm l. | |||||
| 202 | Boolean isConfigEx ist = Read Configurat ions(); | |||||
| 203 | ||||||
| 204 | // Check if server configura tion setti ngs are al ready avai lable on t he disk. | |||||
| 205 | if (isCo nfigExist) | |||||
| 206 | { | |||||
| 207 | // L ist of ser ver config urations t hat are av ailable fr om earlier saved set tings. | |||||
| 208 | Cons ole.Write( "\n(0) Add New Serve r Configur ation (Max imum numbe r up to 9) \t"); | |||||
| 209 | for (int n = 0 ; n < conf igurations .Count; n+ +) | |||||
| 210 | { | |||||
| 211 | String use r; | |||||
| 212 | ||||||
| 213 | switch (co nfiguratio ns[n].Endp ointType) | |||||
| 214 | { | |||||
| 215 | case A uthenticat ionProvide rType.Acti veDirector y: | |||||
| 216 | if (configur ations[n]. Credential s != null) | |||||
| 217 | user = c onfigurati ons[n].Cre dentials.W indows.Cli entCredent ial.Domain + "\\" | |||||
| 218 | + co nfiguratio ns[n].Cred entials.Wi ndows.Clie ntCredenti al.UserNam e; | |||||
| 219 | el se | |||||
| 220 | user = " default"; | |||||
| 221 | br eak; | |||||
| 222 | defaul t: | |||||
| 223 | if (configur ations[n]. Credential s != null) | |||||
| 224 | user = c onfigurati ons[n].Cre dentials.U serName.Us erName; | |||||
| 225 | el se | |||||
| 226 | user = " default"; | |||||
| 227 | br eak; | |||||
| 228 | } | |||||
| 229 | ||||||
| 230 | Console.Wr ite("\n({0 }) Server: {1}, Org : {2}, Us er: {3}\t" , | |||||
| 231 | n + 1, configura tions[n].S erverAddre ss, config urations[n ].Organiza tionName, user); | |||||
| 232 | } | |||||
| 233 | ||||||
| 234 | Cons ole.WriteL ine(); | |||||
| 235 | ||||||
| 236 | Cons ole.Write( "\nSpecify the saved server co nfiguratio n number ( 1-{0}) [{0 }] : ", co nfiguratio ns.Count); | |||||
| 237 | Stri ng input = Console.R eadLine(); | |||||
| 238 | Cons ole.WriteL ine(); | |||||
| 239 | if ( input == S tring.Empt y) input = configura tions.Coun t.ToString (); | |||||
| 240 | if ( !Int32.Try Parse(inpu t, out con figNumber) ) configNu mber = -1; | |||||
| 241 | ||||||
| 242 | if ( configNumb er == 0) | |||||
| 243 | { | |||||
| 244 | addConfig = true; | |||||
| 245 | } | |||||
| 246 | else if (confi gNumber > 0 && confi gNumber <= configura tions.Coun t) | |||||
| 247 | { | |||||
| 248 | // Return the organi zation Uri . | |||||
| 249 | config = c onfigurati ons[config Number - 1 ]; | |||||
| 250 | // Reorder the confi guration l ist and sa ve it to f ile to sav e the rece nt configu ration as a latest o ne. | |||||
| 251 | if (config Number != configurat ions.Count ) | |||||
| 252 | { | |||||
| 253 | Config uration te mp = confi gurations[ configurat ions.Count - 1]; | |||||
| 254 | config urations[c onfigurati ons.Count - 1] = con figuration s[configNu mber - 1]; | |||||
| 255 | config urations[c onfigNumbe r - 1] = t emp; | |||||
| 256 | } | |||||
| 257 | addConfig = false; | |||||
| 258 | } | |||||
| 259 | else | |||||
| 260 | throw new InvalidOpe rationExce ption("The specified server co nfiguratio n does not exist."); | |||||
| 261 | } | |||||
| 262 | else | |||||
| 263 | addC onfig = tr ue; | |||||
| 264 | ||||||
| 265 | if (addC onfig) | |||||
| 266 | { | |||||
| 267 | // G et the ser ver addres s. If no v alue is en tered, def ault to Mi crosoft Dy namics | |||||
| 268 | // C RM Online in the Nor th America n data cen ter. | |||||
| 269 | conf ig.ServerA ddress = G etServerAd dress(out ssl); | |||||
| 270 | ||||||
| 271 | if ( String.IsN ullOrWhite Space(conf ig.ServerA ddress)) | |||||
| 272 | config.Ser verAddress = "crm.dy namics.com "; | |||||
| 273 | ||||||
| 274 | ||||||
| 275 | // O ne of the Microsoft Dynamics C RM Online data cente rs. | |||||
| 276 | if ( config.Ser verAddress .EndsWith( ".dynamics .com", Str ingCompari son.Invari antCulture IgnoreCase )) | |||||
| 277 | { | |||||
| 278 | // Check i f the orga nization i s provisio ned in Mic rosoft Off ice 365. | |||||
| 279 | if (GetOrg Type(confi g.ServerAd dress)) | |||||
| 280 | { | |||||
| 281 | config.Dis coveryUri = | |||||
| 282 | new Ur i(String.F ormat("htt ps://disco .{0}/XRMSe rvices/201 1/Discover y.svc", co nfig.Serve rAddress)) ; | |||||
| 283 | } | |||||
| 284 | else | |||||
| 285 | { | |||||
| 286 | config.Dis coveryUri = | |||||
| 287 | new Ur i(String.F ormat("htt ps://dev.{ 0}/XRMServ ices/2011/ Discovery. svc", conf ig.ServerA ddress)); | |||||
| 288 | ||||||
| 289 | // Get or set the de vice crede ntials. Th is is requ ired for M icrosoft a ccount aut henticatio n. | |||||
| 290 | config.Dev iceCredent ials = Get DeviceCred entials(); | |||||
| 291 | } | |||||
| 292 | } | |||||
| 293 | // C heck if th e server u ses Secure Socket La yer (https ). | |||||
| 294 | else if (ssl) | |||||
| 295 | config.Dis coveryUri = | |||||
| 296 | new Ur i(String.F ormat("htt ps://{0}/X RMServices /2011/Disc overy.svc" , config.S erverAddre ss)); | |||||
| 297 | else | |||||
| 298 | config.Dis coveryUri = | |||||
| 299 | new Ur i(String.F ormat("htt p://{0}/XR MServices/ 2011/Disco very.svc", config.Se rverAddres s)); | |||||
| 300 | ||||||
| 301 | // G et the tar get organi zation. | |||||
| 302 | conf ig.Organiz ationUri = GetOrgani zationAddr ess(); | |||||
| 303 | conf igurations .Add(confi g); | |||||
| 304 | int length = c onfigurati ons.Count; | |||||
| 305 | int i = length - 2; | |||||
| 306 | // C heck if a new config uration al ready exis ts. | |||||
| 307 | // I f found, r eorder lis t to show latest in use. | |||||
| 308 | whil e (i > 0) | |||||
| 309 | { | |||||
| 310 | ||||||
| 311 | if (config urations[c onfigurati ons.Count - 1].Equal s(configur ations[i]) ) | |||||
| 312 | { | |||||
| 313 | config urations.R emoveAt(i) ; | |||||
| 314 | } | |||||
| 315 | i--; | |||||
| 316 | } | |||||
| 317 | // S et max con figuration s to 9 oth erwise ove rwrite exi sting one. | |||||
| 318 | if ( configurat ions.Count > 9) | |||||
| 319 | { | |||||
| 320 | configurat ions.Remov eAt(0); | |||||
| 321 | } | |||||
| 322 | } | |||||
| 323 | else | |||||
| 324 | { | |||||
| 325 | // G et the exi sting user 's logon c redentials . | |||||
| 326 | conf ig.Credent ials = Get UserLogonC redentials (config); | |||||
| 327 | } | |||||
| 328 | SaveConf igurations (); | |||||
| 329 | return c onfig; | |||||
| 330 | } | |||||
| 331 | ||||||
| 332 | // / <summary > | |||||
| 333 | // / Discover s the orga nizations that the c alling use r belongs to. | |||||
| 334 | // / </summar y> | |||||
| 335 | // / <param n ame="servi ce">A Disc overy serv ice proxy instance.< /param> | |||||
| 336 | // / <returns >Array con taining de tailed inf ormation o n each org anization that | |||||
| 337 | // / the user belongs t o.</return s> | |||||
| 338 | pu blic Organ izationDet ailCollect ion Discov erOrganiza tions(IDis coveryServ ice servic e) | |||||
| 339 | { | |||||
| 340 | if (serv ice == nul l) throw n ew Argumen tNullExcep tion("serv ice"); | |||||
| 341 | Retrieve Organizati onsRequest orgReques t = new Re trieveOrga nizationsR equest(); | |||||
| 342 | Retrieve Organizati onsRespons e orgRespo nse = | |||||
| 343 | (Ret rieveOrgan izationsRe sponse)ser vice.Execu te(orgRequ est); | |||||
| 344 | ||||||
| 345 | return o rgResponse .Details; | |||||
| 346 | } | |||||
| 347 | ||||||
| 348 | // / <summary > | |||||
| 349 | // / Finds a specific o rganizatio n detail i n the arra y of organ ization de tails | |||||
| 350 | // / returned from the Discovery service. | |||||
| 351 | // / </summar y> | |||||
| 352 | // / <param n ame="orgFr iendlyName ">The frie ndly name of the org anization to find.</ param> | |||||
| 353 | // / <param n ame="orgDe tails">Arr ay of orga nization d etail obje ct returne d from the discovery service.< /param> | |||||
| 354 | // / <returns >Organizat ion detail s or null if the org anization was not fo und.</retu rns> | |||||
| 355 | // / <seealso cref="Dis coveryOrga nizations" /> | |||||
| 356 | pu blic Organ izationDet ail FindOr ganization (string or gFriendlyN ame, | |||||
| 357 | Organiza tionDetail [] orgDeta ils) | |||||
| 358 | { | |||||
| 359 | if (Stri ng.IsNullO rWhiteSpac e(orgFrien dlyName)) | |||||
| 360 | thro w new Argu mentNullEx ception("o rgFriendly Name"); | |||||
| 361 | if (orgD etails == null) | |||||
| 362 | thro w new Argu mentNullEx ception("o rgDetails" ); | |||||
| 363 | Organiza tionDetail orgDetail = null; | |||||
| 364 | ||||||
| 365 | foreach (Organizat ionDetail detail in orgDetails ) | |||||
| 366 | { | |||||
| 367 | if ( String.Com pare(detai l.Friendly Name, orgF riendlyNam e, | |||||
| 368 | StringComp arison.Inv ariantCult ureIgnoreC ase) == 0) | |||||
| 369 | { | |||||
| 370 | orgDetail = detail; | |||||
| 371 | break; | |||||
| 372 | } | |||||
| 373 | } | |||||
| 374 | return o rgDetail; | |||||
| 375 | } | |||||
| 376 | ||||||
| 377 | // / <summary > | |||||
| 378 | // / Reads a server con figuration file. | |||||
| 379 | // / Read the configura tion from disk, if i t exists, at C:\User s\YourUser Name\AppDa ta\Roaming \CrmServer \Credentia ls.xml. | |||||
| 380 | // / </summar y> | |||||
| 381 | // / <returns >Is config uration se ttings alr eady avail able on di sk.</retur ns> | |||||
| 382 | pu blic Boole an ReadCon figuration s() | |||||
| 383 | { | |||||
| 384 | Boolean isConfigEx ist = fals e; | |||||
| 385 | ||||||
| 386 | if (conf igurations == null) | |||||
| 387 | conf igurations = new Lis t<Configur ation>(); | |||||
| 388 | ||||||
| 389 | if (File .Exists(Cr mServiceHe lperConsta nts.Server Credential sFile)) | |||||
| 390 | { | |||||
| 391 | XEle ment confi gurationsF romFile = | |||||
| 392 | XElement.L oad(CrmSer viceHelper Constants. ServerCred entialsFil e); | |||||
| 393 | fore ach (XElem ent config in config urationsFr omFile.Nod es()) | |||||
| 394 | { | |||||
| 395 | Configurat ion newCon fig = new Configurat ion(); | |||||
| 396 | var server Address = config.Ele ment("Serv erAddress" ); | |||||
| 397 | if (server Address != null) | |||||
| 398 | if (!S tring.IsNu llOrEmpty( serverAddr ess.Value) ) | |||||
| 399 | ne wConfig.Se rverAddres s = server Address.Va lue; | |||||
| 400 | var organi zationName = config. Element("O rganizatio nName"); | |||||
| 401 | if (organi zationName != null) | |||||
| 402 | if (!S tring.IsNu llOrEmpty( organizati onName.Val ue)) | |||||
| 403 | ne wConfig.Or ganization Name = org anizationN ame.Value; | |||||
| 404 | var discov eryUri = c onfig.Elem ent("Disco veryUri"); | |||||
| 405 | if (discov eryUri != null) | |||||
| 406 | if (!S tring.IsNu llOrEmpty( discoveryU ri.Value)) | |||||
| 407 | ne wConfig.Di scoveryUri = new Uri (discovery Uri.Value) ; | |||||
| 408 | var organi zationUri = config.E lement("Or ganization Uri"); | |||||
| 409 | if (organi zationUri != null) | |||||
| 410 | if (!S tring.IsNu llOrEmpty( organizati onUri.Valu e)) | |||||
| 411 | ne wConfig.Or ganization Uri = new Uri(organi zationUri. Value); | |||||
| 412 | var homeRe almUri = c onfig.Elem ent("HomeR ealmUri"); | |||||
| 413 | if (homeRe almUri != null) | |||||
| 414 | if (!S tring.IsNu llOrEmpty( homeRealmU ri.Value)) | |||||
| 415 | ne wConfig.Ho meRealmUri = new Uri (homeRealm Uri.Value) ; | |||||
| 416 | ||||||
| 417 | var vendpo intType = config.Ele ment("Endp ointType") ; | |||||
| 418 | if (vendpo intType != null) | |||||
| 419 | newCon fig.Endpoi ntType = | |||||
| 420 | Retrieve Authentica tionType(v endpointTy pe.Value); | |||||
| 421 | if (config .Element(" Credential s").HasEle ments) | |||||
| 422 | { | |||||
| 423 | newCon fig.Creden tials = | |||||
| 424 | Pa rseInCrede ntials(con fig.Elemen t("Credent ials"), | |||||
| 425 | ne wConfig.En dpointType , | |||||
| 426 | ne wConfig.Se rverAddres s + ":" + newConfig. Organizati onName + " :" + confi g.Element( "Credentia ls").Eleme nt("UserNa me").Value ); | |||||
| 427 | } | |||||
| 428 | if (newCon fig.Endpoi ntType == Authentica tionProvid erType.Liv eId) | |||||
| 429 | { | |||||
| 430 | newCon fig.Device Credential s = GetDev iceCredent ials(); | |||||
| 431 | } | |||||
| 432 | var userPr incipalNam e = config .Element(" UserPrinci palName"); | |||||
| 433 | if (userPr incipalNam e != null) | |||||
| 434 | if (!S tring.IsNu llOrWhiteS pace(userP rincipalNa me.Value)) | |||||
| 435 | ne wConfig.Us erPrincipa lName = us erPrincipa lName.Valu e; | |||||
| 436 | configurat ions.Add(n ewConfig); | |||||
| 437 | } | |||||
| 438 | } | |||||
| 439 | ||||||
| 440 | if (conf igurations .Count > 0 ) | |||||
| 441 | isCo nfigExist = true; | |||||
| 442 | ||||||
| 443 | return i sConfigExi st; | |||||
| 444 | } | |||||
| 445 | ||||||
| 446 | // / <summary > | |||||
| 447 | // / Writes a ll server configurat ions to a file. | |||||
| 448 | // / </summar y> | |||||
| 449 | // / <remarks >If the fi le exists, it is ove rwritten.< /remarks> | |||||
| 450 | pu blic void SaveConfig urations() | |||||
| 451 | { | |||||
| 452 | if (conf igurations == null) | |||||
| 453 | thro w new Null ReferenceE xception(" No server connection configura tions were found."); | |||||
| 454 | ||||||
| 455 | FileInfo file = ne w FileInfo (CrmServic eHelperCon stants.Ser verCredent ialsFile); | |||||
| 456 | ||||||
| 457 | // Creat e director y if it do es not exi st. | |||||
| 458 | if (!fil e.Director y.Exists) | |||||
| 459 | file .Directory .Create(); | |||||
| 460 | ||||||
| 461 | // Repla ce the fil e if it ex ists. | |||||
| 462 | using (F ileStream fs = file. Open(FileM ode.Create , FileAcce ss.Write, FileShare. None)) | |||||
| 463 | { | |||||
| 464 | usin g (XmlText Writer wri ter = new XmlTextWri ter(fs, En coding.UTF 8)) | |||||
| 465 | { | |||||
| 466 | writer.For matting = Formatting .Indented; | |||||
| 467 | writer.Wri teStartDoc ument(); | |||||
| 468 | writer.Wri teStartEle ment("Conf igurations "); | |||||
| 469 | writer.Wri teFullEndE lement(); | |||||
| 470 | writer.Wri teEndDocum ent(); | |||||
| 471 | } | |||||
| 472 | } | |||||
| 473 | ||||||
| 474 | foreach (Configura tion confi g in confi gurations) | |||||
| 475 | Save Configurat ion(CrmSer viceHelper Constants. ServerCred entialsFil e, config, true); | |||||
| 476 | } | |||||
| 477 | ||||||
| 478 | // / <summary > | |||||
| 479 | // / Writes a server co nfiguratio n to a fil e. | |||||
| 480 | // / </summar y> | |||||
| 481 | // / <param n ame="pathn ame">The f ile name a nd system path of th e output c onfigurati on file.</ param> | |||||
| 482 | // / <param n ame="confi g">A serve r connecti on configu ration.</p aram> | |||||
| 483 | // / <param n ame="appen d">If true , the conf iguration is appende d to the f ile, other wise a new file | |||||
| 484 | // / is creat ed.</param > | |||||
| 485 | pu blic void SaveConfig uration(St ring pathn ame, Confi guration c onfig, boo l append) | |||||
| 486 | { | |||||
| 487 | if (Stri ng.IsNullO rWhiteSpac e(pathname )) throw n ew Argumen tNullExcep tion("path name"); | |||||
| 488 | if (conf ig == null ) throw ne w Argument NullExcept ion("confi g"); | |||||
| 489 | // Targe t is the k ey with wh ich associ ated crede ntials can be fetche d from win dows crede ntials man ager. | |||||
| 490 | String t arget = co nfig.Serve rAddress + ":" + con fig.Organi zationName ; | |||||
| 491 | if(null != config. Credential s) | |||||
| 492 | { | |||||
| 493 | swit ch(config. EndpointTy pe) | |||||
| 494 | { | |||||
| 495 | case Authe nticationP roviderTyp e.ActiveDi rectory: | |||||
| 496 | target = target + ":" + co nfig.Crede ntials.Win dows.Clien tCredentia l.UserName ; | |||||
| 497 | break; | |||||
| 498 | case Authe nticationP roviderTyp e.LiveId: | |||||
| 499 | case Authe nticationP roviderTyp e.Federati on: | |||||
| 500 | case Authe nticationP roviderTyp e.OnlineFe deration: | |||||
| 501 | target = target + ":" + co nfig.Crede ntials.Use rName.User Name; | |||||
| 502 | break; | |||||
| 503 | default: | |||||
| 504 | target = String. Empty; | |||||
| 505 | break; | |||||
| 506 | } | |||||
| 507 | } | |||||
| 508 | ||||||
| 509 | XElement configura tionsFromF ile = XEle ment.Load( pathname); | |||||
| 510 | XElement newConfig = | |||||
| 511 | new XElement(" Configurat ion", | |||||
| 512 | new XEleme nt("Server Address", config.Ser verAddress ), | |||||
| 513 | new XEleme nt("Organi zationName ", config. Organizati onName), | |||||
| 514 | new XEleme nt("Discov eryUri", | |||||
| 515 | (confi g.Discover yUri != nu ll) | |||||
| 516 | ? conf ig.Discove ryUri.Orig inalString | |||||
| 517 | : Stri ng.Empty), | |||||
| 518 | new XEleme nt("Organi zationUri" , | |||||
| 519 | (confi g.Organiza tionUri != null) | |||||
| 520 | ? conf ig.Organiz ationUri.O riginalStr ing | |||||
| 521 | : Stri ng.Empty), | |||||
| 522 | new XEleme nt("HomeRe almUri", | |||||
| 523 | (confi g.HomeReal mUri != nu ll) | |||||
| 524 | ? conf ig.HomeRea lmUri.Orig inalString | |||||
| 525 | : Stri ng.Empty), | |||||
| 526 | ParseOutCr edentials( config.Cre dentials, config.End pointType, target), | |||||
| 527 | new XEleme nt("Endpoi ntType", c onfig.Endp ointType.T oString()) , | |||||
| 528 | new XEleme nt("UserPr incipalNam e", | |||||
| 529 | (confi g.UserPrin cipalName != null) | |||||
| 530 | ? conf ig.UserPri ncipalName | |||||
| 531 | : Stri ng.Empty) | |||||
| 532 | ); | |||||
| 533 | ||||||
| 534 | if (appe nd) | |||||
| 535 | { | |||||
| 536 | conf igurations FromFile.A dd(newConf ig); | |||||
| 537 | } | |||||
| 538 | else | |||||
| 539 | { | |||||
| 540 | conf igurations FromFile.R eplaceAll( newConfig) ; | |||||
| 541 | } | |||||
| 542 | ||||||
| 543 | using (X mlTextWrit er writer = new XmlT extWriter( pathname, Encoding.U TF8)) | |||||
| 544 | { | |||||
| 545 | writ er.Formatt ing = Form atting.Ind ented; | |||||
| 546 | conf igurations FromFile.S ave(writer ); | |||||
| 547 | } | |||||
| 548 | } | |||||
| 549 | ||||||
| 550 | // / <summary > | |||||
| 551 | // / Obtains the user's logon cre dentials f or the tar get server . | |||||
| 552 | // / </summar y> | |||||
| 553 | // / <param n ame="confi g">An inst ance of th e Configur ation.</pa ram> | |||||
| 554 | // / <returns >Logon cre dentials o f the user .</returns > | |||||
| 555 | pu blic stati c ClientCr edentials GetUserLog onCredenti als(Server Connection .Configura tion confi g) | |||||
| 556 | { | |||||
| 557 | ClientCr edentials credential s = new Cl ientCreden tials(); | |||||
| 558 | String u serName; | |||||
| 559 | SecureSt ring passw ord; | |||||
| 560 | String d omain; | |||||
| 561 | Boolean isCredenti alExist = (config.Cr edentials != null) ? true : fa lse; | |||||
| 562 | switch ( config.End pointType) | |||||
| 563 | { | |||||
| 564 | // A n on-premi ses Micros oft Dynami cs CRM ser ver deploy ment. | |||||
| 565 | case Authentic ationProvi derType.Ac tiveDirect ory: | |||||
| 566 | // Uses cr edentials from windo ws credent ial manage r for earl ier saved configurat ion. | |||||
| 567 | if (isCred entialExis t && !Stri ng.IsNullO rWhiteSpac e(config.O rganizatio nName)) | |||||
| 568 | { | |||||
| 569 | domain = config. Credential s.Windows. ClientCred ential.Dom ain; | |||||
| 570 | userNa me = confi g.Credenti als.Window s.ClientCr edential.U serName; | |||||
| 571 | if (St ring.IsNul lOrWhiteSp ace(config .Credentia ls.Windows .ClientCre dential.Pa ssword)) | |||||
| 572 | { | |||||
| 573 | Co nsole.Writ e("\nEnter domain\\u sername: " ); | |||||
| 574 | Co nsole.Writ eLine( | |||||
| 575 | co nfig.Crede ntials.Win dows.Clien tCredentia l.Domain + "\\" | |||||
| 576 | + config.Cre dentials.W indows.Cli entCredent ial.UserNa me); | |||||
| 577 | ||||||
| 578 | Co nsole.Writ e(" Enter Pass word: "); | |||||
| 579 | pa ssword = R eadPasswor d(); | |||||
| 580 | } | |||||
| 581 | else | |||||
| 582 | { | |||||
| 583 | pa ssword = c onfig.Cred entials.Wi ndows.Clie ntCredenti al.SecureP assword; | |||||
| 584 | } | |||||
| 585 | } | |||||
| 586 | // Uses de fault cred entials sa ved in win dows crede ntial mana ger for cu rrent orga nization. | |||||
| 587 | else if (! isCredenti alExist && !String.I sNullOrWhi teSpace(co nfig.Organ izationNam e)) | |||||
| 588 | { | |||||
| 589 | return null; | |||||
| 590 | } | |||||
| 591 | // Prompts users to enter cred ential for current o rganizatio n. | |||||
| 592 | else | |||||
| 593 | { | |||||
| 594 | String [] domainA ndUserName ; | |||||
| 595 | do | |||||
| 596 | { | |||||
| 597 | Co nsole.Writ e("\nEnter domain\\u sername: " ); | |||||
| 598 | do mainAndUse rName = Co nsole.Read Line().Spl it('\\'); | |||||
| 599 | ||||||
| 600 | // If user d o not choo se to ente r user nam e, | |||||
| 601 | // then try to use def ault crede ntial from windows c redential manager. | |||||
| 602 | if (domainAn dUserName. Length == 1 && Strin g.IsNullOr WhiteSpace (domainAnd UserName[0 ])) | |||||
| 603 | { | |||||
| 604 | return n ull; | |||||
| 605 | } | |||||
| 606 | } | |||||
| 607 | while (domainAnd UserName.L ength != 2 || String .IsNullOrW hiteSpace( domainAndU serName[0] ) | |||||
| 608 | || String.Is NullOrWhit eSpace(dom ainAndUser Name[1])); | |||||
| 609 | ||||||
| 610 | domain = domainA ndUserName [0]; | |||||
| 611 | userNa me = domai nAndUserNa me[1]; | |||||
| 612 | ||||||
| 613 | Consol e.Write(" Ente r Password : "); | |||||
| 614 | passwo rd = ReadP assword(); | |||||
| 615 | } | |||||
| 616 | if (null ! = password ) | |||||
| 617 | { | |||||
| 618 | creden tials.Wind ows.Client Credential = | |||||
| 619 | ne w System.N et.Network Credential (userName, password, domain); | |||||
| 620 | } | |||||
| 621 | else | |||||
| 622 | { | |||||
| 623 | creden tials.Wind ows.Client Credential = null; | |||||
| 624 | } | |||||
| 625 | ||||||
| 626 | break; | |||||
| 627 | // A Microsoft Dynamics CRM Online server de ployment. | |||||
| 628 | case Authentic ationProvi derType.Li veId: | |||||
| 629 | // A n internet -facing de ployment ( IFD) of Mi crosoft Dy namics CRM . | |||||
| 630 | case Authentic ationProvi derType.Fe deration: | |||||
| 631 | // M anaged Ide ntity/Fede rated Iden tity users using Mic rosoft Off ice 365. | |||||
| 632 | case Authentic ationProvi derType.On lineFedera tion: | |||||
| 633 | // Use sav ed credent ials. | |||||
| 634 | if (isCred entialExis t) | |||||
| 635 | { | |||||
| 636 | userNa me = confi g.Credenti als.UserNa me.UserNam e; | |||||
| 637 | if (St ring.IsNul lOrWhiteSp ace(config .Credentia ls.UserNam e.Password )) | |||||
| 638 | { | |||||
| 639 | Co nsole.Writ e("\n Ente r Username : "); | |||||
| 640 | Co nsole.Writ eLine(conf ig.Credent ials.UserN ame.UserNa me); | |||||
| 641 | ||||||
| 642 | Co nsole.Writ e(" Enter Password: "); | |||||
| 643 | pa ssword = R eadPasswor d(); | |||||
| 644 | } | |||||
| 645 | else | |||||
| 646 | { | |||||
| 647 | pa ssword = C onvertToSe cureString (config.Cr edentials. UserName.P assword); | |||||
| 648 | } | |||||
| 649 | } | |||||
| 650 | // For Onl ineFederat ion enviro nments, in itially tr y to authe nticate wi th the cur rent UserP rincipalNa me | |||||
| 651 | // for sin gle sign-o n scenario . | |||||
| 652 | else if (c onfig.Endp ointType = = Authenti cationProv iderType.O nlineFeder ation | |||||
| 653 | && con fig.AuthFa ilureCount == 0 | |||||
| 654 | && !St ring.IsNul lOrWhiteSp ace(UserPr incipal.Cu rrent.User PrincipalN ame)) | |||||
| 655 | { | |||||
| 656 | config .UserPrinc ipalName = UserPrinc ipal.Curre nt.UserPri ncipalName ; | |||||
| 657 | return null; | |||||
| 658 | } | |||||
| 659 | // Otherwi se request username and passwo rd. | |||||
| 660 | else | |||||
| 661 | { | |||||
| 662 | config .UserPrinc ipalName = String.Em pty; | |||||
| 663 | if (co nfig.Endpo intType == Authentic ationProvi derType.Li veId) | |||||
| 664 | Co nsole.Writ e("\n Ente r Microsof t account: "); | |||||
| 665 | else | |||||
| 666 | Co nsole.Writ e("\n Ente r Username : "); | |||||
| 667 | userNa me = Conso le.ReadLin e(); | |||||
| 668 | if (st ring.IsNul lOrWhiteSp ace(userNa me)) | |||||
| 669 | { | |||||
| 670 | re turn null; | |||||
| 671 | } | |||||
| 672 | ||||||
| 673 | Consol e.Write(" Enter Pass word: "); | |||||
| 674 | passwo rd = ReadP assword(); | |||||
| 675 | } | |||||
| 676 | credential s.UserName .UserName = userName ; | |||||
| 677 | credential s.UserName .Password = ConvertT oUnsecureS tring(pass word); | |||||
| 678 | break; | |||||
| 679 | defa ult: | |||||
| 680 | credential s = null; | |||||
| 681 | break; | |||||
| 682 | } | |||||
| 683 | return c redentials ; | |||||
| 684 | } | |||||
| 685 | ||||||
| 686 | // / <summary > | |||||
| 687 | // / Prompts user to en ter passwo rd in cons ole window | |||||
| 688 | // / and capt ure the en tered pass word into SecureStri ng. | |||||
| 689 | // / </summar y> | |||||
| 690 | // / <returns >Password stored in a secure s tring.</re turns> | |||||
| 691 | pu blic stati c SecureSt ring ReadP assword() | |||||
| 692 | { | |||||
| 693 | SecureSt ring ssPas sword = ne w SecureSt ring(); | |||||
| 694 | ||||||
| 695 | ConsoleK eyInfo inf o = Consol e.ReadKey( true); | |||||
| 696 | while (i nfo.Key != ConsoleKe y.Enter) | |||||
| 697 | { | |||||
| 698 | if ( info.Key = = ConsoleK ey.Backspa ce) | |||||
| 699 | { | |||||
| 700 | if (ssPass word.Lengt h != 0) | |||||
| 701 | { | |||||
| 702 | ssPass word.Remov eAt(ssPass word.Lengt h - 1); | |||||
| 703 | Consol e.Write("\ b \b"); // erase last char | |||||
| 704 | } | |||||
| 705 | } | |||||
| 706 | else if (info. KeyChar >= ' ') // n o control chars | |||||
| 707 | { | |||||
| 708 | ssPassword .AppendCha r(info.Key Char); | |||||
| 709 | Console.Wr ite("*"); | |||||
| 710 | } | |||||
| 711 | info = Console .ReadKey(t rue); | |||||
| 712 | } | |||||
| 713 | ||||||
| 714 | Console. WriteLine( ); | |||||
| 715 | Console. WriteLine( ); | |||||
| 716 | ||||||
| 717 | // Lock the secure string pa ssword. | |||||
| 718 | ssPasswo rd.MakeRea dOnly(); | |||||
| 719 | ||||||
| 720 | return s sPassword; | |||||
| 721 | } | |||||
| 722 | ||||||
| 723 | // / <summary > | |||||
| 724 | // / Generic method to obtain dis covery/org anization service pr oxy instan ce. | |||||
| 725 | // / </summar y> | |||||
| 726 | // / <typepar am name="T Service"> | |||||
| 727 | // / Set IDis coveryServ ice or IOr ganization Service ty pe | |||||
| 728 | // / to reque st respect ive servic e proxy in stance. | |||||
| 729 | // / </typepa ram> | |||||
| 730 | // / <typepar am name="T Proxy"> | |||||
| 731 | // / Set the return typ e to eithe r Discover yServicePr oxy | |||||
| 732 | // / or Organ izationSer viceProxy type based on TServi ce type. | |||||
| 733 | // / </typepa ram> | |||||
| 734 | // / <param n ame="curre ntConfig"> An instanc e of exist ing Config uration</p aram> | |||||
| 735 | // / <returns >An instan ce of TPro xy | |||||
| 736 | // / i.e. Dis coveryServ iceProxy o r Organiza tionServic eProxy</re turns> | |||||
| 737 | pu blic stati c TProxy G etProxy<TS ervice, TP roxy>(Serv erConnecti on.Configu ration cur rentConfig ) | |||||
| 738 | where TS ervice : c lass | |||||
| 739 | where TP roxy : Ser viceProxy< TService> | |||||
| 740 | { | |||||
| 741 | // Check if it is organizati on service proxy req uest. | |||||
| 742 | Boolean isOrgServi ceRequest = typeof(T Service).E quals(type of(IOrgani zationServ ice)); | |||||
| 743 | ||||||
| 744 | // Get a ppropriate Uri from Configurat ion. | |||||
| 745 | Uri serv iceUri = i sOrgServic eRequest ? | |||||
| 746 | curr entConfig. Organizati onUri : cu rrentConfi g.Discover yUri; | |||||
| 747 | ||||||
| 748 | // Set s ervice man agement fo r either o rganizatio n service Uri or dis covery ser vice Uri. | |||||
| 749 | // For o rganizatio n service Uri, if se rvice mana gement exi sts | |||||
| 750 | // then use it fro m cache. O therwise c reate new service ma nagement f or current organizat ion. | |||||
| 751 | IService Management <TService> serviceMa nagement = | |||||
| 752 | (isO rgServiceR equest && null != cu rrentConfi g.Organiza tionServic eManagemen t) ? | |||||
| 753 | (ISe rviceManag ement<TSer vice>)curr entConfig. Organizati onServiceM anagement : | |||||
| 754 | Serv iceConfigu rationFact ory.Create Management <TService> ( | |||||
| 755 | serv iceUri); | |||||
| 756 | ||||||
| 757 | if (isOr gServiceRe quest) | |||||
| 758 | { | |||||
| 759 | if ( currentCon fig.Organi zationToke nResponse == null) | |||||
| 760 | { | |||||
| 761 | currentCon fig.Organi zationServ iceManagem ent = | |||||
| 762 | (IServ iceManagem ent<IOrgan izationSer vice>)serv iceManagem ent; | |||||
| 763 | } | |||||
| 764 | } | |||||
| 765 | // Set t he Endpoin tType in t he current Configura tion objec t | |||||
| 766 | // while adding ne w configur ation usin g discover y service proxy. | |||||
| 767 | else | |||||
| 768 | { | |||||
| 769 | // G et the End pointType. | |||||
| 770 | curr entConfig. EndpointTy pe = servi ceManageme nt.Authent icationTyp e; | |||||
| 771 | // G et the log on credent ials. | |||||
| 772 | curr entConfig. Credential s = GetUse rLogonCred entials(cu rrentConfi g); | |||||
| 773 | } | |||||
| 774 | ||||||
| 775 | // Set t he credent ials. | |||||
| 776 | Authenti cationCred entials au thCredenti als = new Authentica tionCreden tials(); | |||||
| 777 | ||||||
| 778 | // If Us erPrincipa lName exis ts, use it . Otherwis e, set the logon cre dentials f rom the co nfiguratio n. | |||||
| 779 | if (!Str ing.IsNull OrWhiteSpa ce(current Config.Use rPrincipal Name)) | |||||
| 780 | { | |||||
| 781 | // S ingle sing -on with t he Federat ed Identit y organiza tion using current U serPrinici palName. | |||||
| 782 | auth Credential s.UserPrin cipalName = currentC onfig.User PrincipalN ame; | |||||
| 783 | } | |||||
| 784 | else | |||||
| 785 | { | |||||
| 786 | auth Credential s.ClientCr edentials = currentC onfig.Cred entials; | |||||
| 787 | } | |||||
| 788 | ||||||
| 789 | Type cla ssType; | |||||
| 790 | ||||||
| 791 | // Obtai n discover y/organiza tion servi ce proxy f or Federat ed, | |||||
| 792 | // Micro soft accou nt and Onl ineFederat ed environ ments. | |||||
| 793 | if (curr entConfig. EndpointTy pe != | |||||
| 794 | Auth entication ProviderTy pe.ActiveD irectory) | |||||
| 795 | { | |||||
| 796 | if ( currentCon fig.Endpoi ntType == Authentica tionProvid erType.Liv eId) | |||||
| 797 | { | |||||
| 798 | authCreden tials.Supp ortingCred entials = new Authen ticationCr edentials( ); | |||||
| 799 | authCreden tials.Supp ortingCred entials.Cl ientCreden tials = | |||||
| 800 | curren tConfig.De viceCreden tials; | |||||
| 801 | } | |||||
| 802 | ||||||
| 803 | Auth entication Credential s tokenCre dentials = | |||||
| 804 | serviceMan agement.Au thenticate ( | |||||
| 805 | authCr edentials) ; | |||||
| 806 | ||||||
| 807 | i f (isOrgSe rviceReque st) | |||||
| 808 | { | |||||
| 809 | // Set Sec urityToken Response f or the cur rent organ ization. | |||||
| 810 | currentCon fig.Organi zationToke nResponse = tokenCre dentials.S ecurityTok enResponse ; | |||||
| 811 | // Set cla ssType to ManagedTok enOrganiza tionServic eProxy. | |||||
| 812 | classType = typeof(M anagedToke nOrganizat ionService Proxy); | |||||
| 813 | ||||||
| 814 | } | |||||
| 815 | else | |||||
| 816 | { | |||||
| 817 | // Set cla ssType to ManagedTok enDiscover yServicePr oxy. | |||||
| 818 | classType = typeof(M anagedToke nDiscovery ServicePro xy); | |||||
| 819 | } | |||||
| 820 | ||||||
| 821 | // I nvokes Man agedTokenO rganizatio nServicePr oxy or Man agedTokenD iscoverySe rviceProxy | |||||
| 822 | // ( IServiceMa nagement<T Service>, SecurityTo kenRespons e) constru ctor. | |||||
| 823 | retu rn (TProxy )classType | |||||
| 824 | .Get Constructo r(new Type [] | |||||
| 825 | { | |||||
| 826 | typeof (IServiceM anagement< TService>) , | |||||
| 827 | typeof (SecurityT okenRespon se) | |||||
| 828 | }) | |||||
| 829 | .Inv oke(new ob ject[] | |||||
| 830 | { | |||||
| 831 | servic eManagemen t, | |||||
| 832 | tokenC redentials .SecurityT okenRespon se | |||||
| 833 | }); | |||||
| 834 | } | |||||
| 835 | ||||||
| 836 | // Obtai n discover y/organiza tion servi ce proxy f or ActiveD irectory e nvironment . | |||||
| 837 | if (isOr gServiceRe quest) | |||||
| 838 | { | |||||
| 839 | clas sType = ty peof(Manag edTokenOrg anizationS erviceProx y); | |||||
| 840 | } | |||||
| 841 | else | |||||
| 842 | { | |||||
| 843 | clas sType = ty peof(Manag edTokenDis coveryServ iceProxy); | |||||
| 844 | } | |||||
| 845 | ||||||
| 846 | // Invok es Managed TokenDisco veryServic eProxy or ManagedTok enOrganiza tionServic eProxy | |||||
| 847 | // (ISer viceManage ment<TServ ice>, Clie ntCredenti als) const ructor. | |||||
| 848 | return ( TProxy)cla ssType | |||||
| 849 | .Get Constructo r(new Type [] | |||||
| 850 | { | |||||
| 851 | typeof( IServiceMa nagement<T Service>), | |||||
| 852 | typeof( ClientCred entials) | |||||
| 853 | } ) | |||||
| 854 | .Invo ke(new obj ect[] | |||||
| 855 | { | |||||
| 856 | service Management , | |||||
| 857 | authCre dentials.C lientCrede ntials | |||||
| 858 | } ); | |||||
| 859 | } | |||||
| 860 | ||||||
| 861 | // / <summary > | |||||
| 862 | // / Convert SecureStri ng to unse cure strin g. | |||||
| 863 | // / </summar y> | |||||
| 864 | // / <param n ame="secur ePassword" >Pass Secu reString f or convers ion.</para m> | |||||
| 865 | // / <returns >unsecure string</re turns> | |||||
| 866 | pu blic stati c String C onvertToUn secureStri ng(SecureS tring secu rePassword ) | |||||
| 867 | { | |||||
| 868 | if (secu rePassword == null) | |||||
| 869 | thro w new Argu mentNullEx ception("s ecurePassw ord"); | |||||
| 870 | ||||||
| 871 | IntPtr u nmanagedSt ring = Int Ptr.Zero; | |||||
| 872 | try | |||||
| 873 | { | |||||
| 874 | unma nagedStrin g = Marsha l.SecureSt ringToGlob alAllocUni code(secur ePassword) ; | |||||
| 875 | retu rn Marshal .PtrToStri ngUni(unma nagedStrin g); | |||||
| 876 | } | |||||
| 877 | finally | |||||
| 878 | { | |||||
| 879 | Mars hal.ZeroFr eeGlobalAl locUnicode (unmanaged String); | |||||
| 880 | } | |||||
| 881 | } | |||||
| 882 | ||||||
| 883 | // / <summary > | |||||
| 884 | // / Convert unsecure s tring to S ecureStrin g. | |||||
| 885 | // / </summar y> | |||||
| 886 | // / <param n ame="passw ord">Pass unsecure s tring for conversion .</param> | |||||
| 887 | // / <returns >SecureStr ing</retur ns> | |||||
| 888 | pu blic stati c SecureSt ring Conve rtToSecure String(str ing passwo rd) | |||||
| 889 | { | |||||
| 890 | if (pass word == nu ll) | |||||
| 891 | thro w new Argu mentNullEx ception("p assword"); | |||||
| 892 | ||||||
| 893 | var secu rePassword = new Sec ureString( ); | |||||
| 894 | foreach (char c in password) | |||||
| 895 | secu rePassword .AppendCha r(c); | |||||
| 896 | securePa ssword.Mak eReadOnly( ); | |||||
| 897 | return s ecurePassw ord; | |||||
| 898 | } | |||||
| 899 | #e ndregion P ublic meth ods | |||||
| 900 | ||||||
| 901 | #r egion Prot ected meth ods | |||||
| 902 | ||||||
| 903 | // / <summary > | |||||
| 904 | // / Obtains the name a nd port of the serve r running the Micros oft Dynami cs CRM | |||||
| 905 | // / Discover y service. | |||||
| 906 | // / </summar y> | |||||
| 907 | // / <returns >The serve r's networ k name and optional TCP/IP por t.</return s> | |||||
| 908 | pr otected vi rtual Stri ng GetServ erAddress( out bool s sl) | |||||
| 909 | { | |||||
| 910 | ssl = fa lse; | |||||
| 911 | ||||||
| 912 | Console. Write("Ent er a CRM s erver name and port [crm.dynam ics.com]: "); | |||||
| 913 | String s erver = Co nsole.Read Line(); | |||||
| 914 | ||||||
| 915 | if (serv er.EndsWit h(".dynami cs.com") | | String.I sNullOrWhi teSpace(se rver)) | |||||
| 916 | { | |||||
| 917 | ssl = true; | |||||
| 918 | } | |||||
| 919 | else | |||||
| 920 | { | |||||
| 921 | Cons ole.Write( "Is this s erver conf igured for Secure So cket Layer (https) ( y/n) [n]: "); | |||||
| 922 | Stri ng answer = Console. ReadLine() ; | |||||
| 923 | ||||||
| 924 | if ( answer == "y" || ans wer == "Y" ) | |||||
| 925 | ssl = true ; | |||||
| 926 | } | |||||
| 927 | ||||||
| 928 | return s erver; | |||||
| 929 | } | |||||
| 930 | ||||||
| 931 | // / <summary > | |||||
| 932 | // / Is this organizati on provisi oned in Mi crosoft Of fice 365? | |||||
| 933 | // / </summar y> | |||||
| 934 | // / <param n ame="serve r">The ser ver's netw ork name.< /param> | |||||
| 935 | pr otected vi rtual Bool ean GetOrg Type(Strin g server) | |||||
| 936 | { | |||||
| 937 | Boolean isO365Org = false; | |||||
| 938 | if (Stri ng.IsNullO rWhiteSpac e(server)) | |||||
| 939 | retu rn isO365O rg; | |||||
| 940 | if (serv er.IndexOf ('.') == - 1) | |||||
| 941 | retu rn isO365O rg; | |||||
| 942 | ||||||
| 943 | Console. Write("Is this organ ization pr ovisioned in Microso ft Office 365 (y/n) [y]: "); | |||||
| 944 | String a nswer = Co nsole.Read Line(); | |||||
| 945 | ||||||
| 946 | if (answ er == "y" || answer == "Y" || answer.Equ als(String .Empty)) | |||||
| 947 | isO3 65Org = tr ue; | |||||
| 948 | ||||||
| 949 | return i sO365Org; | |||||
| 950 | } | |||||
| 951 | ||||||
| 952 | // / <summary > | |||||
| 953 | // / Obtains the web ad dress (Uri ) of the t arget orga nization. | |||||
| 954 | // / </summar y> | |||||
| 955 | // / <returns >Uri of th e organiza tion servi ce or an e mpty strin g.</return s> | |||||
| 956 | pr otected vi rtual Uri GetOrganiz ationAddre ss() | |||||
| 957 | { | |||||
| 958 | using (D iscoverySe rviceProxy servicePr oxy = GetD iscoveryPr oxy()) | |||||
| 959 | { | |||||
| 960 | // O btain orga nization i nformation from the Discovery service. | |||||
| 961 | if ( servicePro xy != null ) | |||||
| 962 | { | |||||
| 963 | // Obtain informatio n about th e organiza tions that the syste m user bel ongs to. | |||||
| 964 | Organizati onDetailCo llection o rgs = Disc overOrgani zations(se rviceProxy ); | |||||
| 965 | ||||||
| 966 | if (orgs.C ount > 0) | |||||
| 967 | { | |||||
| 968 | Consol e.WriteLin e("\nList of organiz ations tha t you belo ng to:"); | |||||
| 969 | for (i nt n = 0; n < orgs.C ount; n++) | |||||
| 970 | { | |||||
| 971 | Co nsole.Writ e("\n({0}) {1} ({2}) \t", n + 1 , orgs[n]. FriendlyNa me, orgs[n ].UrlName) ; | |||||
| 972 | } | |||||
| 973 | ||||||
| 974 | Consol e.Write("\ n\nSpecify an organi zation num ber (1-{0} ) [1]: ", orgs.Count ); | |||||
| 975 | String input = C onsole.Rea dLine(); | |||||
| 976 | if (in put == Str ing.Empty) | |||||
| 977 | { | |||||
| 978 | in put = "1"; | |||||
| 979 | } | |||||
| 980 | int or gNumber; | |||||
| 981 | Int32. TryParse(i nput, out orgNumber) ; | |||||
| 982 | if (or gNumber > 0 && orgNu mber <= or gs.Count) | |||||
| 983 | { | |||||
| 984 | co nfig.Organ izationNam e = orgs[o rgNumber - 1].Friend lyName; | |||||
| 985 | // Return th e organiza tion Uri. | |||||
| 986 | re turn new S ystem.Uri( orgs[orgNu mber - 1]. Endpoints[ EndpointTy pe.Organiz ationServi ce]); | |||||
| 987 | } | |||||
| 988 | else | |||||
| 989 | th row new In validOpera tionExcept ion("The s pecified o rganizatio n does not exist."); | |||||
| 990 | } | |||||
| 991 | else | |||||
| 992 | { | |||||
| 993 | Consol e.WriteLin e("\nYou d o not belo ng to any organizati ons on the specified server.") ; | |||||
| 994 | return new Syste m.Uri(Stri ng.Empty); | |||||
| 995 | } | |||||
| 996 | } | |||||
| 997 | else | |||||
| 998 | throw new InvalidOpe rationExce ption("An invalid se rver name was specif ied."); | |||||
| 999 | } | |||||
| 1000 | } | |||||
| 1001 | ||||||
| 1002 | // / <summary > | |||||
| 1003 | // / Get the device cre dentials b y either l oading fro m the loca l cache | |||||
| 1004 | // / or reque st new dev ice creden tials by r egistering the devic e. | |||||
| 1005 | // / </summar y> | |||||
| 1006 | // / <returns >Device Cr edentials. </returns> | |||||
| 1007 | pr otected vi rtual Clie ntCredenti als GetDev iceCredent ials() | |||||
| 1008 | { | |||||
| 1009 | return M icrosoft.C rm.Service s.Utility. DeviceIdMa nager.Load OrRegister Device(); | |||||
| 1010 | } | |||||
| 1011 | ||||||
| 1012 | // / <summary > | |||||
| 1013 | // / Get the discovery service pr oxy based on existin g configur ation data . | |||||
| 1014 | // / Added ne w way of g etting dis covery pro xy. | |||||
| 1015 | // / Also pre serving ol d way of g etting dis covery pro xy to supp ort old sc enarios. | |||||
| 1016 | // / </summar y> | |||||
| 1017 | // / <returns >An instan ce of Disc overyServi ceProxy</r eturns> | |||||
| 1018 | pr ivate Disc overyServi ceProxy Ge tDiscovery Proxy() | |||||
| 1019 | { | |||||
| 1020 | try | |||||
| 1021 | { | |||||
| 1022 | // O btain the discovery service pr oxy. | |||||
| 1023 | Disc overyServi ceProxy di scoveryPro xy = GetPr oxy<IDisco veryServic e, Discove ryServiceP roxy>(this .config); | |||||
| 1024 | // C hecking au thenticati on by invo king some SDK method s. | |||||
| 1025 | disc overyProxy .Execute(n ew Retriev eOrganizat ionsReques t()); | |||||
| 1026 | retu rn discove ryProxy; | |||||
| 1027 | } | |||||
| 1028 | catch (S ystem.Serv iceModel.S ecurity.Se curityAcce ssDeniedEx ception ex ) | |||||
| 1029 | { | |||||
| 1030 | // If auth entication failed us ing curren t UserPrin cipalName, | |||||
| 1031 | // request UserName and Passwo rd to try to authent icate usin g user cre dentials. | |||||
| 1032 | if (!Strin g.IsNullOr WhiteSpace (config.Us erPrincipa lName) && | |||||
| 1033 | ex.Mes sage.Conta ins("Acces s is denie d.")) | |||||
| 1034 | { | |||||
| 1035 | config .AuthFailu reCount += 1; | |||||
| 1036 | } | |||||
| 1037 | else | |||||
| 1038 | { | |||||
| 1039 | throw ex; | |||||
| 1040 | } | |||||
| 1041 | } | |||||
| 1042 | // You c an also ca tch other exceptions to handle a specifi c situatio n in your code, for example, | |||||
| 1043 | // System.Ser viceModel. Security.E xpiredSecu rityTokenE xception | |||||
| 1044 | // System.Ser viceModel. Security.M essageSecu rityExcept ion | |||||
| 1045 | // System.Ser viceModel. Security.S ecurityNeg otiationEx ception | |||||
| 1046 | ||||||
| 1047 | // Secon d trial to obtain th e discover y service proxy in c ase of sin gle sign-o n failure. | |||||
| 1048 | return G etProxy<ID iscoverySe rvice, Dis coveryServ iceProxy>( this.confi g); | |||||
| 1049 | ||||||
| 1050 | } | |||||
| 1051 | ||||||
| 1052 | // / <summary > | |||||
| 1053 | // / Verify p assed stri ngs with t he support ed Authent icationPro viderType. | |||||
| 1054 | // / </summar y> | |||||
| 1055 | // / <param n ame="authT ype">Strin g Authenti cationType </param> | |||||
| 1056 | // / <returns >Supported Authentic atoinProvi derType</r eturns> | |||||
| 1057 | pr ivate Auth entication ProviderTy pe Retriev eAuthentic ationType( String aut hType) | |||||
| 1058 | { | |||||
| 1059 | switch ( authType) | |||||
| 1060 | { | |||||
| 1061 | case "ActiveDi rectory": | |||||
| 1062 | return Aut henticatio nProviderT ype.Active Directory; | |||||
| 1063 | case "LiveId": | |||||
| 1064 | return Aut henticatio nProviderT ype.LiveId ; | |||||
| 1065 | case "Federati on": | |||||
| 1066 | return Aut henticatio nProviderT ype.Federa tion; | |||||
| 1067 | case "OnlineFe deration": | |||||
| 1068 | return Aut henticatio nProviderT ype.Online Federation ; | |||||
| 1069 | defa ult: | |||||
| 1070 | throw new ArgumentEx ception(St ring.Forma t("{0} is not a vali d authenti cation typ e", authTy pe)); | |||||
| 1071 | } | |||||
| 1072 | } | |||||
| 1073 | ||||||
| 1074 | // / <summary > | |||||
| 1075 | // / Parse cr edentials from an XM L node to required C lientCrede ntials dat a type | |||||
| 1076 | // / based on passed Au thenticati onProvider Type. | |||||
| 1077 | // / </summar y> | |||||
| 1078 | // / <param n ame="crede ntials">Cr edential X ML node.</ param> | |||||
| 1079 | // / <param n ame="endpo intType">A uthenticat ionProvide rType of t he credent ial.</para m> | |||||
| 1080 | // / <param n ame="targe t">Target is the key with whic h associat ed credent ials can b e fetched. </param> | |||||
| 1081 | // / <returns >Required ClientCred entials ty pe.</retur ns> | |||||
| 1082 | pr ivate Clie ntCredenti als ParseI nCredentia ls(XElemen t credenti als, Authe nticationP roviderTyp e endpoint Type, Stri ng target) | |||||
| 1083 | { | |||||
| 1084 | ClientCr edentials result = n ew ClientC redentials (); | |||||
| 1085 | if (cred entials.Ha sElements) | |||||
| 1086 | { | |||||
| 1087 | Cred ential cre d = Creden tialManage r.ReadCred entials(ta rget); | |||||
| 1088 | swit ch (endpoi ntType) | |||||
| 1089 | { | |||||
| 1090 | case Authe nticationP roviderTyp e.ActiveDi rectory: | |||||
| 1091 | if (nu ll != cred && cred.U serName.Co ntains("\\ ")) | |||||
| 1092 | { | |||||
| 1093 | St ring[] dom ainAndUser = cred.Us erName.Spl it('\\'); | |||||
| 1094 | re sult.Windo ws.ClientC redential = new Syst em.Net.Net workCreden tial() | |||||
| 1095 | { | |||||
| 1096 | User Name = dom ainAndUser [1], | |||||
| 1097 | Doma in = domai nAndUser[0 ], | |||||
| 1098 | Pass word = cre d.Password | |||||
| 1099 | }; | |||||
| 1100 | } | |||||
| 1101 | else | |||||
| 1102 | { | |||||
| 1103 | re sult.Windo ws.ClientC redential = new Syst em.Net.Net workCreden tial() | |||||
| 1104 | { | |||||
| 1105 | UserName = credent ials.Eleme nt("UserNa me").Value , | |||||
| 1106 | Domain = credentia ls.Element ("Domain") .Value | |||||
| 1107 | }; | |||||
| 1108 | } | |||||
| 1109 | break; | |||||
| 1110 | case Authe nticationP roviderTyp e.LiveId: | |||||
| 1111 | case Authe nticationP roviderTyp e.Federati on: | |||||
| 1112 | case Authe nticationP roviderTyp e.OnlineFe deration: | |||||
| 1113 | if (nu ll != cred ) | |||||
| 1114 | { | |||||
| 1115 | re sult.UserN ame.UserNa me = cred. UserName; | |||||
| 1116 | re sult.UserN ame.Passwo rd = cred. Password; | |||||
| 1117 | } | |||||
| 1118 | else | |||||
| 1119 | { | |||||
| 1120 | re sult.UserN ame.UserNa me = crede ntials.Ele ment("User Name").Val ue; | |||||
| 1121 | } | |||||
| 1122 | break; | |||||
| 1123 | default: | |||||
| 1124 | break; | |||||
| 1125 | } | |||||
| 1126 | } | |||||
| 1127 | else | |||||
| 1128 | retu rn null; | |||||
| 1129 | ||||||
| 1130 | return r esult; | |||||
| 1131 | } | |||||
| 1132 | ||||||
| 1133 | // / <summary > | |||||
| 1134 | // / Parse Cl ientCreden tials into XML node. | |||||
| 1135 | // / </summar y> | |||||
| 1136 | // / <param n ame="clien tCredentia ls">Client Credential s type.</p aram> | |||||
| 1137 | // / <param n ame="endpo intType">A uthenticat ionProvide rType of t he credent ials.</par am> | |||||
| 1138 | // / <param n ame="targe t">Target is the key with whic h associat ed credent ials can b e fetched. </param> | |||||
| 1139 | // / <returns >XML node containing credentia ls data.</ returns> | |||||
| 1140 | pr ivate XEle ment Parse OutCredent ials(Clien tCredentia ls clientC redentials , | |||||
| 1141 | Authenti cationProv iderType e ndpointTyp e, String target) | |||||
| 1142 | { | |||||
| 1143 | if (clie ntCredenti als != nul l) | |||||
| 1144 | { | |||||
| 1145 | Cred ential cre d = Creden tialManage r.ReadCred entials(ta rget); | |||||
| 1146 | swit ch (endpoi ntType) | |||||
| 1147 | { | |||||
| 1148 | case Authe nticationP roviderTyp e.ActiveDi rectory: | |||||
| 1149 | if (cr ed == null ) | |||||
| 1150 | { | |||||
| 1151 | // Add entry in window s credenti al manager for futur e use. | |||||
| 1152 | if (!String. IsNullOrWh iteSpace(c lientCrede ntials.Win dows.Clien tCredentia l.Password )) | |||||
| 1153 | { | |||||
| 1154 | Credenti alManager. WriteCrede ntials(tar get, | |||||
| 1155 | new Credential (clientCre dentials.W indows.Cli entCredent ial.Domain + "\\" | |||||
| 1156 | + clientCr edentials. Windows.Cl ientCreden tial.UserN ame, | |||||
| 1157 | clientCred entials.Wi ndows.Clie ntCredenti al.Passwor d), | |||||
| 1158 | true ); | |||||
| 1159 | } | |||||
| 1160 | } | |||||
| 1161 | else | |||||
| 1162 | { | |||||
| 1163 | // Replace i f the pass word has b een change d. | |||||
| 1164 | if (!clientC redentials .Windows.C lientCrede ntial.Pass word.Equal s(cred.Pas sword)) | |||||
| 1165 | { | |||||
| 1166 | Credenti alManager. DeleteCred entials(ta rget, fals e); | |||||
| 1167 | Credenti alManager. WriteCrede ntials(tar get, | |||||
| 1168 | new Credential (clientCre dentials.W indows.Cli entCredent ial.Domain + "\\" | |||||
| 1169 | + clientCr edentials. Windows.Cl ientCreden tial.UserN ame, | |||||
| 1170 | clientCred entials.Wi ndows.Clie ntCredenti al.Passwor d), | |||||
| 1171 | true ); | |||||
| 1172 | } | |||||
| 1173 | } | |||||
| 1174 | return new XElem ent("Crede ntials", | |||||
| 1175 | ne w XElement ("UserName ", clientC redentials .Windows.C lientCrede ntial.User Name), | |||||
| 1176 | ne w XElement ("Domain", clientCre dentials.W indows.Cli entCredent ial.Domain ) | |||||
| 1177 | ); | |||||
| 1178 | case Authe nticationP roviderTyp e.LiveId: | |||||
| 1179 | case Authe nticationP roviderTyp e.Federati on: | |||||
| 1180 | case Authe nticationP roviderTyp e.OnlineFe deration: | |||||
| 1181 | if (cr ed == null ) | |||||
| 1182 | { | |||||
| 1183 | // Add entry in window s credenti al manager for futur e use. | |||||
| 1184 | if (!String. IsNullOrWh iteSpace(c lientCrede ntials.Use rName.Pass word)) | |||||
| 1185 | { | |||||
| 1186 | Credenti alManager. WriteCrede ntials(tar get, | |||||
| 1187 | new Credential (clientCre dentials.U serName.Us erName, | |||||
| 1188 | clientCred entials.Us erName.Pas sword), | |||||
| 1189 | true ); | |||||
| 1190 | } | |||||
| 1191 | } | |||||
| 1192 | else | |||||
| 1193 | { | |||||
| 1194 | // Replace i f the pass word has b een change d. | |||||
| 1195 | if (!clientC redentials .UserName. Password.E quals(cred .Password) ) | |||||
| 1196 | { | |||||
| 1197 | Credenti alManager. DeleteCred entials(ta rget, fals e); | |||||
| 1198 | Credenti alManager. WriteCrede ntials(tar get, | |||||
| 1199 | new C redential( clientCred entials.Us erName.Use rName, | |||||
| 1200 | c lientCrede ntials.Use rName.Pass word), | |||||
| 1201 | true) ; | |||||
| 1202 | } | |||||
| 1203 | } | |||||
| 1204 | return new XElem ent("Crede ntials", | |||||
| 1205 | new XElement( "UserName" , clientCr edentials. UserName.U serName) | |||||
| 1206 | ); | |||||
| 1207 | default: | |||||
| 1208 | break; | |||||
| 1209 | } | |||||
| 1210 | } | |||||
| 1211 | ||||||
| 1212 | return n ew XElemen t("Credent ials", "") ; | |||||
| 1213 | } | |||||
| 1214 | #e ndregion P rivate met hods | |||||
| 1215 | ||||||
| 1216 | #r egion Priv ate Classe s | |||||
| 1217 | // / <summary > | |||||
| 1218 | // / private static cla ss to stor e constant s required by the Cr mServiceHe lper class . | |||||
| 1219 | // / </summar y> | |||||
| 1220 | pr ivate stat ic class C rmServiceH elperConst ants | |||||
| 1221 | { | |||||
| 1222 | /// <sum mary> | |||||
| 1223 | /// Cred entials fi le path. | |||||
| 1224 | /// </su mmary> | |||||
| 1225 | public s tatic read only strin g ServerCr edentialsF ile = Path .Combine( | |||||
| 1226 | Path .Combine(E nvironment .GetFolder Path(Envir onment.Spe cialFolder .Applicati onData), " CrmServer" ), | |||||
| 1227 | "Cre dentials.x ml"); | |||||
| 1228 | } | |||||
| 1229 | #e ndregion | |||||
| 1230 | } | |||||
| 1231 | ||||||
| 1232 | #regio n Other Cl asses | |||||
| 1233 | intern al sealed class Cred ential | |||||
| 1234 | { | |||||
| 1235 | pr ivate Secu reString _ userName; | |||||
| 1236 | pr ivate Secu reString _ password; | |||||
| 1237 | ||||||
| 1238 | in ternal Cre dential(CR EDENTIAL_S TRUCT cred ) | |||||
| 1239 | { | |||||
| 1240 | _userNam e = Conver tToSecureS tring(cred .userName) ; | |||||
| 1241 | int size = (int)cr ed.credent ialBlobSiz e; | |||||
| 1242 | if (size != 0) | |||||
| 1243 | { | |||||
| 1244 | byte [] bpasswo rd = new b yte[size]; | |||||
| 1245 | Mars hal.Copy(c red.creden tialBlob, bpassword, 0, size); | |||||
| 1246 | _pas sword = Co nvertToSec ureString( Encoding.U nicode.Get String(bpa ssword)); | |||||
| 1247 | } | |||||
| 1248 | else | |||||
| 1249 | { | |||||
| 1250 | _pas sword = Co nvertToSec ureString( String.Emp ty); | |||||
| 1251 | } | |||||
| 1252 | } | |||||
| 1253 | ||||||
| 1254 | pu blic Crede ntial(stri ng userNam e, string password) | |||||
| 1255 | { | |||||
| 1256 | if (Stri ng.IsNullO rWhiteSpac e(userName )) | |||||
| 1257 | thro w new Argu mentNullEx ception("u serName"); | |||||
| 1258 | if (Stri ng.IsNullO rWhiteSpac e(password )) | |||||
| 1259 | thro w new Argu mentNullEx ception("p assword"); | |||||
| 1260 | ||||||
| 1261 | _userNam e = Conver tToSecureS tring(user Name); | |||||
| 1262 | _passwor d = Conver tToSecureS tring(pass word); | |||||
| 1263 | } | |||||
| 1264 | ||||||
| 1265 | pu blic strin g UserName | |||||
| 1266 | { | |||||
| 1267 | get { re turn Conve rtToUnsecu reString(_ userName); } | |||||
| 1268 | } | |||||
| 1269 | ||||||
| 1270 | pu blic strin g Password | |||||
| 1271 | { | |||||
| 1272 | get { re turn Conve rtToUnsecu reString(_ password); } | |||||
| 1273 | } | |||||
| 1274 | ||||||
| 1275 | // / <summary > | |||||
| 1276 | // / This con verts a Se cureString password to plain t ext | |||||
| 1277 | // / </summar y> | |||||
| 1278 | // / <param n ame="secur ePassword" >SecureStr ing passwo rd</param> | |||||
| 1279 | // / <returns >plain tex t password </returns> | |||||
| 1280 | pr ivate stri ng Convert ToUnsecure String(Sec ureString secret) | |||||
| 1281 | { | |||||
| 1282 | if (secr et == null ) | |||||
| 1283 | retu rn string. Empty; | |||||
| 1284 | ||||||
| 1285 | IntPtr u nmanagedSt ring = Int Ptr.Zero; | |||||
| 1286 | try | |||||
| 1287 | { | |||||
| 1288 | unma nagedStrin g = Marsha l.SecureSt ringToGlob alAllocUni code(secre t); | |||||
| 1289 | retu rn Marshal .PtrToStri ngUni(unma nagedStrin g); | |||||
| 1290 | } | |||||
| 1291 | finally | |||||
| 1292 | { | |||||
| 1293 | Mars hal.ZeroFr eeGlobalAl locUnicode (unmanaged String); | |||||
| 1294 | } | |||||
| 1295 | } | |||||
| 1296 | ||||||
| 1297 | // / <summary > | |||||
| 1298 | // / This con verts a st ring to Se cureString | |||||
| 1299 | // / </summar y> | |||||
| 1300 | // / <param n ame="passw ord">plain text pass word</para m> | |||||
| 1301 | // / <returns >SecureStr ing passwo rd</return s> | |||||
| 1302 | pr ivate Secu reString C onvertToSe cureString (string se cret) | |||||
| 1303 | { | |||||
| 1304 | if (stri ng.IsNullO rEmpty(sec ret)) | |||||
| 1305 | retu rn null; | |||||
| 1306 | ||||||
| 1307 | SecureSt ring secur ePassword = new Secu reString() ; | |||||
| 1308 | char[] p asswordCha rs = secre t.ToCharAr ray(); | |||||
| 1309 | foreach (char pwdC har in pas swordChars ) | |||||
| 1310 | { | |||||
| 1311 | secu rePassword .AppendCha r(pwdChar) ; | |||||
| 1312 | } | |||||
| 1313 | securePa ssword.Mak eReadOnly( ); | |||||
| 1314 | return s ecurePassw ord; | |||||
| 1315 | } | |||||
| 1316 | ||||||
| 1317 | ||||||
| 1318 | // / <summary > | |||||
| 1319 | // / 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. | |||||
| 1320 | // / </summar y> | |||||
| 1321 | [S tructLayou t(LayoutKi nd.Sequent ial, CharS et = CharS et.Unicode )] | |||||
| 1322 | in ternal str uct CREDEN TIAL_STRUC T | |||||
| 1323 | { | |||||
| 1324 | public U Int32 flag s; | |||||
| 1325 | public U Int32 type ; | |||||
| 1326 | public s tring targ etName; | |||||
| 1327 | public s tring comm ent; | |||||
| 1328 | public S ystem.Runt ime.Intero pServices. ComTypes.F ILETIME la stWritten; | |||||
| 1329 | public U Int32 cred entialBlob Size; | |||||
| 1330 | public I ntPtr cred entialBlob ; | |||||
| 1331 | public U Int32 pers ist; | |||||
| 1332 | public U Int32 attr ibuteCount ; | |||||
| 1333 | public I ntPtr cred Attribute; | |||||
| 1334 | public s tring targ etAlias; | |||||
| 1335 | public s tring user Name; | |||||
| 1336 | } | |||||
| 1337 | ||||||
| 1338 | } | |||||
| 1339 | ||||||
| 1340 | /// <s ummary> | |||||
| 1341 | /// Th is class e xposes met hods to re ad, write and delete user cred entials | |||||
| 1342 | /// </ summary> | |||||
| 1343 | intern al static class Cred entialMana ger | |||||
| 1344 | { | |||||
| 1345 | // / <summary > | |||||
| 1346 | // / Target N ame agains t which al l credenti als are st ored on th e disk. | |||||
| 1347 | // / </summar y> | |||||
| 1348 | pu blic const string Ta rgetName = "Microsof t_CRMSDK:" ; | |||||
| 1349 | ||||||
| 1350 | // / <summary > | |||||
| 1351 | // / Cache co ntaining s ecrets in- memory (us ed to impr ove perfor mance and avoid IO o perations) . | |||||
| 1352 | // / </summar y> | |||||
| 1353 | pr ivate stat ic Diction ary<string , Credenti al> creden tialCache = new Dict ionary<str ing, Crede ntial>(); | |||||
| 1354 | ||||||
| 1355 | pu blic stati c Uri GetC redentialT arget(Uri target) | |||||
| 1356 | { | |||||
| 1357 | if (null == target ) | |||||
| 1358 | thro w new Argu mentNullEx ception("t arget"); | |||||
| 1359 | return n ew Uri(tar get.GetLef tPart(UriP artial.Aut hority)); | |||||
| 1360 | } | |||||
| 1361 | ||||||
| 1362 | pr ivate enum CRED_TYPE : int | |||||
| 1363 | { | |||||
| 1364 | GENERIC = 1, | |||||
| 1365 | DOMAIN_P ASSWORD = 2, | |||||
| 1366 | DOMAIN_C ERTIFICATE = 3, | |||||
| 1367 | DOMAIN_V ISIBLE_PAS SWORD = 4, | |||||
| 1368 | MAXIMUM = 5 | |||||
| 1369 | } | |||||
| 1370 | ||||||
| 1371 | in ternal enu m CRED_PER SIST : uin t | |||||
| 1372 | { | |||||
| 1373 | SESSION = 1, | |||||
| 1374 | LOCAL_MA CHINE = 2, | |||||
| 1375 | ENTERPRI SE = 3 | |||||
| 1376 | } | |||||
| 1377 | ||||||
| 1378 | pr ivate stat ic class N ativeMetho ds | |||||
| 1379 | { | |||||
| 1380 | [DllImpo rt("advapi 32.dll", S etLastErro r = true, | |||||
| 1381 | Entr yPoint = " CredReadW" , CharSet = CharSet. Unicode)] | |||||
| 1382 | [return: MarshalAs (Unmanaged Type.Bool) ] | |||||
| 1383 | public s tatic exte rn bool Cr edRead(str ing target , CRED_TYP E type, in t reserved Flag, | |||||
| 1384 | [Mar shalAs(Unm anagedType .CustomMar shaler, | |||||
| 1385 | MarshalTyp eRef = typ eof(Creden tialMarsha ler))] out Credentia l credenti al); | |||||
| 1386 | ||||||
| 1387 | [DllImpo rt("Advapi 32.dll", S etLastErro r = true, | |||||
| 1388 | Entr yPoint = " CredWriteW ", CharSet = CharSet .Unicode)] | |||||
| 1389 | [return: MarshalAs (Unmanaged Type.Bool) ] | |||||
| 1390 | public s tatic exte rn bool Cr edWrite(re f Credenti al.CREDENT IAL_STRUCT credentia l, UInt32 flags); | |||||
| 1391 | ||||||
| 1392 | [DllImpo rt("Advapi 32.dll", E ntryPoint = "CredFre e", SetLas tError = t rue)] | |||||
| 1393 | [return: MarshalAs (Unmanaged Type.Bool) ] | |||||
| 1394 | public s tatic exte rn bool Cr edFree(Int Ptr cred); | |||||
| 1395 | ||||||
| 1396 | [DllImpo rt("advapi 32.dll", E ntryPoint = "CredDel eteW", Cha rSet = Cha rSet.Unico de)] | |||||
| 1397 | [return: MarshalAs (Unmanaged Type.Bool) ] | |||||
| 1398 | public s tatic exte rn bool Cr edDelete(s tring targ et, int ty pe, int fl ags); | |||||
| 1399 | } | |||||
| 1400 | ||||||
| 1401 | pr ivate seal ed class C redentialM arshaler : ICustomMa rshaler | |||||
| 1402 | { | |||||
| 1403 | private static Cre dentialMar shaler _in stance; | |||||
| 1404 | ||||||
| 1405 | public v oid CleanU pManagedDa ta(object ManagedObj ) | |||||
| 1406 | { | |||||
| 1407 | // N othing to do since a ll data ca n be garba ge collect ed. | |||||
| 1408 | } | |||||
| 1409 | ||||||
| 1410 | public v oid CleanU pNativeDat a(IntPtr p NativeData ) | |||||
| 1411 | { | |||||
| 1412 | if ( pNativeDat a == IntPt r.Zero) | |||||
| 1413 | { | |||||
| 1414 | return; | |||||
| 1415 | } | |||||
| 1416 | Nati veMethods. CredFree(p NativeData ); | |||||
| 1417 | } | |||||
| 1418 | ||||||
| 1419 | public i nt GetNati veDataSize () | |||||
| 1420 | { | |||||
| 1421 | thro w new NotI mplemented Exception( "The metho d or opera tion is no t implemen ted."); | |||||
| 1422 | } | |||||
| 1423 | ||||||
| 1424 | public I ntPtr Mars halManaged ToNative(o bject obj) | |||||
| 1425 | { | |||||
| 1426 | thro w new NotI mplemented Exception( "Not imple mented yet "); | |||||
| 1427 | } | |||||
| 1428 | ||||||
| 1429 | public o bject Mars halNativeT oManaged(I ntPtr pNat iveData) | |||||
| 1430 | { | |||||
| 1431 | if ( pNativeDat a == IntPt r.Zero) | |||||
| 1432 | { | |||||
| 1433 | return nul l; | |||||
| 1434 | } | |||||
| 1435 | retu rn new Cre dential((C redential. CREDENTIAL _STRUCT)Ma rshal.PtrT oStructure (pNativeDa ta, typeof (Credentia l.CREDENTI AL_STRUCT) )); | |||||
| 1436 | } | |||||
| 1437 | ||||||
| 1438 | ||||||
| 1439 | public s tatic ICus tomMarshal er GetInst ance(strin g cookie) | |||||
| 1440 | { | |||||
| 1441 | if ( null == _i nstance) | |||||
| 1442 | _instance = new Cred entialMars haler(); | |||||
| 1443 | retu rn _instan ce; | |||||
| 1444 | } | |||||
| 1445 | } | |||||
| 1446 | ||||||
| 1447 | pu blic stati c Credenti al ReadCre dentials(S tring targ et) | |||||
| 1448 | { | |||||
| 1449 | Credenti al cachedC redential; | |||||
| 1450 | ||||||
| 1451 | // Try t o read the username from cache | |||||
| 1452 | if (cred entialCach e.TryGetVa lue(Target Name + tar get, out c achedCrede ntial)) | |||||
| 1453 | { | |||||
| 1454 | retu rn cachedC redential; | |||||
| 1455 | } | |||||
| 1456 | ||||||
| 1457 | Credenti al credent ial; | |||||
| 1458 | bool bSu ccess = Na tiveMethod s.CredRead (TargetNam e + target , CRED_TYP E.GENERIC, 0, out cr edential); | |||||
| 1459 | // No ma tch found. | |||||
| 1460 | if (!bSu ccess) | |||||
| 1461 | { | |||||
| 1462 | retu rn null; | |||||
| 1463 | } | |||||
| 1464 | ||||||
| 1465 | credenti alCache[Ta rgetName + target.To String()] = credenti al; | |||||
| 1466 | return c redential; | |||||
| 1467 | } | |||||
| 1468 | ||||||
| 1469 | pu blic stati c Credenti al ReadWin dowsCreden tial(Uri t arget) | |||||
| 1470 | { | |||||
| 1471 | Credenti al credent ial; | |||||
| 1472 | bool bSu ccess = Na tiveMethod s.CredRead (target.Ho st, CRED_T YPE.DOMAIN _PASSWORD, 0, out cr edential); | |||||
| 1473 | if (!bSu ccess) | |||||
| 1474 | { | |||||
| 1475 | thro w new Inva lidOperati onExceptio n("Unable to read wi ndows cred entials fo r Uri {0}. ErrorCode {1}", | |||||
| 1476 | new System .Component Model.Win3 2Exception (Marshal.G etLastWin3 2Error())) ; | |||||
| 1477 | } | |||||
| 1478 | return c redential; | |||||
| 1479 | } | |||||
| 1480 | // / <summary > | |||||
| 1481 | // / Fetches the creden tials. | |||||
| 1482 | // / </summar y> | |||||
| 1483 | // / <param n ame="targe t">Target is the key with whic h associat ed credent ials can b e fetched< /param> | |||||
| 1484 | // / <param n ame="userC redentials ">It is th e in param eter which contains the userna me and pas sword</par am> | |||||
| 1485 | // / <param n ame="allow PhysicalSt ore">If al lowPhysica lStore is true then the creden tials are stored on disk</para m> | |||||
| 1486 | pu blic stati c void Wri teCredenti als(String target, C redential userCreden tials, boo l allowPhy sicalStore ) | |||||
| 1487 | { | |||||
| 1488 | if (Stri ng.IsNullO rWhiteSpac e(target)) | |||||
| 1489 | thro w new Argu mentNullEx ception("t arget"); | |||||
| 1490 | if (null == userCr edentials) | |||||
| 1491 | thro w new Argu mentNullEx ception("u serCredent ials"); | |||||
| 1492 | // Cache the usern ame and pa ssword in memory | |||||
| 1493 | credenti alCache[Ta rgetName + target] = userCrede ntials; | |||||
| 1494 | ||||||
| 1495 | // Store the crede ntials if allowed | |||||
| 1496 | string p asswordToS tore = all owPhysical Store ? us erCredenti als.Passwo rd : strin g.Empty; | |||||
| 1497 | Credenti al.CREDENT IAL_STRUCT credentia l = new Cr edential.C REDENTIAL_ STRUCT(); | |||||
| 1498 | try | |||||
| 1499 | { | |||||
| 1500 | cred ential.tar getName = TargetName + target; | |||||
| 1501 | cred ential.typ e = (UInt3 2)CRED_TYP E.GENERIC; | |||||
| 1502 | cred ential.use rName = us erCredenti als.UserNa me; | |||||
| 1503 | cred ential.att ributeCoun t = 0; | |||||
| 1504 | cred ential.per sist = (UI nt32)CRED_ PERSIST.LO CAL_MACHIN E; | |||||
| 1505 | byte [] bpasswo rd = Encod ing.Unicod e.GetBytes (passwordT oStore); | |||||
| 1506 | cred ential.cre dentialBlo bSize = (U Int32)bpas sword.Leng th; | |||||
| 1507 | cred ential.cre dentialBlo b = Marsha l.AllocCoT askMem(bpa ssword.Len gth); | |||||
| 1508 | Mars hal.Copy(b password, 0, credent ial.creden tialBlob, bpassword. Length); | |||||
| 1509 | if ( !NativeMet hods.CredW rite(ref c redential, 0)) | |||||
| 1510 | { | |||||
| 1511 | throw new System.Com ponentMode l.Win32Exc eption(Mar shal.GetLa stWin32Err or()); | |||||
| 1512 | } | |||||
| 1513 | } | |||||
| 1514 | finally | |||||
| 1515 | { | |||||
| 1516 | if ( IntPtr.Zer o != crede ntial.cred entialBlob ) | |||||
| 1517 | Marshal.Fr eeCoTaskMe m(credenti al.credent ialBlob); | |||||
| 1518 | } | |||||
| 1519 | } | |||||
| 1520 | ||||||
| 1521 | // / <summary > | |||||
| 1522 | // / Deletes the creden tials. | |||||
| 1523 | // / </summar y> | |||||
| 1524 | // / <param n ame="targe t">Target is the key with whic h associat ed credent ials can b e fetched< /param> | |||||
| 1525 | // / <param n ame="softD elete">If a softDele te is done then cred entials ar e deleted only from memory. | |||||
| 1526 | // / They are completel y removed otherwise. </param> | |||||
| 1527 | pu blic stati c void Del eteCredent ials(Strin g target, bool softD elete) | |||||
| 1528 | { | |||||
| 1529 | if (Stri ng.IsNullO rWhiteSpac e(target)) | |||||
| 1530 | thro w new Argu mentNullEx ception("t arget"); | |||||
| 1531 | if (soft Delete) | |||||
| 1532 | { | |||||
| 1533 | // R emoves onl y the pass word | |||||
| 1534 | try | |||||
| 1535 | { | |||||
| 1536 | Credential tempCrede ntial = Re adCredenti als(target ); | |||||
| 1537 | WriteCrede ntials(tar get, new C redential( tempCreden tial.UserN ame, Strin g.Empty), true); | |||||
| 1538 | } | |||||
| 1539 | catc h (Excepti on) | |||||
| 1540 | { | |||||
| 1541 | // Do noth ing | |||||
| 1542 | } | |||||
| 1543 | } | |||||
| 1544 | else | |||||
| 1545 | { | |||||
| 1546 | // R emoves the entry com pletely | |||||
| 1547 | Nati veMethods. CredDelete (TargetNam e + target , (int)CRE D_TYPE.GEN ERIC, 0); | |||||
| 1548 | cred entialCach e.Remove(T argetName + target); | |||||
| 1549 | } | |||||
| 1550 | } | |||||
| 1551 | } | |||||
| 1552 | ||||||
| 1553 | /// <s ummary> | |||||
| 1554 | /// Wr apper clas s for Disc overyServi ceProxy to support a uto refres h security token. | |||||
| 1555 | /// </ summary> | |||||
| 1556 | intern al sealed class Mana gedTokenDi scoverySer viceProxy : Discover yServicePr oxy | |||||
| 1557 | { | |||||
| 1558 | pr ivate Auto RefreshSec urityToken <Discovery ServicePro xy, IDisco veryServic e> _proxyM anager; | |||||
| 1559 | ||||||
| 1560 | pu blic Manag edTokenDis coveryServ iceProxy(U ri service Uri, Clien tCredentia ls userCre dentials) | |||||
| 1561 | : base(s erviceUri, null, use rCredentia ls, null) | |||||
| 1562 | { | |||||
| 1563 | this._pr oxyManager = new Aut oRefreshSe curityToke n<Discover yServicePr oxy, IDisc overyServi ce>(this); | |||||
| 1564 | } | |||||
| 1565 | ||||||
| 1566 | pu blic Manag edTokenDis coveryServ iceProxy(I ServiceMan agement<ID iscoverySe rvice> ser viceManage ment, | |||||
| 1567 | Security TokenRespo nse securi tyTokenRes ) | |||||
| 1568 | : base(s erviceMana gement, se curityToke nRes) | |||||
| 1569 | { | |||||
| 1570 | this._pr oxyManager = new Aut oRefreshSe curityToke n<Discover yServicePr oxy, IDisc overyServi ce>(this); | |||||
| 1571 | } | |||||
| 1572 | ||||||
| 1573 | pu blic Manag edTokenDis coveryServ iceProxy(I ServiceMan agement<ID iscoverySe rvice> ser viceManage ment, | |||||
| 1574 | ClientCre dentials u serCredent ials) | |||||
| 1575 | : base(s erviceMana gement, us erCredenti als) | |||||
| 1576 | { | |||||
| 1577 | this._pr oxyManager = new Aut oRefreshSe curityToke n<Discover yServicePr oxy, IDisc overyServi ce>(this); | |||||
| 1578 | } | |||||
| 1579 | ||||||
| 1580 | pr otected ov erride Sec urityToken Response A uthenticat eDeviceCor e() | |||||
| 1581 | { | |||||
| 1582 | return t his._proxy Manager.Au thenticate Device(); | |||||
| 1583 | } | |||||
| 1584 | ||||||
| 1585 | pr otected ov erride voi d Authenti cateCore() | |||||
| 1586 | { | |||||
| 1587 | this._pr oxyManager .PrepareCr edentials( ); | |||||
| 1588 | base.Aut henticateC ore(); | |||||
| 1589 | } | |||||
| 1590 | ||||||
| 1591 | pr otected ov erride voi d Validate Authentica tion() | |||||
| 1592 | { | |||||
| 1593 | this._pr oxyManager .RenewToke nIfRequire d(); | |||||
| 1594 | base.Val idateAuthe ntication( ); | |||||
| 1595 | } | |||||
| 1596 | } | |||||
| 1597 | ||||||
| 1598 | /// <s ummary> | |||||
| 1599 | /// Wr apper clas s for Orga nizationSe rviceProxy to suppor t auto ref resh secur ity token | |||||
| 1600 | /// </ summary> | |||||
| 1601 | intern al sealed class Mana gedTokenOr ganization ServicePro xy : Organ izationSer viceProxy | |||||
| 1602 | { | |||||
| 1603 | pr ivate Auto RefreshSec urityToken <Organizat ionService Proxy, IOr ganization Service> _ proxyManag er; | |||||
| 1604 | ||||||
| 1605 | pu blic Manag edTokenOrg anizationS erviceProx y(Uri serv iceUri, Cl ientCreden tials user Credential s) | |||||
| 1606 | : base(s erviceUri, null, use rCredentia ls, null) | |||||
| 1607 | { | |||||
| 1608 | this._pr oxyManager = new Aut oRefreshSe curityToke n<Organiza tionServic eProxy, IO rganizatio nService>( this); | |||||
| 1609 | } | |||||
| 1610 | ||||||
| 1611 | pu blic Manag edTokenOrg anizationS erviceProx y(IService Management <IOrganiza tionServic e> service Management , | |||||
| 1612 | Security TokenRespo nse securi tyTokenRes ) | |||||
| 1613 | : base(s erviceMana gement, se curityToke nRes) | |||||
| 1614 | { | |||||
| 1615 | this._pr oxyManager = new Aut oRefreshSe curityToke n<Organiza tionServic eProxy, IO rganizatio nService>( this); | |||||
| 1616 | } | |||||
| 1617 | ||||||
| 1618 | pu blic Manag edTokenOrg anizationS erviceProx y(IService Management <IOrganiza tionServic e> service Management , | |||||
| 1619 | ClientCr edentials userCreden tials) | |||||
| 1620 | : base(s erviceMana gement, us erCredenti als) | |||||
| 1621 | { | |||||
| 1622 | this._pr oxyManager = new Aut oRefreshSe curityToke n<Organiza tionServic eProxy, IO rganizatio nService>( this); | |||||
| 1623 | } | |||||
| 1624 | ||||||
| 1625 | pr otected ov erride Sec urityToken Response A uthenticat eDeviceCor e() | |||||
| 1626 | { | |||||
| 1627 | return t his._proxy Manager.Au thenticate Device(); | |||||
| 1628 | } | |||||
| 1629 | ||||||
| 1630 | pr otected ov erride voi d Authenti cateCore() | |||||
| 1631 | { | |||||
| 1632 | this._pr oxyManager .PrepareCr edentials( ); | |||||
| 1633 | base.Aut henticateC ore(); | |||||
| 1634 | } | |||||
| 1635 | ||||||
| 1636 | pr otected ov erride voi d Validate Authentica tion() | |||||
| 1637 | { | |||||
| 1638 | this._pr oxyManager .RenewToke nIfRequire d(); | |||||
| 1639 | base.Val idateAuthe ntication( ); | |||||
| 1640 | } | |||||
| 1641 | } | |||||
| 1642 | ||||||
| 1643 | /// <s ummary> | |||||
| 1644 | /// Cl ass that w raps acqui ring the s ecurity to ken for a service | |||||
| 1645 | /// </ summary> | |||||
| 1646 | public sealed cl ass AutoRe freshSecur ityToken<T Proxy, TSe rvice> | |||||
| 1647 | wh ere TProxy : Service Proxy<TSer vice> | |||||
| 1648 | wh ere TServi ce : class | |||||
| 1649 | { | |||||
| 1650 | pr ivate Clie ntCredenti als _devic eCredentia ls; | |||||
| 1651 | pr ivate TPro xy _proxy; | |||||
| 1652 | ||||||
| 1653 | // / <summary > | |||||
| 1654 | // / Instanti ates an in stance of the proxy class | |||||
| 1655 | // / </summar y> | |||||
| 1656 | // / <param n ame="proxy ">Proxy th at will be used to a uthenticat e the user </param> | |||||
| 1657 | pu blic AutoR efreshSecu rityToken( TProxy pro xy) | |||||
| 1658 | { | |||||
| 1659 | if (null == proxy) | |||||
| 1660 | { | |||||
| 1661 | thro w new Argu mentNullEx ception("p roxy"); | |||||
| 1662 | } | |||||
| 1663 | ||||||
| 1664 | this._pr oxy = prox y; | |||||
| 1665 | } | |||||
| 1666 | ||||||
| 1667 | // / <summary > | |||||
| 1668 | // / Prepares authentic ation befo re authen6 ticated | |||||
| 1669 | // / </summar y> | |||||
| 1670 | pu blic void PrepareCre dentials() | |||||
| 1671 | { | |||||
| 1672 | if (null == this._ proxy.Clie ntCredenti als) | |||||
| 1673 | { | |||||
| 1674 | retu rn; | |||||
| 1675 | } | |||||
| 1676 | ||||||
| 1677 | switch ( this._prox y.ServiceC onfigurati on.Authent icationTyp e) | |||||
| 1678 | { | |||||
| 1679 | case Authentic ationProvi derType.Ac tiveDirect ory: | |||||
| 1680 | this._prox y.ClientCr edentials. UserName.U serName = null; | |||||
| 1681 | this._prox y.ClientCr edentials. UserName.P assword = null; | |||||
| 1682 | break; | |||||
| 1683 | case Authentic ationProvi derType.Fe deration: | |||||
| 1684 | case Authentic ationProvi derType.Li veId: | |||||
| 1685 | this._prox y.ClientCr edentials. Windows.Cl ientCreden tial = nul l; | |||||
| 1686 | break; | |||||
| 1687 | defa ult: | |||||
| 1688 | return; | |||||
| 1689 | } | |||||
| 1690 | } | |||||
| 1691 | ||||||
| 1692 | // / <summary > | |||||
| 1693 | // / Authenti cates the device tok en | |||||
| 1694 | // / </summar y> | |||||
| 1695 | // / <returns >Generated SecurityT okenRespon se for the device</r eturns> | |||||
| 1696 | pu blic Secur ityTokenRe sponse Aut henticateD evice() | |||||
| 1697 | { | |||||
| 1698 | if (null == this._ deviceCred entials) | |||||
| 1699 | { | |||||
| 1700 | this ._deviceCr edentials = DeviceId Manager.Lo adOrRegist erDevice( | |||||
| 1701 | this._prox y.ServiceC onfigurati on.Current Issuer.Iss uerAddress .Uri); | |||||
| 1702 | } | |||||
| 1703 | ||||||
| 1704 | return t his._proxy .ServiceCo nfiguratio n.Authenti cateDevice (this._dev iceCredent ials); | |||||
| 1705 | } | |||||
| 1706 | ||||||
| 1707 | // / <summary > | |||||
| 1708 | // / Renews t he token ( if it is n ear expira tion or ha s expired) | |||||
| 1709 | // / </summar y> | |||||
| 1710 | pu blic void RenewToken IfRequired () | |||||
| 1711 | { | |||||
| 1712 | if (null != this._ proxy.Secu rityTokenR esponse && | |||||
| 1713 | Date Time.UtcNo w.AddMinut es(15) >= this._prox y.Security TokenRespo nse.Respon se.Lifetim e.Expires) | |||||
| 1714 | { | |||||
| 1715 | try | |||||
| 1716 | { | |||||
| 1717 | this._prox y.Authenti cate(); | |||||
| 1718 | } | |||||
| 1719 | catc h (Communi cationExce ption) | |||||
| 1720 | { | |||||
| 1721 | if (null = = this._pr oxy.Securi tyTokenRes ponse || | |||||
| 1722 | DateTi me.UtcNow >= this._p roxy.Secur ityTokenRe sponse.Res ponse.Life time.Expir es) | |||||
| 1723 | { | |||||
| 1724 | throw; | |||||
| 1725 | } | |||||
| 1726 | ||||||
| 1727 | // Ignore the except ion | |||||
| 1728 | } | |||||
| 1729 | } | |||||
| 1730 | } | |||||
| 1731 | } | |||||
| 1732 | #endre gion | |||||
| 1733 | } | |||||
| 1734 | //</snippe tCrmServic eHelper> |
Araxis Merge (but not the data content of this report) is Copyright © 1993-2016 Araxis Ltd (www.araxis.com). All rights reserved.